diff --git a/.gitignore b/.gitignore index c72191ba4..2c4269fe0 100644 --- a/.gitignore +++ b/.gitignore @@ -97,3 +97,4 @@ BuildTools/macosx/temp1/boost_1_57_0/b2 *.plist .vs/slnx.sqlite +BuildTools/temp/CLAPACK-3.1.1-VisualStudio/BLAS/blas.vcproj diff --git a/Algorithms/DataUtils.h b/Algorithms/DataUtils.h new file mode 100644 index 000000000..dd099d1ef --- /dev/null +++ b/Algorithms/DataUtils.h @@ -0,0 +1,518 @@ + + +#ifndef __GEODA_CENTER_DATAUTILS_H +#define __GEODA_CENTER_DATAUTILS_H + +#include +#include +#include +#include +#include +#include +#include // std::max + +#include "../GdaConst.h" +#include "../ShapeOperations/GalWeight.h" +using namespace std; + +class DataUtils { +public: + static double ManhattanDistance(double* x1, double* x2, size_t size) + { + double d =0; + for (size_t i =0; i >& matrix) + { + int n = matrix[0].size(); + int k = matrix.size(); + + for (int j = 0; j < k; j++) { + double avg = 0.0; + for (int i = 0; i < n; i++) avg += matrix[j][i]; + avg /= n; + for (int i = 0; i < n; i++) matrix[j][i] -= avg; + } + + for (int i = 0; i < n; i++) { + double avg = 0.0; + for (int j = 0; j < k; j++) avg += matrix[j][i]; + avg /= k; + for (int j = 0; j < k; j++) matrix[j][i] -= avg; + } + } + + static void multiply(vector >& matrix, double factor) + { + int n = matrix[0].size(); + int k = matrix.size(); + for (int i = 0; i < k; i++) { + for (int j = 0; j < n; j++) { + matrix[i][j] *= factor; + } + } + } + + static void squareEntries(vector >& matrix) + { + int n = matrix[0].size(); + int k = matrix.size(); + for (int i = 0; i < k; i++) { + for (int j = 0; j < n; j++) { + matrix[i][j] = pow(matrix[i][j], 2.0); + } + } + } + + static double prod(vector x, vector y) { + int n = x.size(); + double val = 0; + for (int i=0; i& x) { + double norm = sqrt(prod(x, x)); + for (int i = 0; i < x.size(); i++) x[i] /= norm; + return norm; + } + + static void normalize(vector >& x) + { + for (int i = 0; i < x.size(); i++) normalize(x[i]); + } + + static void eigen(vector >& matrix, vector >& evecs, vector& evals, int maxiter) { + + if ( GdaConst::use_gda_user_seed) { + srand(GdaConst::gda_user_seed); + } + + int d = evals.size(); + int k = matrix.size(); + //double eps = 1.0E-10; + double eps = GdaConst::gda_eigen_tol; + for (int m = 0; m < d; m++) { + if (m > 0) + for (int i = 0; i < k; i++) + for (int j = 0; j < k; j++) + matrix[i][j] -= evals[(m - 1)] * evecs[(m - 1)][i] * evecs[(m - 1)][j]; + for (int i = 0; i < k; i++) + evecs[m][i] = (double) rand() / RAND_MAX; + normalize(evecs[m]); + + double r = 0.0; + + for (int iter = 0; (fabs(1.0 - r) > eps) && (iter < maxiter); iter++) { + //for (int iter = 0; iter < maxiter; iter++) { + vector q(k,0); + for (int i = 0; i < k; i++) { + for (int j = 0; j < k; j++) + q[i] += matrix[i][j] * evecs[m][j]; + } + evals[m] = prod(evecs[m], q); + normalize(q); + r = abs(prod(evecs[m], q)); + evecs[m] = q; + } + } + } + + static void reverse_eigen(vector >& matrix, vector >& evecs, vector& evals, int maxiter) { + + if ( GdaConst::use_gda_user_seed) { + srand(GdaConst::gda_user_seed); + } + double rho = largestEigenvalue(matrix); + int d = evals.size(); + int k = matrix.size(); + double eps = 1.0E-6; + for (int m = 0; m < d; m++) { + if (m > 0) + for (int i = 0; i < k; i++) + for (int j = 0; j < k; j++) + matrix[i][j] -= evals[(m - 1)] * evecs[(m - 1)][i] * evecs[(m - 1)][j]; + for (int i = 0; i < k; i++) + evecs[m][i] = (double) rand() / RAND_MAX; + normalize(evecs[m]); + + double r = 0.0; + + for (int iter = 0; (fabs(1.0 - r) > eps) && (iter < maxiter); iter++) { + vector q(k,0); + for (int i = 0; i < k; i++) { + q[i] -= rho * evecs[m][i]; + for (int j = 0; j < k; j++) + q[i] += matrix[i][j] * evecs[m][j]; + } + evals[m] = prod(evecs[m], q); + normalize(q); + r = abs(prod(evecs[m], q)); + evecs[m] = q; + } + } + } + + static double smallestEigenvalue(vector >& matrix) + { + int n = matrix.size(); + double rho = largestEigenvalue(matrix); + double eps = 1.0E-6; + int maxiter = 100; + double lambda = 0.0; + vector x(n); + for (int i = 0; i < n; i++) + x[i] = (0.5 - (double) rand() / RAND_MAX); + normalize(x); + + double r = 0.0; + + for (int iter = 0; (abs(1.0 - r) > eps) && (iter < 100); iter++) { + vector q(n,0); + + for (int i = 0; i < n; i++) { + q[i] -= rho * x[i]; + for (int j = 0; j < n; j++) + q[i] += matrix[i][j] * x[j]; + } + lambda = prod(x, q); + normalize(q); + r = fabs(prod(x, q)); + x = q; + } + return lambda + rho; + } + + static double largestEigenvalue(vector >& matrix) + { + int n = matrix.size(); + double eps = 1.0E-6; + int maxiter = 100; + double lambda = 0.0; + vector x(n,1.0); + double r = 0.0; + + for (int iter = 0; (fabs(1.0 - r) > eps) && (iter < 100); iter++) { + vector q(n,0); + + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) + q[i] += matrix[i][j] * x[j]; + } + lambda = prod(x, q); + normalize(q); + r = fabs(prod(x, q)); + x = q; + } + return lambda; + } + + static void randomize(vector >& matrix) { + if ( GdaConst::use_gda_user_seed) { + srand(GdaConst::gda_user_seed); + } + int k = matrix.size(); + int n = matrix[0].size(); + for (int i = 0; i < k; i++) { + for (int j = 0; j < n; j++) { + matrix[i][j] = (double) rand() / RAND_MAX; + } + } + } + + static vector landmarkIndices(vector >& matrix) { + int k = matrix.size(); + int n = matrix[0].size(); + vector result(k); + for (int i = 0; i < k; i++) { + for (int j = 0; j < n; j++) { + if (matrix[i][j] == 0.0) { + result[i] = j; + } + } + } + return result; + } + + static vector > copyMatrix(vector >& matrix) { + int k = matrix.size(); + int n = matrix[0].size(); + vector > copy(k); + + for (int i = 0; i < k; i++) { + copy[i].resize(n); + for (int j = 0; j < n; j++) { + copy[i][j] = matrix[i][j]; + } + } + return copy; + } + + static double** fullRaggedMatrix(double** matrix, int n, int k, bool isSqrt=false) { + double** copy = new double*[k]; + + for (int i = 0; i < k; i++) { + copy[i] = new double[n]; + for (int j = 0; j < n; j++) + copy[i][j] = 0; + } + + for (int i = 1; i < k; i++) { + for (int j = 0; j < i; j++) { + if (isSqrt) copy[i][j] = sqrt(matrix[i][j]); + copy[i][j] = matrix[i][j]; + copy[j][i] = copy[i][j]; + } + } + + return copy; + } + + // upper triangular part of a symmetric matrix + static double* getPairWiseDistance(double** matrix, int n, int k, double dist(double* , double* , size_t)) + { + unsigned long long _n = n; + + unsigned long long cnt = 0; + unsigned long long nn = _n*(_n-1)/2; + double* result = new double[nn]; + for (int i=0; i > copyRaggedMatrix(double** matrix, int n, int k) { + vector > copy(k); + + for (int i = 0; i < k; i++) { + copy[i].resize(n); + for (int j = 0; j < n; j++) + copy[i][j] = 0; + } + + for (int i = 1; i < k; i++) { + for (int j = 0; j < i; j++) { + copy[i][j] = matrix[i][j]; + copy[j][i] = matrix[i][j]; + } + } + + return copy; + } + + static void selfprod(vector >& d, vector >& result) + { + int k = d.size(); + int n = d[0].size(); + for (int i = 0; i < k; i++) { + for (int j = 0; j <= i; j++) { + double sum = 0.0; + for (int m = 0; m < n; m++) sum += d[i][m] * d[j][m]; + result[i][j] = sum; + result[j][i] = sum; + } + } + } + + static void svd(vector >& matrix, vector >& svecs, vector& svals, int maxiter=100) + { + int k = matrix.size(); + int n = matrix[0].size(); + int d = svecs.size(); + + for (int m = 0; m < d; m++) svals[m] = normalize(svecs[m]); + vector > K(k); + for (int i=0; i > temp(d); + for (int i=0; i > tempOld(d); + for (int i=0; i > landmarkMatrix(vector >& matrix) + { + int k = matrix.size(); + int n = matrix[0].size(); + + vector > result(k); + for (int i=0; i index = landmarkIndices(matrix); + for (int i = 0; i < k; i++) { + for (int j = 0; j < k; j++) { + result[i][j] = matrix[i][index[j]]; + } + } + return result; + } + + /* + static vector > pivotRows(vector >& matrix, int k) + { + int K = matrix.size(); + if (k >= K) { + return matrix; + } + int n = matrix[0].size(); + //System.out.println(n + " " + k + " " + K); + vector > result(k); + for (int i=0; i _min(n); + for (int i = 0; i < n; i++) + _min[i] = DBL_MAX; + for (int i = 0; i < k; i++) { + int argmax = 0; + for (int j = 0; j < n; j++) { + result[i][j] = matrix[i][pivot]; + _min[j] = std::min(_min[j], result[i][j]); + if (_min[j] > _min[argmax]) { + argmax = j; + } + } + pivot = argmax; + } + return result; + }*/ + + static void scale(vector >& x, vector >& D) + { + int n = x[0].size(); + int d = x.size(); + double xysum = 0.0; + double dsum = 0.0; + for (int i = 0; i < n; i++) { + for (int j = 0; j < i; j++) { + double dxy = 0.0; + for (int k = 0; k < d; k++) dxy += pow(x[k][i]-x[k][j], 2.0); + xysum += sqrt(dxy); + dsum += D[i][j]; + } + } + dsum /= xysum; + for (int i = 0; i < n; i++) { + for (int k = 0; k < d; k++) x[k][i] *= dsum; + } + } + + /* + static vector > maxminPivotMatrix(vector >& matrix, int k) + { + int n = matrix[0].size(); + vector > result(k); + for (int i=0; i min(n); + for (int i = 0; i < n; i++) min[i] = DBL_MAX; + for (int i = 0; i < k; i++) { + for (int j = 0; j < n; j++) { + result[i][j] = distance(matrix, pivot, j); + } + pivot = 0; + for (int j = 0; j < n; j++) { + min[j] = std::min(min[j], result[i][j]); + if (min[j] > min[pivot]) pivot = j; + } + } + return result; + } + + static vector > randomPivotMatrix(vector >& matrix, int k) + { + int n = matrix[0].size(); + vector > result(k); + for (int i=0; i +#include #include #include @@ -43,6 +45,12 @@ void setrandomstate(int seed) random_state = seed; } +void resetrandom() +{ + reset_random = 1; + uniform(); +} + /* ************************************************************************ */ #ifdef WINDOWS @@ -1004,10 +1012,9 @@ Otherwise, the distance between two columns in the matrix is calculated. } } if (!tweight) return 0; /* usually due to empty clusters */ - //result /= tweight; - // squared - return result; + //return sqrt(result); + return result; } /* ********************************************************************* */ @@ -1082,8 +1089,8 @@ Otherwise, the distance between two columns in the matrix is calculated. } } if (!tweight) return 0; /* usually due to empty clusters */ - result /= tweight; - return result; + //result /= tweight; + return sqrt(result); } /* ********************************************************************* */ @@ -1773,7 +1780,7 @@ A double-precison number between 0.0 and 1.0. static int s1 = 0; static int s2 = 0; - if (s1==0 || s2==0) /* initialize */ + if (s1==0 || s2==0 || reset_random==1) /* initialize */ { if (random_state<0) { unsigned int initseed = (unsigned int) time(0); srand(initseed); @@ -1782,6 +1789,7 @@ A double-precison number between 0.0 and 1.0. } s1 = rand(); s2 = rand(); + reset_random = 0; } do @@ -1799,9 +1807,34 @@ A double-precison number between 0.0 and 1.0. return z*scale; } +double uniform(int& s1, int& s2) +{ + if (s1 == 0 || s2 == 0) + return uniform(); + + int z; + static const int m1 = 2147483563; + static const int m2 = 2147483399; + const double scale = 1.0/m1; + + do + { int k; + k = s1/53668; + s1 = 40014*(s1-k*53668)-k*12211; + if (s1 < 0) s1+=m1; + k = s2/52774; + s2 = 40692*(s2-k*52774)-k*3791; + if(s2 < 0) s2+=m2; + z = s1-s2; + if(z < 1) z+=(m1-1); + } while (z==m1); /* To avoid returning 1.0 */ + + return z*scale; +} + /* ************************************************************************ */ -static int binomial(int n, double p) +static int binomial(int n, double p, int& s1, int& s2) /* Purpose ======= @@ -1839,7 +1872,7 @@ An integer drawn from a binomial distribution with parameters (p, n). const double a = (n+1)*s; double r = exp(n*log(q)); /* pow() causes a crash on AIX */ int x = 0; - double u = uniform(); + double u = uniform(s1, s2); while(1) { if (u < r) return x; u-=r; @@ -1867,8 +1900,8 @@ An integer drawn from a binomial distribution with parameters (p, n). { /* Step 1 */ int y; int k; - double u = uniform(); - double v = uniform(); + double u = uniform(s1, s2); + double v = uniform(s1, s2); u *= p4; if (u <= p1) return (int)(xm-p1*v+u); /* Step 2 */ @@ -1975,7 +2008,7 @@ nearest(int d_idx, int n_cluster, double *d2, } static void kplusplusassign (int nclusters, int ndata, int nelements, int clusterid[], double** data, double** cdata, int** mask, int** cmask, - double weight[], int transpose, char dist) + double weight[], int transpose, char dist, int& s1, int& s2) { /* Set the metric function as indicated by dist */ double (*metric) @@ -1996,7 +2029,9 @@ static void kplusplusassign (int nclusters, int ndata, int nelements, int cluste int* cand_center_index = (int*)malloc(sizeof(int) * n_local_trials); // random pick first center - int idx = (int) (uniform() * nelements); + int idx; + if (s1==0 || s2==0) idx = (int) (uniform() * nelements); + else idx = (int) (uniform(s1, s2) * nelements); for ( j=0; j 0) { + _s1 = s1 + ipass; + _s2 = _s1; + } + for (i = 0; i < nelements; i++) uniform(_s1, _s2); + if (method == 0) { /* Perform the EM algorithm. First, randomly assign elements to clusters. */ //if (npass!=0) - randomassign (nclusters, nelements, tclusterid); + randomassign (nclusters, nelements, tclusterid, _s1, _s2); } else { /* Perform the kmeans++ algorithm: finding init centers */ - kplusplusassign(nclusters,ndata,nelements,tclusterid,data,cdata,mask,cmask,weight,transpose,dist); + kplusplusassign(nclusters,ndata,nelements,tclusterid,data,cdata,mask,cmask,weight,transpose,dist, _s1, _s2); } for (i = 0; i < nclusters; i++) counts[i] = 0; @@ -2564,9 +2610,11 @@ kmeans(int nclusters, int nrows, int ncolumns, double** data, int** mask, } total += distance; } + if (total>=previous) break; /* total>=previous is FALSE on some machines even if total and previous * are bitwise identical. */ + for (i = 0; i < nelements; i++) if (saved[i]!=tclusterid[i]) break; if (i==nelements) @@ -2577,7 +2625,22 @@ kmeans(int nclusters, int nrows, int ncolumns, double** data, int** mask, { *error = total; break; } - +//////////////////////////////////////////// + if (min_bound > 0) { + for (j = 0; j < nclusters; j++) bounds[j] = 0; + for (j = 0; j < nelements; j++) bounds[tclusterid[j]] += bound_vals[j]; + bool not_good = false; + for (j = 0; j < nclusters; j++) + { + if (bounds[j] < min_bound) { + not_good = true; + break; + } + } + if (not_good) + continue; + } +//////////////////////////////////////////// for (i = 0; i < nclusters; i++) mapping[i] = -1; for (i = 0; i < nelements; i++) { j = tclusterid[i]; @@ -2593,8 +2656,10 @@ kmeans(int nclusters, int nrows, int ncolumns, double** data, int** mask, } } if (i==nelements) ifound++; /* break statement not encountered */ + } while (++ipass < npass); + free(bounds); free(saved); return ifound; } @@ -2605,7 +2670,7 @@ static int kmedians(int nclusters, int nrows, int ncolumns, double** data, int** mask, double weight[], int transpose, int npass, int n_maxiter, char dist, double** cdata, int** cmask, int clusterid[], double* error, - int tclusterid[], int counts[], int mapping[], double cache[]) + int tclusterid[], int counts[], int mapping[], double cache[], double bound_vals[], double min_bound, int s1, int s2) { int i, j, k; const int nelements = (transpose==0) ? nrows : ncolumns; const int ndata = (transpose==0) ? ncolumns : nrows; @@ -2621,14 +2686,23 @@ kmedians(int nclusters, int nrows, int ncolumns, double** data, int** mask, if (saved==NULL) return -1; *error = DBL_MAX; - + double* bounds = (double*)malloc(nclusters*sizeof(double)); + do { double total = DBL_MAX; int counter = 0; int period = 10; - + int _s1 = 0; + int _s2 = 0; + if (s1 > 0) { + _s1 = s1 + ipass; + _s2 = _s1; + } + for (i = 0; i < nelements; i++) uniform(_s1, _s2); + + /* Perform the EM algorithm. First, randomly assign elements to clusters. */ - if (npass!=0) randomassign (nclusters, nelements, tclusterid); + if (npass!=0) randomassign (nclusters, nelements, tclusterid, _s1, _s2); for (i = 0; i < nclusters; i++) counts[i]=0; for (i = 0; i < nelements; i++) counts[tclusterid[i]]++; @@ -2684,7 +2758,22 @@ kmedians(int nclusters, int nrows, int ncolumns, double** data, int** mask, { *error = total; break; } - + //////////////////////////////////////////// + if (min_bound > 0) { + for (j = 0; j < nclusters; j++) bounds[j] = 0; + for (j = 0; j < nelements; j++) bounds[tclusterid[j]] += bound_vals[j]; + bool not_good = false; + for (j = 0; j < nclusters; j++) + { + if (bounds[j] < min_bound) { + not_good = true; + break; + } + } + if (not_good) + continue; + } + //////////////////////////////////////////// for (i = 0; i < nclusters; i++) mapping[i] = -1; for (i = 0; i < nelements; i++) { j = tclusterid[i]; @@ -2702,16 +2791,21 @@ kmedians(int nclusters, int nrows, int ncolumns, double** data, int** mask, if (i==nelements) ifound++; /* break statement not encountered */ } while (++ipass < npass); + free(bounds); free(saved); return ifound; } +void test(int nclusters, int nrows, int ncolumns, double** data, int** mask, double weight[], int transpose, int npass, int n_maxiter, char a) +{ + +} /* ********************************************************************* */ void kcluster (int nclusters, int nrows, int ncolumns, double** data, int** mask, double weight[], int transpose, int npass, int n_maxiter, char method, char dist, - int clusterid[], double* error, int* ifound) + int clusterid[], double* error, int* ifound, double bound_vals[], double min_bound, int s1, int s2) /* Purpose ======= @@ -2854,7 +2948,7 @@ number of clusters is larger than the number of elements being clustered, if(cache) { *ifound = kmedians(nclusters, nrows, ncolumns, data, mask, weight, transpose, npass, n_maxiter, dist, cdata, cmask, clusterid, error, - tclusterid, counts, mapping, cache); + tclusterid, counts, mapping, cache, bound_vals, min_bound, s1, s2); free(cache); } } @@ -2862,11 +2956,11 @@ number of clusters is larger than the number of elements being clustered, /* kmeans but with KMeans++ algorithm*/ *ifound = kmeans(nclusters, nrows, ncolumns, data, mask, weight, transpose, 1, npass, n_maxiter, dist, cdata, cmask, clusterid, error, - tclusterid, counts, mapping); + tclusterid, counts, mapping, bound_vals, min_bound, s1, s2); else *ifound = kmeans(nclusters, nrows, ncolumns, data, mask, weight, transpose, 0, npass, n_maxiter, dist, cdata, cmask, clusterid, error, - tclusterid, counts, mapping); + tclusterid, counts, mapping, bound_vals, min_bound, s1, s2); /* Deallocate temporarily used space */ if (npass > 1) @@ -2883,7 +2977,7 @@ number of clusters is larger than the number of elements being clustered, /* *********************************************************************** */ void kmedoids (int nclusters, int nelements, double** distmatrix, - int npass, int clusterid[], double* error, int* ifound) + int npass, int clusterid[], double* error, int* ifound, double bound_vals[], double min_bound, int s1, int s2) /* Purpose ======= @@ -2981,14 +3075,23 @@ to 0. If kmedoids fails due to a memory allocation error, ifound is set to -1. return; } } - + double* bounds = (double*)malloc(nclusters*sizeof(double)); *error = DBL_MAX; do /* Start the loop */ { double total = DBL_MAX; int counter = 0; int period = 10; - - if (npass!=0) randomassign (nclusters, nelements, tclusterid); + + int _s1 = 0; + int _s2 = 0; + if (s1 > 0) { + _s1 = s1 + ipass; + _s2 = _s1; + } + for (i = 0; i < nelements; i++) uniform(_s1, _s2); + + if (npass!=0) + randomassign (nclusters, nelements, tclusterid, _s1, _s2); while(1) { double previous = total; total = 0.0; @@ -3031,6 +3134,22 @@ to 0. If kmedoids fails due to a memory allocation error, ifound is set to -1. break; /* Identical solution found; break out of this loop */ } + //////////////////////////////////////////// + if (min_bound > 0) { + for (j = 0; j < nclusters; j++) bounds[j] = 0; + for (j = 0; j < nelements; j++) bounds[tclusterid[j]] += bound_vals[j]; + bool not_good = false; + for (j = 0; j < nclusters; j++) + { + if (bounds[j] < min_bound) { + not_good = true; + break; + } + } + if (not_good) + continue; + } + //////////////////////////////////////////// for (i = 0; i < nelements; i++) { if (clusterid[i]!=centroids[tclusterid[i]]) { if (total < *error) @@ -3049,6 +3168,7 @@ to 0. If kmedoids fails due to a memory allocation error, ifound is set to -1. /* Deallocate temporarily used space */ if (npass > 1) free(tclusterid); + free(bounds); free(saved); free(centroids); free(errors); @@ -4752,3 +4872,131 @@ when microarrays are being clustered. /* Never get here */ return -2.0; } + +/* ******************************************************************** */ + +double** mds(int nrows, int ncolumns, double** data, int** mask, + double weight[], int transpose, char dist, double** distmatrix, int low_dim) + +/* + Purpose + ======= + + Multidimensional Scaling - Given a matrix of interpoint distances, + find a set of low dimensional points that have similar interpoint + distances. + + The routine returns the distance in double precision. + If the parameter transpose is set to a nonzero value, the clusters are + interpreted as clusters of microarrays, otherwise as clusters of gene. + + Arguments + ========= + */ +{ + //https://github.com/stober/mds/blob/master/src/mds.py + + int n = (transpose==0) ? nrows : ncolumns; + const int ldistmatrix = distmatrix==NULL ? 1 : 0; + + /* Calculate the distance matrix if the user didn't give it */ + if(ldistmatrix) + { distmatrix = + distancematrix(nrows, ncolumns, data, mask, weight, dist, transpose); + if (!distmatrix) return NULL; /* Insufficient memory */ + } + + int i, j; + double** E; + + E = (double**)malloc(n*sizeof(double*)); + if(E==NULL) return NULL; /* Not enough memory available */ + for (i = 0; i < n; i++) + { E[i] = (double*)malloc(n*sizeof(double)); + if (E[i]==NULL) break; /* Not enough memory available */ + } + + double sum_E = 0, avg_E = 0; + /* Calculate the distances and save them in the ragged array */ + /* E = (-0.5 * d*d) */ + for (i=0; i= rows) + return; + + unsigned long id_1; + unsigned long id_2; + unsigned long idx; + float tmp=0; + float dist=0; + + for (unsigned long i=0; i +#include +#include + +#ifdef __linux__ +//do nothing +float* gpu_distmatrix(const char* cl_path, int rows, int columns, double** data, int start, int end) +{ + return NULL; +} +#else + +#ifdef __APPLE__ +#include +#else +#include +#endif + +#define MAX_SOURCE_SIZE (0x100000) + +using namespace std; + +float* gpu_distmatrix(const char* cl_path, int rows, int columns, double** data, int start, int end) +{ + unsigned long long _rows = rows; + unsigned long long _columns = columns; + unsigned long long sz_float = sizeof(float); + unsigned long long _block = end-start+1; + unsigned long long i; + + unsigned long long indata_size = _rows * _columns * sz_float; + unsigned long long outdata_size = _rows * _block * sz_float; + float* a = (float *) malloc (indata_size); + float* r = (float *) malloc (outdata_size); + + unsigned long long idx; + + for (i=0; i // for std::ptrdiff_t +#include // for std::numeric_limits<...>::infinity() +#include // for std::fill_n +#include // for std::runtime_error +#include // for std::string + +#include "fastcluster.h" + +using namespace fastcluster; + +void fastcluster::MST_linkage_core(const t_index N, const t_float * const D, + cluster_result & Z2) { +/* + N: integer, number of data points + D: condensed distance matrix N*(N-1)/2 + Z2: output data structure + + The basis of this algorithm is an algorithm by Rohlf: + + F. James Rohlf, Hierarchical clustering using the minimum spanning tree, + The Computer Journal, vol. 16, 1973, p. 93–95. +*/ + t_index i; + t_index idx2; + doubly_linked_list active_nodes(N); + auto_array_ptr d(N); + + t_index prev_node; + t_float min; + + // first iteration + idx2 = 1; + min = std::numeric_limits::infinity(); + for (i=1; i tmp) + d[i] = tmp; + else if (fc_isnan(tmp)) + throw (nan_error()); +#if HAVE_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + if (d[i] < min) { + min = d[i]; + idx2 = i; + } + } + Z2.append(prev_node, idx2, min); + } +} diff --git a/Algorithms/fastcluster.h b/Algorithms/fastcluster.h new file mode 100644 index 000000000..3eac13961 --- /dev/null +++ b/Algorithms/fastcluster.h @@ -0,0 +1,2122 @@ +/* + fastcluster: Fast hierarchical clustering routines for R and Python + + Copyright © 2011 Daniel Müllner + + + This library implements various fast algorithms for hierarchical, + agglomerative clustering methods: + + (1) Algorithms for the "stored matrix approach": the input is the array of + pairwise dissimilarities. + + MST_linkage_core: single linkage clustering with the "minimum spanning + tree algorithm (Rohlfs) + + NN_chain_core: nearest-neighbor-chain algorithm, suitable for single, + complete, average, weighted and Ward linkage (Murtagh) + + generic_linkage: generic algorithm, suitable for all distance update + formulas (Müllner) + + (2) Algorithms for the "stored data approach": the input are points in a + vector space. + + MST_linkage_core_vector: single linkage clustering for vector data + + generic_linkage_vector: generic algorithm for vector data, suitable for + the Ward, centroid and median methods. + + generic_linkage_vector_alternative: alternative scheme for updating the + nearest neighbors. This method seems faster than "generic_linkage_vector" + for the centroid and median methods but slower for the Ward method. + + All these implementation treat infinity values correctly. They throw an + exception if a NaN distance value occurs. +*/ + +#ifndef __GEODA_CENTER_FASTCLUSTER_H__ +#define __GEODA_CENTER_FASTCLUSTER_H__ + +#include // for std::ptrdiff_t +#include // for std::numeric_limits<...>::infinity() +#include // for std::fill_n +#include // for std::runtime_error +#include // for std::string +#include + +// Microsoft Visual Studio does not have fenv.h +#ifdef _MSC_VER +#if (_MSC_VER == 1500 || _MSC_VER == 1600) +#define NO_INCLUDE_FENV +#endif +#endif +#ifndef NO_INCLUDE_FENV +#include +#endif + +#include // also for DBL_MAX, DBL_MIN +#ifndef DBL_MANT_DIG +#error The constant DBL_MANT_DIG could not be defined. +#endif +#define T_FLOAT_MANT_DIG DBL_MANT_DIG + +#ifndef LONG_MAX +#include +#endif +#ifndef LONG_MAX +#error The constant LONG_MAX could not be defined. +#endif +#ifndef INT_MAX +#error The constant INT_MAX could not be defined. +#endif + +#ifndef INT32_MAX +#define __STDC_LIMIT_MACROS +#include +#endif + +#ifndef HAVE_DIAGNOSTIC +#if __GNUC__ > 4 || (__GNUC__ == 4 && (__GNUC_MINOR__ >= 6)) +#define HAVE_DIAGNOSTIC 1 +#endif +#endif + +typedef int_fast32_t t_index; +#ifndef INT32_MAX +#define MAX_INDEX 0x7fffffffL +#else +#define MAX_INDEX INT32_MAX +#endif +#if (LONG_MAX < MAX_INDEX) +#error The integer format "t_index" must not have a greater range than "long int". +#endif +#if (INT_MAX > MAX_INDEX) +#error The integer format "int" must not have a greater range than "t_index". +#endif +typedef double t_float; + +#define fc_isnan(X) ((X)!=(X)) + +namespace fastcluster { + + enum method_codes { + // non-Euclidean methods + METHOD_METR_SINGLE = 0, + METHOD_METR_COMPLETE = 1, + METHOD_METR_AVERAGE = 2, + METHOD_METR_WEIGHTED = 3, + METHOD_METR_WARD = 4, + METHOD_METR_CENTROID = 5, + METHOD_METR_MEDIAN = 6 + }; + + enum { + // Euclidean methods + METHOD_VECTOR_SINGLE = 0, + METHOD_VECTOR_WARD = 1, + METHOD_VECTOR_CENTROID = 2, + METHOD_VECTOR_MEDIAN = 3 + }; + + enum { + // Return values + RET_SUCCESS = 0, + RET_MEMORY_ERROR = 1, + RET_STL_ERROR = 2, + RET_UNKNOWN_ERROR = 3 + }; + + // self-destructing array pointer + template + class auto_array_ptr{ + private: + type * ptr; + auto_array_ptr(auto_array_ptr const &); // non construction-copyable + auto_array_ptr& operator=(auto_array_ptr const &); // non copyable + public: + auto_array_ptr() + : ptr(NULL) + { } + template + auto_array_ptr(index const size) + : ptr(new type[size]) + { } + template + auto_array_ptr(index const size, value const val) + : ptr(new type[size]) + { + std::fill_n(ptr, size, val); + } + ~auto_array_ptr() { + delete [] ptr; } + void free() { + delete [] ptr; + ptr = NULL; + } + template + void init(index const size) { + ptr = new type [size]; + } + template + void init(index const size, value const val) { + init(size); + std::fill_n(ptr, size, val); + } + inline operator type *() const { return ptr; } + }; + + struct node { + t_index node1, node2; + t_float dist; + + /* + inline bool operator< (const node a) const { + return this->dist < a.dist; + } + */ + + inline friend bool operator< (const node a, const node b) { + return (a.dist < b.dist); + } + }; + + class cluster_result { + private: + auto_array_ptr Z; + t_index pos; + + public: + cluster_result(const t_index size) + : Z(size) + , pos(0) + {} + + void append(const t_index node1, const t_index node2, const t_float dist) { + Z[pos].node1 = node1; + Z[pos].node2 = node2; + Z[pos].dist = dist; + ++pos; + } + + node * operator[] (const t_index idx) const { return Z + idx; } + + /* Define several methods to postprocess the distances. All these functions + are monotone, so they do not change the sorted order of distances. */ + + void sqrt() const { + for (node * ZZ=Z; ZZ!=Z+pos; ++ZZ) { + ZZ->dist = ::sqrt(ZZ->dist); + } + } + + void sqrt(const t_float) const { // ignore the argument + sqrt(); + } + + void sqrtdouble(const t_float) const { // ignore the argument + for (node * ZZ=Z; ZZ!=Z+pos; ++ZZ) { + ZZ->dist = ::sqrt(2*ZZ->dist); + } + } + + void power(const t_float p) const { + t_float const q = 1/p; + for (node * ZZ=Z; ZZ!=Z+pos; ++ZZ) { + ZZ->dist = pow(ZZ->dist,q); + } + } + + void plusone(const t_float) const { // ignore the argument + for (node * ZZ=Z; ZZ!=Z+pos; ++ZZ) { + ZZ->dist += 1; + } + } + + void divide(const t_float denom) const { + for (node * ZZ=Z; ZZ!=Z+pos; ++ZZ) { + ZZ->dist /= denom; + } + } + }; + + // The size of a node is either 1 (a single point) or is looked up from + // one of the clusters. +//#define size_(r_) ( ((r_(node1); + *(Z++) = static_cast(node2); + } + else { + *(Z++) = static_cast(node2); + *(Z++) = static_cast(node1); + } + *(Z++) = dist; + *(Z++) = size; + } + }; + + class doubly_linked_list { + /* + Class for a doubly linked list. Initially, the list is the integer range + [0, size]. We provide a forward iterator and a method to delete an index + from the list. + + Typical use: for (i=L.start; L succ; + + private: + auto_array_ptr pred; + // Not necessarily private, we just do not need it in this instance. + + public: + doubly_linked_list(const t_index size) + // Initialize to the given size. + : start(0) + , succ(size+1) + , pred(size+1) + { + for (t_index i=0; i(2*N-3-(r_))*(r_)>>1)+(c_)-1] ) + // Z is an ((N-1)x4)-array +#define Z_(_r, _c) (Z[(_r)*4 + (_c)]) + + /* + Lookup function for a union-find data structure. + + The function finds the root of idx by going iteratively through all + parent elements until a root is found. An element i is a root if + nodes[i] is zero. To make subsequent searches faster, the entry for + idx and all its parents is updated with the root element. + */ + class union_find { + private: + auto_array_ptr parent; + t_index nextparent; + + public: + union_find(const t_index size) + : parent(size>0 ? 2*size-1 : 0, 0) + , nextparent(size) + { } + + t_index Find (t_index idx) const { + if (parent[idx] != 0 ) { // a → b + t_index p = idx; + idx = parent[idx]; + if (parent[idx] != 0 ) { // a → b → c + do { + idx = parent[idx]; + } while (parent[idx] != 0); + do { + t_index tmp = parent[p]; + parent[p] = idx; + p = tmp; + } while (parent[p] != idx); + } + } + return idx; + } + + void Union (const t_index node1, const t_index node2) { + parent[node1] = parent[node2] = nextparent++; + } + }; + + class nan_error{}; +#ifdef FE_INVALID + class fenv_error{}; +#endif + + + + /* Functions for the update of the dissimilarity array */ + + inline static void f_single( t_float * const b, const t_float a ) { + if (*b > a) *b = a; + } + inline static void f_complete( t_float * const b, const t_float a ) { + if (*b < a) *b = a; + } + inline static void f_average( t_float * const b, const t_float a, const t_float s, const t_float t) { + *b = s*a + t*(*b); +#ifndef FE_INVALID +#if HAVE_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wfloat-equal" +#endif + if (fc_isnan(*b)) { + throw(nan_error()); + } +#if HAVE_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif +#endif + } + inline static void f_weighted( t_float * const b, const t_float a) { + *b = (a+*b)*.5; +#ifndef FE_INVALID +#if HAVE_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wfloat-equal" +#endif + if (fc_isnan(*b)) { + throw(nan_error()); + } +#if HAVE_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif +#endif + } + inline static void f_ward( t_float * const b, const t_float a, const t_float c, const t_float s, const t_float t, const t_float v) { + *b = ( (v+s)*a - v*c + (v+t)*(*b) ) / (s+t+v); + //*b = a+(*b)-(t*a+s*(*b)+v*c)/(s+t+v); +#ifndef FE_INVALID +#if HAVE_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wfloat-equal" +#endif + if (fc_isnan(*b)) { + throw(nan_error()); + } +#if HAVE_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif +#endif + } + inline static void f_centroid( t_float * const b, const t_float a, const t_float stc, const t_float s, const t_float t) { + *b = s*a - stc + t*(*b); +#ifndef FE_INVALID + if (fc_isnan(*b)) { + throw(nan_error()); + } +#if HAVE_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif +#endif + } + inline static void f_median( t_float * const b, const t_float a, const t_float c_4) { + *b = (a+(*b))*.5 - c_4; +#ifndef FE_INVALID +#if HAVE_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wfloat-equal" +#endif + if (fc_isnan(*b)) { + throw(nan_error()); + } +#if HAVE_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif +#endif + } + + + class binary_min_heap { + /* + Class for a binary min-heap. The data resides in an array A. The elements of + A are not changed but two lists I and R of indices are generated which point + to elements of A and backwards. + + The heap tree structure is + + H[2*i+1] H[2*i+2] + \ / + \ / + ≤ ≤ + \ / + \ / + H[i] + + where the children must be less or equal than their parent. Thus, H[0] + contains the minimum. The lists I and R are made such that H[i] = A[I[i]] + and R[I[i]] = i. + + This implementation is not designed to handle NaN values. + */ + private: + t_float * const A; + t_index size; + auto_array_ptr I; + auto_array_ptr R; + + // no default constructor + binary_min_heap(); + // noncopyable + binary_min_heap(binary_min_heap const &); + binary_min_heap & operator=(binary_min_heap const &); + + public: + binary_min_heap(t_float * const A_, const t_index size_) + : A(A_), size(size_), I(size), R(size) + { // Allocate memory and initialize the lists I and R to the identity. This + // does not make it a heap. Call heapify afterwards! + for (t_index i=0; i>1); idx>0; ) { + --idx; + update_geq_(idx); + } + } + + inline t_index argmin() const { + // Return the minimal element. + return I[0]; + } + + void heap_pop() { + // Remove the minimal element from the heap. + --size; + I[0] = I[size]; + R[I[0]] = 0; + update_geq_(0); + } + + void remove(t_index idx) { + // Remove an element from the heap. + --size; + R[I[size]] = R[idx]; + I[R[idx]] = I[size]; + if ( H(size)<=A[idx] ) { + update_leq_(R[idx]); + } + else { + update_geq_(R[idx]); + } + } + + void replace ( const t_index idxold, const t_index idxnew, + const t_float val) { + R[idxnew] = R[idxold]; + I[R[idxnew]] = idxnew; + if (val<=A[idxold]) + update_leq(idxnew, val); + else + update_geq(idxnew, val); + } + + void update ( const t_index idx, const t_float val ) const { + // Update the element A[i] with val and re-arrange the indices to preserve + // the heap condition. + if (val<=A[idx]) + update_leq(idx, val); + else + update_geq(idx, val); + } + + void update_leq ( const t_index idx, const t_float val ) const { + // Use this when the new value is not more than the old value. + A[idx] = val; + update_leq_(R[idx]); + } + + void update_geq ( const t_index idx, const t_float val ) const { + // Use this when the new value is not less than the old value. + A[idx] = val; + update_geq_(R[idx]); + } + + private: + void update_leq_ (t_index i) const { + t_index j; + for ( ; (i>0) && ( H(i)>1) ); i=j) + heap_swap(i,j); + } + + void update_geq_ (t_index i) const { + t_index j; + for ( ; (j=2*i+1)=H(i) ) { + ++j; + if ( j>=size || H(j)>=H(i) ) break; + } + else if ( j+1 in products + t_index N; + auto_array_ptr Xnew; + t_index * members; + void (cluster_result::*postprocessfn) (const t_float) const; + t_float postprocessarg; + + t_float (python_dissimilarity::*distfn) (const t_index, const t_index) const; + + auto_array_ptr precomputed; + t_float * precomputed2; + + const t_float * V_data; + + // noncopyable + python_dissimilarity(); + python_dissimilarity(python_dissimilarity const &); + python_dissimilarity & operator=(python_dissimilarity const &); + + public: + // Ignore warning about uninitialized member variables. I know what I am + // doing here, and some member variables are only used for certain metrics. +#if HAVE_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Weffc++" +#endif + python_dissimilarity (t_float * const Xarg, + t_index * const members_, + const unsigned char method, + const unsigned char metric, + bool temp_point_array) + { + switch (method) { + case METHOD_METR_SINGLE: + postprocessfn = NULL; // default + switch (metric) { + case METRIC_EUCLIDEAN: + set_euclidean(); + break; + + case METRIC_CITYBLOCK: + set_cityblock(); + break; + + default: // case METRIC_JACCARD_BOOL: + distfn = &python_dissimilarity::sqeuclidean; + } + break; + + case METHOD_METR_WARD: + postprocessfn = &cluster_result::sqrtdouble; + break; + + default: + postprocessfn = &cluster_result::sqrt; + } + } + + ~python_dissimilarity() { + } + + inline t_float operator () (const t_index i, const t_index j) const { + return (this->*distfn)(i,j); + } + + inline t_float X (const t_index i, const t_index j) const { + return Xa[i*dim+j]; + } + + inline bool Xb (const t_index i, const t_index j) const { + return reinterpret_cast(Xa)[i*dim+j]; + } + + inline t_float * Xptr(const t_index i, const t_index j) const { + return Xa+i*dim+j; + } + + void merge(const t_index i, const t_index j, const t_index newnode) const { + t_float const * const Pi = i(members[i]) + + Pj[k]*static_cast(members[j])) / + static_cast(members[i]+members[j]); + } + members[newnode] = members[i]+members[j]; + } + + void merge_weighted(const t_index i, const t_index j, const t_index newnode) + const { + t_float const * const Pi = i(members[i]) + + Pj[k]*static_cast(members[j])) / + static_cast(members[i]+members[j]); + } + members[j] += members[i]; + } + + void merge_inplace_weighted(const t_index i, const t_index j) const { + t_float const * const Pi = Xa+i*dim; + t_float * const Pj = Xa+j*dim; + for(t_index k=0; k(members[i]); + t_float mj = static_cast(members[j]); + return sqeuclidean(i,j)*mi*mj/(mi+mj); + } + + inline t_float ward_initial(const t_index i, const t_index j) const { + // alias for sqeuclidean + // Factor 2!!! + return sqeuclidean(i,j); + } + + // This method must not produce NaN if the input is non-NaN. + inline static t_float ward_initial_conversion(const t_float min) { + return min*.5; + } + + inline t_float ward_extended(const t_index i, const t_index j) const { + t_float mi = static_cast(members[i]); + t_float mj = static_cast(members[j]); + return sqeuclidean_extended(i,j)*mi*mj/(mi+mj); + } + + /* We need two variants of the Euclidean metric: one that does not check + for a NaN result, which is used for the initial distances, and one which + does, for the updated distances during the clustering procedure. + */ + template + t_float sqeuclidean(const t_index i, const t_index j) const { + t_float sum = 0; + /* + for (t_index k=0; k; + postprocessfn = &cluster_result::sqrt; + } + + void set_cityblock() { + distfn = &python_dissimilarity::cityblock; + } + + void set_chebychev() { + distfn = &python_dissimilarity::chebychev; + } + + t_float seuclidean(const t_index i, const t_index j) const { + t_float sum = 0; + for (t_index k=0; kmax) { + max = diff; + } + } + return max; + } + + t_float cosine(const t_index i, const t_index j) const { + t_float sum = 0; + for (t_index k=0; k(sum1) / static_cast(sum2); + } + + t_float canberra(const t_index i, const t_index j) const { + t_float sum = 0; + for (t_index k=0; k(dim)-NTT-NXO); // NFFTT + } + + void nbool_correspond_xo(const t_index i, const t_index j) const { + NXO = 0; + for (t_index k=0; k(2*NTFFT) / static_cast(NTFFT + NFFTT); + } + + // Prevent a zero denominator for equal vectors. + t_float dice(const t_index i, const t_index j) const { + nbool_correspond(i, j); + return (NXO==0) ? 0 : + static_cast(NXO) / static_cast(NXO+2*NTT); + } + + t_float rogerstanimoto(const t_index i, const t_index j) const { + nbool_correspond_xo(i, j); + return static_cast(2*NXO) / static_cast(NXO+dim); + } + + t_float russellrao(const t_index i, const t_index j) const { + nbool_correspond_tt(i, j); + return static_cast(dim-NTT); + } + + // Prevent a zero denominator for equal vectors. + t_float sokalsneath(const t_index i, const t_index j) const { + nbool_correspond(i, j); + return (NXO==0) ? 0 : + static_cast(2*NXO) / static_cast(NTT+2*NXO); + } + + t_float kulsinski(const t_index i, const t_index j) const { + nbool_correspond_tt(i, j); + return static_cast(NTT) * (precomputed[i] + precomputed[j]); + } + + // 'matching' distance = Hamming distance + t_float matching(const t_index i, const t_index j) const { + nbool_correspond_xo(i, j); + return static_cast(NXO); + } + + // Prevent a zero denominator for equal vectors. + t_float jaccard_bool(const t_index i, const t_index j) const { + nbool_correspond(i, j); + return (NXO==0) ? 0 : + static_cast(NXO) / static_cast(NXO+NTT); + } + }; + + //double cuttree(); + + + void MST_linkage_core(const t_index N, const t_float * const D, + cluster_result & Z2); + + template + void NN_chain_core(const t_index N, t_float * const D, t_members * const members, cluster_result & Z2) + { + /* + N: integer + D: condensed distance matrix N*(N-1)/2 + Z2: output data structure + + This is the NN-chain algorithm, described on page 86 in the following book: + + Fionn Murtagh, Multidimensional Clustering Algorithms, + Vienna, Würzburg: Physica-Verlag, 1985. + */ + t_index i; + + auto_array_ptr NN_chain(N); + t_index NN_chain_tip = 0; + + t_index idx1, idx2; + + t_float size1, size2; + doubly_linked_list active_nodes(N); + + t_float min; + + for (t_float const * DD=D; DD!=D+(static_cast(N)*(N-1)>>1); + ++DD) { +#if HAVE_DIAGNOSTIC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wfloat-equal" +#endif + if (fc_isnan(*DD)) { + throw(nan_error()); + } +#if HAVE_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + } + +#ifdef FE_INVALID + if (feclearexcept(FE_INVALID)) throw fenv_error(); +#endif + + for (t_index j=0; jidx2) { + t_index tmp = idx1; + idx1 = idx2; + idx2 = tmp; + } + + if (method==METHOD_METR_AVERAGE || + method==METHOD_METR_WARD) { + size1 = static_cast(members[idx1]); + size2 = static_cast(members[idx2]); + members[idx2] += members[idx1]; + } + + // Remove the smaller index from the valid indices (active_nodes). + active_nodes.remove(idx1); + + switch (method) { + case METHOD_METR_SINGLE: + /* + Single linkage. + + Characteristic: new distances are never longer than the old distances. + */ + // Update the distance matrix in the range [start, idx1). + for (i=active_nodes.start; i(members[i]); + for (i=active_nodes.start; i(members[i]) ); + // Update the distance matrix in the range (idx1, idx2). + for (; i(members[i]) ); + // Update the distance matrix in the range (idx2, N). + for (i=active_nodes.succ[idx2]; i(members[i]) ); + break; + + default: + throw std::runtime_error(std::string("Invalid method.")); + } + } +#ifdef FE_INVALID + if (fetestexcept(FE_INVALID)) throw fenv_error(); +#endif + } + + template + void generic_linkage(const t_index N, t_float * const D, t_members * const members, cluster_result & Z2) + { + /* + N: integer, number of data points + D: condensed distance matrix N*(N-1)/2 + Z2: output data structure + */ + + const t_index N_1 = N-1; + t_index i, j; // loop variables + t_index idx1, idx2; // row and column indices + + auto_array_ptr n_nghbr(N_1); // array of nearest neighbors + auto_array_ptr mindist(N_1); // distances to the nearest neighbors + auto_array_ptr row_repr(N); // row_repr[i]: node number that the + // i-th row represents + doubly_linked_list active_nodes(N); + binary_min_heap nn_distances(&*mindist, N_1); // minimum heap structure for + // the distance to the nearest neighbor of each point + t_index node1, node2; // node numbers in the output + t_float size1, size2; // and their cardinalities + + t_float min; // minimum and row index for nearest-neighbor search + t_index idx; + + for (i=0; ii} D(i,j) for i in range(N-1) + t_float const * DD = D; + for (i=0; i::infinity(); + for (idx=j=i+1; ji} D(i,j) + + Normally, we have equality. However, this minimum may become invalid due + to the updates in the distance matrix. The rules are: + + 1) If mindist[i] is equal to D(i, n_nghbr[i]), this is the correct + minimum and n_nghbr[i] is a nearest neighbor. + + 2) If mindist[i] is smaller than D(i, n_nghbr[i]), this might not be the + correct minimum. The minimum needs to be recomputed. + + 3) mindist[i] is never bigger than the true minimum. Hence, we never + miss the true minimum if we take the smallest mindist entry, + re-compute the value if necessary (thus maybe increasing it) and + looking for the now smallest mindist entry until a valid minimal + entry is found. This step is done in the lines below. + + The update process for D below takes care that these rules are + fulfilled. This makes sure that the minima in the rows D(i,i+1:)of D are + re-calculated when necessary but re-calculation is avoided whenever + possible. + + The re-calculation of the minima makes the worst-case runtime of this + algorithm cubic in N. We avoid this whenever possible, and in most cases + the runtime appears to be quadratic. + */ + idx1 = nn_distances.argmin(); + if (method != METHOD_METR_SINGLE) { + while ( mindist[idx1] < D_(idx1, n_nghbr[idx1]) ) { + // Recompute the minimum mindist[idx1] and n_nghbr[idx1]. + n_nghbr[idx1] = j = active_nodes.succ[idx1]; // exists, maximally N-1 + min = D_(idx1,j); + for (j=active_nodes.succ[j]; j(members[idx1]); + size2 = static_cast(members[idx2]); + members[idx2] += members[idx1]; + } + Z2.append(node1, node2, mindist[idx1]); + + // Remove idx1 from the list of active indices (active_nodes). + active_nodes.remove(idx1); + // Index idx2 now represents the new (merged) node with label N+i. + row_repr[idx2] = N+i; + + // Update the distance matrix + switch (method) { + case METHOD_METR_SINGLE: + /* + Single linkage. + + Characteristic: new distances are never longer than the old distances. + */ + // Update the distance matrix in the range [start, idx1). + for (j=active_nodes.start; j(members[j]) ); + if (n_nghbr[j] == idx1) + n_nghbr[j] = idx2; + } + // Update the distance matrix in the range (idx1, idx2). + for (; j(members[j]) ); + if (D_(j, idx2) < mindist[j]) { + nn_distances.update_leq(j, D_(j, idx2)); + n_nghbr[j] = idx2; + } + } + // Update the distance matrix in the range (idx2, N). + if (idx2(members[j]) ); + min = D_(idx2,j); + for (j=active_nodes.succ[j]; j(members[j]) ); + if (D_(idx2,j) < min) { + min = D_(idx2,j); + n_nghbr[idx2] = j; + } + } + nn_distances.update(idx2, min); + } + break; + + case METHOD_METR_CENTROID: { + /* + Centroid linkage. + + Shorter and longer distances can occur, not bigger than max(d1,d2) + but maybe smaller than min(d1,d2). + */ + // Update the distance matrix in the range [start, idx1). + t_float s = size1/(size1+size2); + t_float t = size2/(size1+size2); + t_float stc = s*t*mindist[idx1]; + for (j=active_nodes.start; j + void MST_linkage_core_vector(const t_index N, + t_dissimilarity & dist, + cluster_result & Z2) + { + /* + N: integer, number of data points + dist: function pointer to the metric + Z2: output data structure + + The basis of this algorithm is an algorithm by Rohlf: + + F. James Rohlf, Hierarchical clustering using the minimum spanning tree, + The Computer Journal, vol. 16, 1973, p. 93–95. + */ + t_index i; + t_index idx2; + doubly_linked_list active_nodes(N); + auto_array_ptr d(N); + + t_index prev_node; + t_float min; + + // first iteration + idx2 = 1; + min = std::numeric_limits::infinity(); + for (i=1; i tmp) + d[i] = tmp; + else if (fc_isnan(tmp)) + throw (nan_error()); +#if HAVE_DIAGNOSTIC +#pragma GCC diagnostic pop +#endif + if (d[i] < min) { + min = d[i]; + idx2 = i; + } + } + Z2.append(prev_node, idx2, min); + } + } + + + template + void generic_linkage_vector(const t_index N, + t_dissimilarity & dist, + cluster_result & Z2) + { + /* + N: integer, number of data points + dist: function pointer to the metric + Z2: output data structure + + This algorithm is valid for the distance update methods + "Ward", "centroid" and "median" only! + */ + const t_index N_1 = N-1; + t_index i, j; // loop variables + t_index idx1, idx2; // row and column indices + + auto_array_ptr n_nghbr(N_1); // array of nearest neighbors + auto_array_ptr mindist(N_1); // distances to the nearest neighbors + auto_array_ptr row_repr(N); // row_repr[i]: node number that the + // i-th row represents + doubly_linked_list active_nodes(N); + binary_min_heap nn_distances(&*mindist, N_1); // minimum heap structure for + // the distance to the nearest neighbor of each point + t_index node1, node2; // node numbers in the output + t_float min; // minimum and row index for nearest-neighbor search + + for (i=0; ii} D(i,j) for i in range(N-1) + for (i=0; i::infinity(); + t_index idx; + for (idx=j=i+1; j(i,j); + } + if (tmp(idx1,j); + for (j=active_nodes.succ[j]; j(idx1,j); + if (tmp(j, idx2); + if (tmp < mindist[j]) { + nn_distances.update_leq(j, tmp); + n_nghbr[j] = idx2; + } + else if (n_nghbr[j] == idx2) + n_nghbr[j] = idx1; // invalidate + } + // Find the nearest neighbor for idx2. + if (idx2(idx2,j); + for (j=active_nodes.succ[j]; j(idx2, j); + if (tmp < min) { + min = tmp; + n_nghbr[idx2] = j; + } + } + nn_distances.update(idx2, min); + } + } + } + } + + + template + void generic_linkage_vector_alternative(const t_index N, + t_dissimilarity & dist, + cluster_result & Z2) + { + /* + N: integer, number of data points + dist: function pointer to the metric + Z2: output data structure + + This algorithm is valid for the distance update methods + "Ward", "centroid" and "median" only! + */ + const t_index N_1 = N-1; + t_index i, j=0; // loop variables + t_index idx1, idx2; // row and column indices + + auto_array_ptr n_nghbr(2*N-2); // array of nearest neighbors + auto_array_ptr mindist(2*N-2); // distances to the nearest neighbors + + doubly_linked_list active_nodes(N+N_1); + binary_min_heap nn_distances(&*mindist, N_1, 2*N-2, 1); // minimum heap + // structure for the distance to the nearest neighbor of each point + + t_float min; // minimum for nearest-neighbor searches + + // Initialize the minimal distances: + // Find the nearest neighbor of each point. + // n_nghbr[i] = argmin_{j>i} D(i,j) for i in range(N-1) + for (i=1; i::infinity(); + t_index idx; + for (idx=j=0; j(i,j); + } + if (tmp. + * + * Created 5/30/2017 lixun910@gmail.com + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include +#include +#include + +#include "../logger.h" +#include "../GdaJson.h" +#include "geocoding.h" + +using namespace std; + + +GeoCodingInterface::GeoCodingInterface() +{ +} + +GeoCodingInterface::~GeoCodingInterface() +{ +} + +size_t dump_to_string(void *ptr, size_t size, size_t count, void *stream) { + ((string*)stream)->append((char*)ptr, 0, size*count); + return size*count; +} + +bool GeoCodingInterface::doGet(CURL* curl, const char* url, string& response) +{ + wxLogMessage("AutoUpdate::ReadUrlContent()"); + + CURLcode res; + int res_code = 0; + + if (curl) { + curl_easy_setopt(curl, CURLOPT_URL, url); + + curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, dump_to_string); + curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response); + curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 1L); + curl_easy_setopt(curl, CURLOPT_TIMEOUT, 5L); + + res = curl_easy_perform(curl); + + //curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &res_code); + } + + //if (!((res_code == 200 || res_code == 201) && res != CURLE_ABORTED_BY_CALLBACK)) + //{ + // return false; + //} + return true; +} + +void GeoCodingInterface::run(){ +} + +void GeoCodingInterface::geocoding(vector& _addresses, vector& _lats, vector& _lngs, vector& _undefs, wxGauge* _prg, bool* _stop) +{ + lats.clear(); + lngs.clear(); + undefs.clear(); + addresses.clear(); + + lats = _lats; + lngs = _lngs; + undefs = _undefs; + addresses = _addresses; + stop = _stop; + + CURL* curl = curl_easy_init(); + + int out_limit_count = 0; + + for ( int i=0, n=addresses.size(); i10) + break; + if (undefs[i] == false && lats[i] != 0 && lngs[i] != 0) + continue; + const wxString& addr = addresses[i]; + wxString url = create_request_url(addr); + wxURI uri(url); + wxString encoded_url = uri.BuildURI(); + string response; + // send request to server + doGet(curl, encoded_url.c_str(), response); + double lat=0; + double lng=0; + int rtn = retrive_latlng(response, &lat, &lng); + if (rtn==-1) { + out_limit_count ++; + wxSleep(2); + } + lats[i] = lat; + lngs[i] = lng; + undefs[i] = (rtn != 1); + _prg->SetValue(i+1); + LOG_MSG(encoded_url); + LOG_MSG(lat); + //wxMilliSleep(50); + } + + curl_easy_cleanup(curl); +} + + +///////////////////////////////////////////////////////////////////////////////////////// +// +// +///////////////////////////////////////////////////////////////////////////////////////// + +GoogleGeoCoder::GoogleGeoCoder(vector& _keys) +{ + keys = _keys; + key = get_next_key(); + url_template = "https://maps.googleapis.com/maps/api/geocode/json?address=%s&key=%s"; +} + +GoogleGeoCoder::~GoogleGeoCoder() +{ + +} + +wxString GoogleGeoCoder::create_request_url(const wxString &_addr) +{ + wxString addr = _addr; + //addr.Replace(" ", "+"); + wxString url = wxString::Format(url_template, addr, key); + return url; +} + +wxString GoogleGeoCoder::get_next_key() +{ + if (!keys.empty()) { + key = keys.back(); + keys.pop_back(); + } + return key; +} + +int GoogleGeoCoder::retrive_latlng(const string& response, double* lat, double* lng) +{ + /* + { + "results" : [ + { + "geometry" : { + "location" : { + "lat" : 37.4224764, + "lng" : -122.0842499 + } + */ + json_spirit::Value v; + try { + if (!json_spirit::read(response, v)) { + throw std::runtime_error("Could not parse recent ds string"); + } + + json_spirit::Value json_results; + json_spirit::Value json_status; + if (GdaJson::findValue(v, json_status, "status")) { + string stat = json_status.get_str(); + if (stat.compare("OVER_QUERY_LIMIT")==0 || + stat.compare("REQUEST_DENIED") ==0) { + error_msg << stat << ": " << key << "\n\n"; + key = get_next_key(); + return -1; + } + } + if (GdaJson::findValue(v, json_results, "results")) { + const json_spirit::Array& results = json_results.get_array(); + if (results.size() == 0) + return 0; + const json_spirit::Object& o = results[0].get_obj(); + + json_spirit::Value json_geometry; + if (GdaJson::findValue(o, json_geometry, "geometry")) { + json_spirit::Value json_location; + if (GdaJson::findValue(json_geometry, json_location, "location")) { + json_spirit::Value json_lat; + json_spirit::Value json_lng; + GdaJson::findValue(json_location, json_lat, "lat"); + GdaJson::findValue(json_location, json_lng, "lng"); + *lat = json_lat.get_real(); + *lng = json_lng.get_real(); + return 1; + } + } + } + + } catch (std::runtime_error e) { + return 0; + } + return 0; +} diff --git a/Algorithms/geocoding.h b/Algorithms/geocoding.h new file mode 100644 index 000000000..c907505ab --- /dev/null +++ b/Algorithms/geocoding.h @@ -0,0 +1,103 @@ +/** + * GeoDa TM, Copyright (C) 2011-2015 by Luc Anselin - all rights reserved + * + * This file is part of GeoDa. + * + * GeoDa is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * GeoDa is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * Created 5/30/2017 lixun910@gmail.com + */ + +#ifndef __GEODA_CENTER_GEOCODING_H +#define __GEODA_CENTER_GEOCODING_H + +#include +#include +#include + +#include + +#include + +using namespace std; + +class GeoCodingInterface { +public: + /** + * Performs eigenvector decomposition of an affinity matrix + * + * @param data the affinity matrix + * @param numDims the number of dimensions to consider when clustering + */ + GeoCodingInterface(); + + virtual ~GeoCodingInterface(); + + virtual void run(); + + /** + * Cluster by kmeans + * + * @param numClusters the number of clusters to assign + */ + virtual void geocoding(vector& address, vector& _lats, vector& _lngs, vector& _undefs, wxGauge* prg, bool* stop); + + int* count; + + bool* stop; + + vector addresses; + + vector lats; + + vector lngs; + + vector undefs; + + wxString error_msg; + +protected: + + bool doGet(CURL* curl, const char* url, string& response); + + virtual wxString create_request_url(const wxString& addr) = 0; + + virtual int retrive_latlng(const string& response, double* lat, double* lng) = 0; +}; + + +class GoogleGeoCoder : public GeoCodingInterface { + +public: + GoogleGeoCoder(vector& _keys); + + virtual ~GoogleGeoCoder(); + +protected: + + virtual wxString create_request_url(const wxString& addr); + + virtual int retrive_latlng(const string& response, double* lat, double* lng); + + wxString key; + + vector keys; + + wxString url_template; + + wxString get_next_key(); +}; + + +#endif diff --git a/Algorithms/gpu_lisa.cpp b/Algorithms/gpu_lisa.cpp new file mode 100644 index 000000000..4f872a121 --- /dev/null +++ b/Algorithms/gpu_lisa.cpp @@ -0,0 +1,506 @@ +#include +#include +#include +#include +#include "../ShapeOperations/GalWeight.h" +#ifdef __linux__ +// do nothing; we got opencl sdk issue on centos +bool gpu_lisa(const char* cl_path, int rows, int permutations, unsigned long long last_seed_used, double* values, double* local_moran, GalElement* w, double* p) +{ + return false; +} + +bool gpu_localjoincount(const char* cl_path, int rows, int permutations, unsigned long long last_seed_used, int num_vars, int* zz, double* local_jc, GalElement* w, double* p) +{ + return false; +} +#else + +#ifdef __APPLE__ +#include +#else +#include +#endif + +#define MAX_SOURCE_SIZE (0x100000) + +#include "../ShapeOperations/GalWeight.h" + +using namespace std; + +char *replace_str(char *str, char *orig, char *rep, int start) +{ + static char temp[4096]; + static char buffer[4096]; + char *p; + + strcpy(temp, str + start); + + if(!(p = strstr(temp, orig))) // Is 'orig' even in 'temp'? + return temp; + + strncpy(buffer, temp, p-temp); // Copy characters from 'temp' start to 'orig' str + buffer[p-temp] = '\0'; + + sprintf(buffer + (p - temp), "%s%s", rep, p + strlen(orig)); + sprintf(str + start, "%s", buffer); + + return str; +} + +bool gpu_lisa(const char* cl_path, int rows, int permutations, unsigned long long last_seed_used, double* values, double* local_moran, GalElement* w, double* p) +{ + int max_n_nbrs = 0; + int* num_nbrs = new int[rows]; + int total_nbrs = 0; + + for (size_t i=0; i max_n_nbrs) { + max_n_nbrs = nnbrs; + } + num_nbrs[i] = nnbrs; + total_nbrs += nnbrs; + } + + int* nbr_idx = new int[total_nbrs]; + size_t idx = 0; + + for (size_t i=0; i max_n_nbrs) { + max_n_nbrs = nnbrs; + } + num_nbrs[i] = nnbrs; + total_nbrs += nnbrs; + } + + unsigned short* nbr_idx = new unsigned short[total_nbrs]; + size_t idx = 0; + + for (size_t i=0; i +#include + +#include +#include "hdbscan.h" + + +using namespace GeoDaClustering; + + +bool EdgeLess1(SimpleEdge* a, SimpleEdge* b) +{ + return a->length < b->length; +} + +//////////////////////////////////////////////////////////////////////////////// +// +// HDBSCAN +// +//////////////////////////////////////////////////////////////////////////////// +HDBScan::HDBScan(int min_cluster_size, int min_samples, double alpha, int _cluster_selection_method, bool _allow_single_cluster, int rows, int cols, double** _distances, double** _data, const vector& _undefs + //,GalElement* w, double* _controls, double _control_thres + ) +{ + int cluster_selection_method = _cluster_selection_method; + bool allow_single_cluster = _allow_single_cluster; + bool match_reference_implementation = false; + + // Core distances + core_dist.resize(rows); + + int k = min_samples; + int dim = cols; + double eps = 0; // error bound + int nPts = rows; + + ANNkd_tree* kdTree = new ANNkd_tree(_data, nPts, dim); + + ANNidxArray nnIdx = new ANNidx[k]; + ANNdistArray dists = new ANNdist[k]; + for (int i=0; iannkSearch(_data[i], k, nnIdx, dists, eps); + core_dist[i] = sqrt(dists[k-1]); + } + delete[] nnIdx; + delete[] dists; + delete kdTree; + + // MST + mst_linkage_core_vector(dim, core_dist, _distances, alpha); + std::sort(mst_edges.begin(), mst_edges.end(), EdgeLess1); + + // Extract the HDBSCAN hierarchy as a dendrogram from mst + int N = rows; + UnionFind U(N); + single_linkage_tree = new double*[N-1]; + for (int i=0; iorig; + int b = e->dest; + double delta = e->length; + + int aa = U.fast_find(a); + int bb = U.fast_find(b); + + single_linkage_tree[i] = new double[4]; + single_linkage_tree[i][0] = aa; + single_linkage_tree[i][1] = bb; + single_linkage_tree[i][2] = delta; + single_linkage_tree[i][3] = U.size[aa] + U.size[bb]; + + //cout << a << " " << b << " " << delta << endl; + //cout << aa << " " << bb << " " << delta << " " < stability_dict = compute_stability(condensed_tree); + + // labels, probabilities, stabilities = get_clusters(condensed_tree, + get_clusters(condensed_tree, stability_dict, labels, probabilities, stabilities, cluster_selection_method, allow_single_cluster, match_reference_implementation); + + // get outliers + outliers = outlier_scores(condensed_tree); + + for (int i=0; i > HDBScan::GetRegions() +{ + int min_cid = labels[0]; + int max_cid = labels[0]; + for (int i=0; i max_cid) { + max_cid = labels[i]; + } + if (labels[i] < min_cid) { + min_cid = labels[i]; + } + } + vector > regions(max_cid + 1); + + int cid = 0; + for (int i=0; i=0) { + int cid = labels[i]; + regions[cid].push_back(i); + } + } + + return regions; +} + +void HDBScan::condense_tree(double** hierarchy, int N, int min_cluster_size) +{ + int root = 2 * (N-1); + int num_points = root /2 + 1; + int next_label = num_points + 1; + + vector node_list = bfs_from_hierarchy(hierarchy, N-1, root); + + vector relabel(root+1); + relabel[root] = num_points; + + vector ignore(node_list.size(),false); + + double lambda_value; + int left_count, right_count; + + for (int i=0; i 0.0) { + lambda_value = 1.0 / children[2]; + } else { + lambda_value = DBL_MAX; + } + + if (left >= num_points) { + left_count = hierarchy[left - num_points][3]; + } else { + left_count = 1; + } + + if (right >= num_points) { + right_count = hierarchy[right - num_points][3]; + } else { + right_count = 1; + } + + if (left_count >= min_cluster_size && right_count >= min_cluster_size) { + relabel[left] = next_label; + next_label += 1; + condensed_tree.push_back(new CondensedTree(relabel[node], relabel[left], lambda_value, left_count)); + + relabel[right] = next_label; + next_label += 1; + condensed_tree.push_back(new CondensedTree(relabel[node], relabel[right], lambda_value, right_count)); + + } else if (left_count < min_cluster_size && right_count < min_cluster_size) { + vector sub_nodes = bfs_from_hierarchy(hierarchy, N-1, left); + for (int j=0; j sub_nodes1 = bfs_from_hierarchy(hierarchy, N-1, right); + for (int j=0; j sub_nodes = bfs_from_hierarchy(hierarchy, N-1, left); + for (int j=0; j sub_nodes = bfs_from_hierarchy(hierarchy, N-1, right); + for (int j=0; j HDBScan::outlier_scores(vector& tree) +{ + // Generate GLOSH outlier scores from a condensed tree. + vector deaths = max_lambdas(tree); + + int root_cluster = tree[0]->parent; + + vector parent_array(tree.size()); + parent_array[0] = tree[0]->parent; + + for (int i=1; iparent; + if (tree[i]->parent < root_cluster ) { + root_cluster = tree[i]->parent; + } + } + + vector result(root_cluster, 0); + + vector topological_sort_order(tree.size()); + for (int i=0; ichild; + if (cluster < root_cluster) { + break; + } + + int parent = parent_array[n]; + if (deaths[cluster] > deaths[parent]) { + deaths[parent] = deaths[cluster]; + } + } + + for (int n=0; nchild; + if (point >= root_cluster) { + continue; + } + + int cluster = parent_array[n]; + double lambda_max = deaths[cluster]; + + if (lambda_max == 0.0 || tree[n]->lambda_val == DBL_MAX) { + result[point] = 0.0; + } else { + result[point] = (lambda_max - tree[n]->lambda_val) / lambda_max; + } + } + + return result; +} + +boost::unordered_map HDBScan::compute_stability(vector& tree) +{ + int largest_child = tree[0]->child; + int smallest_cluster = tree[0]->parent; + int largest_cluster = tree[0]->parent; + for (int i=1; ichild > largest_child) { + largest_child = tree[i]->child; + } + if (tree[i]->parent < smallest_cluster) { + smallest_cluster = tree[i]->parent; + } + if (tree[i]->parent > largest_cluster) { + largest_cluster = tree[i]->parent; + } + } + int num_clusters = largest_cluster - smallest_cluster + 1; + + if (largest_child < smallest_cluster) { + largest_child = smallest_cluster; + } + + vector > sorted_child_data(tree.size()); + for (int i=0; ichild; + sorted_child_data[i].second = tree[i]->lambda_val; + } + std::sort(sorted_child_data.begin(), sorted_child_data.end()); + + vector births(largest_child + 1, -1); + + int current_child = -1; + double min_lambda = 0; + + int child; + double lambda_; + + for (int row=0; row < sorted_child_data.size(); row++) { + child = sorted_child_data[row].first; + lambda_ = sorted_child_data[row].second; + + if (child == current_child) { + min_lambda = min(min_lambda, lambda_); + } else if ( current_child != -1) { + births[current_child] = min_lambda; + current_child = child; + min_lambda = lambda_; + } else { + // Initialize + current_child = child; + min_lambda = lambda_; + } + } + + if (current_child != -1) { + births[current_child] = min_lambda; + } + + births[smallest_cluster] = 0.0; + + vector result_arr(num_clusters, 0); + + for (int i=0; iparent; + double lambda_ = tree[i]->lambda_val; + int child_size = tree[i]->child_size; + int result_index = parent - smallest_cluster; + result_arr[result_index] += (lambda_ - births[parent]) * child_size; + } + + boost::unordered_map stability; + for (int i=smallest_cluster, cnt=0; i HDBScan::do_labelling(vector& tree, set& clusters, + boost::unordered_map& cluster_label_map, + bool allow_single_cluster, + bool match_reference_implementation) +{ + int root_cluster = tree[0]->parent; //root_cluster = parent_array.min() + int parent_array_max = tree[0]->parent; + for (int i=1; iparent < root_cluster) { + root_cluster = tree[i]->parent; + } + if (tree[i]->parent > parent_array_max) { + parent_array_max = tree[i]->parent; + } + } + vector result(root_cluster); + + TreeUnionFind union_find(parent_array_max + 1); + + for (int n=0; nchild; + int parent = tree[n]->parent; + if (clusters.find(child) ==clusters.end() ) { + union_find.union_(parent, child); + } + } + + for (int n=0; nchild == n) { + c_lambda = tree[j]->lambda_val; + } + if (tree[j]->parent == cluster) { + if (tree[j]->lambda_val > p_lambda) { + p_lambda = tree[j]->lambda_val; + } + } + } + if (c_lambda >= p_lambda && p_lambda > -1) { + result[n] = cluster_label_map[cluster]; + } + } + + } else { + if (match_reference_implementation) { + double point_lambda=-1, cluster_lambda=-1; + for (int j=0; jchild == n) { + point_lambda = tree[j]->lambda_val; + break; + } + } + for (int j=0; jchild == cluster) { + cluster_lambda = tree[j]->lambda_val; + break; + } + } + if (point_lambda > cluster_lambda && cluster_lambda > -1) { + result[n] = cluster_label_map[cluster]; + } else { + result[n] = -1; + } + } else { + result[n] = cluster_label_map[cluster]; + } + } + } + return result; +} + +vector HDBScan::get_probabilities(vector& tree, + boost::unordered_map& cluster_map, + vector& labels) +{ + vector result(labels.size(), 0); + + vector deaths = max_lambdas(tree); + int root_cluster = tree[0]->parent; + for (int i=0; iparent < root_cluster) { + root_cluster = tree[i]->parent; + } + } + + int cluster_num; + int cluster; + double max_lambda; + double lambda_; + + for (int n=0; nchild; + if (point >= root_cluster) { + continue; + } + + cluster_num = labels[point]; + + if (cluster_num == -1) { + continue; + } + + cluster = cluster_map[cluster_num]; + max_lambda = deaths[cluster]; + + if (max_lambda == 0.0 || tree[n]->lambda_val == DBL_MAX) { + result[point] = 1.0; + } else { + lambda_ = min(tree[n]->lambda_val, max_lambda); + result[point] = lambda_ / max_lambda; + } + } + return result; +} + +vector HDBScan::get_stability_scores(vector& labels, set& clusters, + boost::unordered_map& stability, + double max_lambda) +{ + vector result(clusters.size()); + + vector clusters_; + set::iterator it; + for (it=clusters.begin(); it!= clusters.end(); it++) { + clusters_.push_back(*it); + } + sort(clusters_.begin(), clusters_.end()); + + for (int n=0; n HDBScan::max_lambdas(vector& tree) +{ + int largest_parent = tree[0]->parent; + + for (int i=1; iparent > largest_parent) { + largest_parent= tree[i]->parent; + } + } + + vector > sorted_parent_data(tree.size()); + for (int i=0; iparent; + sorted_parent_data[i].second = tree[i]->lambda_val; + } + sort(sorted_parent_data.begin(), sorted_parent_data.end()); + + vector deaths(largest_parent + 1, 0); + + int current_parent = -1; + double max_lambda = 0; + + for (int row=0; row& tree, + boost::unordered_map& stability, + vector& out_labels, + vector& out_probs, + vector& out_stabilities, + int cluster_selection_method, + bool allow_single_cluster, + bool match_reference_implementation) +{ + vector node_list; + boost::unordered_map::iterator sit; + for (sit = stability.begin(); sit!=stability.end(); sit++) { + node_list.push_back(sit->first); + } + std::sort(node_list.begin(), node_list.end(), std::greater()); + if (!allow_single_cluster) { + // exclude root + node_list.pop_back(); + } + + vector cluster_tree; + for (int i=0; ichild_size > 1) { + cluster_tree.push_back(tree[i]); + } + } + + boost::unordered_map is_cluster; + for (int i=0; ichild_size == 1) { + if (tree[i]->child > num_points) { + num_points = tree[i]->child; + } + } + } + num_points += 1; + + double max_lambda = tree[0]->lambda_val; + for (int i=1; ilambda_val > max_lambda) { + max_lambda = tree[i]->lambda_val; + } + } + + if (cluster_selection_method == 0) { + // eom + for (int i=0; iparent == node) { + //child_selection.push_back(node); + int child = cluster_tree[j]->child; + subtree_stability += stability[child]; + } + } + + if (subtree_stability > stability[node]) { + is_cluster[node] = false; + stability[node] = subtree_stability; + } else { + vector sub_nodes = bfs_from_cluster_tree(cluster_tree, node); + for (int j=0; jparent; + for (int i=1; iparent < parent_min) { + parent_min = tree[i]->parent; + } + } + boost::unordered_map::iterator it; + + vector leaves_ = get_cluster_tree_leaves(cluster_tree); + set leaves; + for (int i=0; ifirst] = false; + } + is_cluster[parent_min] = true; + } + for (it=is_cluster.begin(); it!=is_cluster.end(); it++) { + int c = it->first; + if (leaves.find(c) != leaves.end()) { + is_cluster[c] = true; + } else { + is_cluster[c] = false; + } + } + } + + set clusters; + boost::unordered_map::iterator it; + for (it = is_cluster.begin(); it!= is_cluster.end(); it++) { + int c = it->first; + if (it->second) { + clusters.insert(c); + } + } + vector _clusters; + set::iterator _it; + for (_it =clusters.begin(); _it != clusters.end(); _it++) { + _clusters.push_back(*_it); + } + + std::sort(_clusters.begin(), _clusters.end()); + + boost::unordered_map cluster_map, reverse_cluster_map; + for (int i=0; i<_clusters.size(); i++) { + cluster_map[_clusters[i]] = i; + reverse_cluster_map[i] = _clusters[i]; + } + + // do labeling (tree, clusters, cluster_map, False, False + out_labels = do_labelling(tree, clusters, cluster_map, allow_single_cluster, match_reference_implementation); + + // probs = get_probabilities(tree, reverse_cluster_map, labels) + out_probs = get_probabilities(tree, reverse_cluster_map, out_labels); + + // stabilities = get_stability_scores(labels, clusters, stability, max_lambda) + out_stabilities = get_stability_scores(out_labels, clusters, stability, max_lambda); +} + +vector HDBScan::get_cluster_tree_leaves(vector& cluster_tree) +{ + vector result; + + if (cluster_tree.size()==0) { + return result; + } + + int root = cluster_tree[0]->parent; + for (int i=0; iparent < root) { + root = cluster_tree[i]->parent; + } + } + + return recurse_leaf_dfs(cluster_tree, root); + +} + +vector HDBScan::recurse_leaf_dfs(vector& cluster_tree, int current_node) +{ + vector result; + vector children; + for (int i=0; iparent == current_node) { + children.push_back(cluster_tree[i]->child); + } + } + + if (children.size() == 0) { + result.push_back(current_node); + return result; + + } else { + for (int i=0; i tmp = recurse_leaf_dfs(cluster_tree, child); + for (int j=0; j& core_distances, double** dist_metric, double alpha) +{ + int dim = core_distances.size(); + + double current_node_core_distance; + vector in_tree(dim,0); + int current_node = 0; + vector current_distances(dim, DBL_MAX); + + for (int i=1; i right_value || core_value > right_value || left_value > right_value) { + if (right_value < new_distance) { + new_distance = right_value; + new_node = j; + } + continue; + } + + if (core_value > current_node_core_distance) { + if (core_value > left_value) { + left_value = core_value; + } + } else { + if (current_node_core_distance > left_value) { + left_value = current_node_core_distance; + } + } + + if (left_value < right_value) { + current_distances[j] = left_value; + if (left_value < new_distance) { + new_distance = left_value; + new_node = j; + } + } else { + if (right_value < new_distance) { + new_distance = right_value; + new_node = j; + } + } + } + mst_edges.push_back(new SimpleEdge(current_node, new_node, new_distance)); + + current_node = new_node; + } +} diff --git a/Algorithms/hdbscan.h b/Algorithms/hdbscan.h new file mode 100644 index 000000000..7eea18764 --- /dev/null +++ b/Algorithms/hdbscan.h @@ -0,0 +1,319 @@ +/** + * GeoDa TM, Copyright (C) 2011-2015 by Luc Anselin - all rights reserved + * + * This file is part of GeoDa. + * + * GeoDa is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * GeoDa is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * Created: 5/30/2017 lixun910@gmail.com + */ + +#ifndef __GEODA_CENTER_HDBSCAN_H__ +#define __GEODA_CENTER_HDBSCAN_H__ + +#include +#include +#include + +#include "../kNN/ANN.h" +#include "redcap.h" + +using namespace SpanningTreeClustering; + +namespace GeoDaClustering { + struct IdxCompare + { + const std::vector& target; + + IdxCompare(const std::vector& target): target(target) {} + + bool operator()(int a, int b) const { return target[a] < target[b]; } + }; + + class SimpleEdge + { + public: + int orig; + int dest; + double length; + + SimpleEdge(int o, int d, double l) { + orig = o; + dest = d; + length = l; + } + ~SimpleEdge(){} + }; + + class UnionFind + { + public: + int* parent; + int* size; + int next_label; + + public: + UnionFind(int N) { + parent = new int[2*N-1]; + for (int i=0; i<2*N-1; i++) { + parent[i] = -1; + } + next_label = N; + size = new int[2*N -1]; + for (int i=0; i<2*N -1; i++) { + if (i < N) { + size[i] = 1; + } else { + size[i] = 0; + } + } + + } + ~UnionFind() { + delete[] parent; + delete[] size; + } + + int fast_find(int n) { + int p = n; + while (parent[n] != -1) { + n = parent[n]; + } + // label up to the root + while (parent[p] != n) { + parent[p] = n; + p = parent[p]; + } + return n; + } + + void Union(int m, int n) { + size[next_label] = size[m] + size[n]; + parent[m] = next_label; + parent[n] = next_label; + size[next_label] = size[m] + size[n]; + next_label += 1; + } + }; + + class TreeUnionFind + { + public: + vector is_component; + vector > _data; + + TreeUnionFind(int size) { + _data.resize(size); + is_component.resize(size); + for (int i=0; i _data[y_root].second) { + _data[y_root].first = x_root; + } else { + _data[y_root].first = x_root; + _data[x_root].second += 1; + } + } + + int find(int x) { + if (_data[x].first != x) { + _data[x].first = find(_data[x].first); + is_component[x] = false; + } + return _data[x].first; + } + + vector components() { + vector c; + for (int i=0; i mst_edges; + vector condensed_tree; + vector core_dist; + vector labels; + vector probabilities; + vector stabilities; + vector outliers; + + HDBScan(int min_points, + int min_samples, + double alpha, + int cluster_selection_method, + bool allow_single_cluster, + int rows, int cols, + double** _distances, + double** data, + const vector& undefs + //GalElement * w, + //double* controls, + //double control_thres + ); + virtual ~HDBScan(); + + vector > GetRegions(); + + vector outlier_scores(vector& tree); + + boost::unordered_map compute_stability(vector& condensed_tree); + + void condense_tree(double** hierarchy, int N, int min_cluster_size=10); + + vector max_lambdas(vector& tree); + + vector do_labelling(vector& tree, set& clusters, + boost::unordered_map& cluster_label_map, + bool allow_single_cluster = false, + bool match_reference_implementation = false); + + vector get_probabilities(vector& tree, + boost::unordered_map& reverse_cluster_map, + vector& labels); + + vector get_stability_scores(vector& labels, set& clusters, + boost::unordered_map& stability, + double max_lambda); + + void get_clusters(vector& tree, + boost::unordered_map& stability, + vector& out_labels, + vector& out_probs, + vector& out_stabilities, + int cluster_selection_method=0, + bool allow_single_cluster= false, + bool match_reference_implementation=false); + + void mst_linkage_core_vector(int num_features, + vector& core_distances, + double** dist_metric, double alpha); + + vector get_cluster_tree_leaves(vector& cluster_tree); + + vector recurse_leaf_dfs(vector& cluster_tree, int current_node); + + vector bfs_from_hierarchy(double** hierarchy, int dim, int bfs_root) + { + int max_node = 2* dim; + int num_points = max_node - dim + 1; + + vector to_process; + to_process.push_back(bfs_root); + + vector result; + while (!to_process.empty()) { + for (int i=0; i tmp; + for (int i=0; i= num_points) { + int x = to_process[i] - num_points; + tmp.push_back(x); + } + } + to_process.clear(); + if (!tmp.empty()) { + for (int i=0; i bfs_from_cluster_tree(vector& tree, int bfs_root) + { + vector result; + set to_process; + set::iterator it; + + to_process.insert(bfs_root); + + while (!to_process.empty()) { + for (it = to_process.begin(); it != to_process.end(); it++) { + result.push_back(*it); + } + set tmp; + for (int i=0; iparent) != to_process.end() ) { + tmp.insert( tree[i]->child); + } + } + to_process = tmp; + } + return result; + } + }; + +} +#endif diff --git a/Algorithms/lisa_kernel.cl b/Algorithms/lisa_kernel.cl new file mode 100755 index 000000000..dd9b91c35 --- /dev/null +++ b/Algorithms/lisa_kernel.cl @@ -0,0 +1,91 @@ +#pragma OPENCL EXTENSION cl_khr_fp64 : enable +float wang_rnd(uint seed); +float wang_rnd(uint seed) +{ + uint maxint=0; + maxint--; // not ok but works + + seed = (seed ^ 61) ^ (seed >> 16); + seed *= 9; + seed = seed ^ (seed >> 4); + seed *= 0x27d4eb2d; + seed = seed ^ (seed >> 15); + + return ((float)seed)/(float)maxint; +} + +__kernel void lisa(const int n, const int permutations, const unsigned long last_seed, __global double *values, __global double *local_moran, __global int *num_nbrs, __global int *nbr_idx, __global double *p) { + + // Get the index of the current element + size_t i = get_global_id(0); + + if (i >= n) { + return; + } + + size_t j = 0; + size_t seed_start = i + last_seed; + + size_t numNeighbors = num_nbrs[i]; + if (numNeighbors == 0) { + return; + } + + size_t nbr_start = 0; + + for (j=0; j local_moran[i]) { + countLarger++; + } + } + + // pick the smallest + if (permutations-countLarger <= countLarger) { + countLarger = permutations-countLarger; + } + + double sigLocal = (countLarger+1.0)/(permutations+1); + p[i] = sigLocal; +} diff --git a/Algorithms/localjc_kernel.cl b/Algorithms/localjc_kernel.cl new file mode 100755 index 000000000..f750820a7 --- /dev/null +++ b/Algorithms/localjc_kernel.cl @@ -0,0 +1,88 @@ +#pragma OPENCL EXTENSION cl_khr_fp64 : enable +float wang_rnd(uint seed); +float wang_rnd(uint seed) +{ + uint maxint=0; + maxint--; // not ok but works + + seed = (seed ^ 61) ^ (seed >> 16); + seed *= 9; + seed = seed ^ (seed >> 4); + seed *= 0x27d4eb2d; + seed = seed ^ (seed >> 15); + + return ((float)seed)/(float)maxint; +} + +__kernel void localjc(const int n, const int permutations, const unsigned long last_seed, const unsigned long num_vars, __global unsigned short *zz, __global unsigned short *local_jc, __global unsigned short *num_nbrs, __global unsigned short *nbr_idx, __global float *p) { + // Get the index of the current element + int i = get_global_id(0); + if (i >= n) { + return; + } + if (local_jc[i] == 0) { + p[i] = 0; + return; + } + int j = 0; + size_t seed_start = i + last_seed; + size_t rnd_numbers[888]; + unsigned char dict[999]; + for (j=0; j<999; j++) dict[j] = 0; + + size_t numNeighbors = num_nbrs[i]; + if (numNeighbors == 0) { + return; + } + + size_t nbr_start = 0; + + for (j=0; j = local_jc[i]) { + countLarger++; + } + } + + if (permutations-countLarger < countLarger) { + countLarger = permutations-countLarger; + } + p[i] = permutations + 1; + countLarger = countLarger + 1.0; + p[i] = countLarger/p[i]; +} + + diff --git a/Algorithms/maxp.cpp b/Algorithms/maxp.cpp index 3f00186aa..6078fb7a6 100644 --- a/Algorithms/maxp.cpp +++ b/Algorithms/maxp.cpp @@ -21,71 +21,108 @@ #include #include +#include #include +#include #include #include +#include +#include +#include #include "../ShapeOperations/GalWeight.h" #include "../logger.h" #include "../GenUtils.h" -#include "cluster.h" #include "maxp.h" +using namespace boost; using namespace std; -Maxp::Maxp(const GalElement* _w, const vector >& _z, int floor, vector > floor_variable, int initial, vector seed) -: w(_w), z(_z), LARGE(1000000), MAX_ATTEMPTS(100) +Maxp::Maxp(const GalElement* _w, const vector >& _z, double _floor, double* _floor_variable, int _initial, vector _seeds, int _method, int _tabu_length, double _cool_rate,int _rnd_seed, char _dist, bool _test ) +: w(_w), z(_z), floor(_floor), floor_variable(_floor_variable), initial(_initial), LARGE(1000000), MAX_ATTEMPTS(100), rnd_seed(_rnd_seed), test(_test), initial_wss(_initial), regions_group(_initial), area2region_group(_initial), p_group(_initial), dist(_dist), best_ss(DBL_MAX), method(_method), tabu_length(_tabu_length), cooling_rate(_cool_rate) { - num_obs = floor_variable.size(); - - if (random_state<0) { + num_obs = z.size(); + num_vars = z[0].size(); + + if (test) { + initial = 2; + floor = 5; + } + + // setup random number + if (rnd_seed<0) { unsigned int initseed = (unsigned int) time(0); srand(initseed); } else { - srand(random_state); + srand(rnd_seed); } - + seed_start = rand(); + seed_increment = MAX_ATTEMPTS * num_obs * 10000; // init solution - init_solution(); - if (p != 0) + if (_seeds.empty()) { + init_solution(-1); + } else { + map > region_dict; + for (int i=0; i< _seeds.size(); i++) { + int rgn = _seeds[i]; + this->area2region[i] = rgn; + if (region_dict.find(rgn) == region_dict.end()) { + vector ids; + ids.push_back(i); + region_dict[rgn] = ids; + } else { + region_dict[rgn].push_back(i); + } + } + map >::iterator it; + for (it = region_dict.begin(); it!= region_dict.end(); it++) { + this->regions.push_back(it->second); + } + this->p = this->regions.size(); + + GenUtils::sort(_seeds, _seeds, seeds); + } + + if (p == 0) feasible = false; else { feasible = true; - double best_val = objective_function(); - // deep copy - vector > current_regions = regions; - map current_area2region = area2region; - vector initial_wss; + + best_ss = objective_function(); + vector > best_regions; + unordered_map best_area2region; + int attemps = 0; + // parallize following block, comparing the objective_function() return values + //for (int i=0; i 0) { - double val = objective_function(); - initial_wss.push_back(val); - - wxString str; - str << "initial solution"; - str << i; - str << val; - str << best_val; - LOG_MSG(str.ToStdString()); + vector >& current_regions = regions_group[i]; + unordered_map& current_area2region = area2region_group[i]; + + //print_regions(current_regions); + LOG_MSG(initial_wss[i]); + + if (p_group[i] > 0) { + double val = initial_wss[i]; - if (val < best_val) { - current_regions = regions; - current_area2region = area2region; - best_val = val; + if (val < best_ss) { + best_regions = current_regions; + best_area2region = current_area2region; + best_ss = val; } attemps += 1; } } - regions = current_regions; - p = regions.size(); - area2region = current_area2region; - - swap(); + if (!best_regions.empty()) { + regions = best_regions; + p = regions.size(); + area2region = best_area2region; + } } } @@ -94,61 +131,102 @@ Maxp::~Maxp() } -double Maxp::objective_function() +wxString Maxp::print_regions(vector >& _regions) { - double wss = 0; - // for every variable, calc the variance using selected neighbors - vector > selected_z; - - //for (int n=0; n<) - for (int n=0; n val; - for (int i=0; i& region) +void Maxp::run_threaded() { - double cv = 0; - for (size_t i=0; i& f_v = floor_variable[ region[i] ]; - for (size_t j=0; j 0) ? nCPUs : remainder; + + boost::thread_group threadPool; + for (int i=0; i= floor) - return true; - else - return false; + + threadPool.join_all(); +} + +vector >& Maxp::GetRegions() +{ + return regions; } -void Maxp::init_solution() +void Maxp::init_solution(int solution_idx) { - p = 0; + uint64_t seed_local = seed_start + (solution_idx+1) * seed_increment; + int p = 0; bool solving = true; int attempts = 0; + vector > _regions; + unordered_map _area2region; + while (solving && attempts <= MAX_ATTEMPTS) { - vector > regions; + vector > regn; list enclaves; list candidates; - if (seed.empty()) { - vector _candidates; - for (int i=0; i candidates_dict; + + if (seeds.empty()) { + vector _candidates(num_obs); + for (int i=0; i=1; --i) { + int k = Gda::ThomasWangHashDouble(seed_local++) * (i+1); + while (k>=i) k = Gda::ThomasWangHashDouble(seed_local++) * (i+1); + if (k != i) std::iter_swap(_candidates.begin() + k, _candidates.begin()+i); + } + for (int i=0; i cand_dict; + unordered_map::iterator it; + for (int i=0; ifirst); + candidates_dict[ it->first ] = true; + } } list::iterator iter; @@ -161,181 +239,888 @@ void Maxp::init_solution() // try to grow it till threshold constraint is satisfied vector region; region.push_back(seed); - + unordered_map region_dict; + region_dict[seed] = true; + candidates_dict[seed] = false; - bool building_region = true; - while (building_region) { - // check if floor is satisfied - if (check_floor(region)) { - regions.push_back(region); - building_region = false; - } else { - vector potential; - for (int area=0; area= floor) { + is_floor = true; } - building_region = false; } } } + if (is_floor) { + unordered_map::iterator rit; + vector _region; + for (rit=region_dict.begin(); rit!=region_dict.end();rit++) { + if (rit->second) + _region.push_back(rit->first); + } + regn.push_back(_region); + } } // check to see if any regions were made before going to enclave stage bool feasible =false; - if (!regions.empty()) + if (!regn.empty()) feasible = true; else { attempts += 1; break; } // self.enclaves = enclaves[:] - map a2r; - for (int i=0; i a2r; + for (int i=0; i 0 && encAttempts != encCount) { + while (enclaves.size() > 0 && encAttempts != encCount) { int enclave = enclaves.front(); enclaves.pop_front(); + // find regions that close to this enclaved region + set _cand; + for ( int n=0; n::iterator iter_s = _cand.begin(); + std::advance(iter_s, regID); + int rid = *iter_s; + + regn[rid].push_back(enclave); a2r[enclave] = rid; + // structure to loop over enclaves until no more joining is possible encCount = enclaves.size(); encAttempts = 0; feasible = true; - */ + } else { // put back on que, no contiguous regions yet enclaves.push_back(enclave); encAttempts += 1; feasible = false; } - - if (feasible) { + } + + if (feasible) { + double ss = objective_function(regn); + if (ss < best_ss) { // just need to be better than first initial solution solving = false; - p = regions.size(); + p = regn.size(); + _regions = regn; + _area2region = a2r; + } + } else { + if (attempts == MAX_ATTEMPTS) { + LOG_MSG("No initial solution found"); + p = 0; + } + } + attempts += 1; + } + + if (solution_idx >=0) { + if (_regions.empty()) { + p_group[solution_idx] = 0; + initial_wss[solution_idx] = 0; + } else { + // apply local search + if (method == 0) { + swap(_regions, _area2region, seed_local); + } else if (method == 1) { + tabu_search(_regions, _area2region, tabu_length, seed_local); } else { - if (attempts == MAX_ATTEMPTS) { - LOG_MSG("No initial solution found"); - p = 0; + double temperature = 1.0; + simulated_annealing(_regions, _area2region, cooling_rate, temperature, seed_local); + } + + regions_group[solution_idx] = _regions; + area2region_group[solution_idx] = _area2region; + p_group[solution_idx] = p; + initial_wss[solution_idx] = objective_function(_regions); + } + } else { + if (this->regions.empty()) { + this->regions = _regions; + this->area2region = _area2region; + this->p = p; + } else { + best_ss = objective_function(); + if (objective_function(_regions) < best_ss) { + this->regions = _regions; + this->area2region = _area2region; + this->p = p; + } + } + + } +} + +void Maxp::shuffle(vector& arry, uint64_t& seed) +{ + //random_shuffle + for (int i=arry.size()-1; i>=1; --i) { + int k = Gda::ThomasWangHashDouble(seed++) * (i+1); + while (k>=i) k = Gda::ThomasWangHashDouble(seed++) * (i+1); + if (k != i) std::iter_swap(arry.begin() + k, arry.begin()+i); + } +} + + +void Maxp::simulated_annealing(vector >& init_regions, unordered_map& init_area2region, double alpha, double temperature, uint64_t seed_local) +{ + vector > local_best_solution; + unordered_map local_best_area2region; + double local_best_ssd = 1; + + int nr = init_regions.size(); + vector changed_regions(nr, 1); + + bool use_sa = false; + double T = 1; // temperature + // Openshaw's Simulated Annealing for AZP algorithm + int maxit = 0; + + while ( T > 0.1 || maxit < 3 ) { + //while ( maxit < 3 ) { + int improved = 0; + + bool swapping = true; + int total_move = 0; + int nr = init_regions.size(); + vector::iterator iter; + vector changed_regions(nr, 1); + while (swapping) { + int moves_made = 0; + vector regionIds; + for (int r=0; r0) { + regionIds.push_back(r); + //} + } + shuffle(regionIds, seed_local); + for (int r=0; r::iterator m_it, n_it; + unordered_map member_dict, neighbors_dict; + for (int j=0; j candidates; + for (n_it=neighbors_dict.begin(); n_it!=neighbors_dict.end(); n_it++) { + int nbr = n_it->first; + vector& block = init_regions[ init_area2region[ nbr ] ]; + if (check_floor(block, nbr)) { + if (check_contiguity(w, block, nbr)) { + candidates.push_back(nbr); + } + } + } + // find the best local move + if (use_sa) { + // use Simulated Annealing + double cv = 0.0; + int best = 0; + bool best_found = false; + for (int j=0; j& current_internal = init_regions[seed]; + vector& current_outter = init_regions[init_area2region[area]]; + double change = objective_function_change(area, current_internal, current_outter); + change = -change / (local_best_ssd * T); + if (exp(change) > Gda::ThomasWangHashDouble(seed_local++)) { + best = area; + cv = change; + best_found = true; + } + } + if (best_found) { + // make the move + int area = best; + int old_region = init_area2region[area]; + vector& rgn = init_regions[old_region]; + rgn.erase(remove(rgn.begin(),rgn.end(), area), rgn.end()); + + init_area2region[area] = seed; + init_regions[seed].push_back(area); + + moves_made += 1; + changed_regions[seed] = 1; + changed_regions[old_region] = 1; + } + } else { + while (!candidates.empty()) { + double cv = 0.0; + int best = 0; + bool best_found = false; + for (int j=0; j& current_internal = init_regions[seed]; + vector& current_outter = init_regions[init_area2region[area]]; + double change = objective_function_change(area, current_internal, current_outter); + if (change <= cv) { + best = area; + cv = change; + best_found = true; + } + } + candidates.clear(); + if (best_found) { + // make the move + int area = best; + int old_region = init_area2region[area]; + vector& rgn = init_regions[old_region]; + rgn.erase(remove(rgn.begin(),rgn.end(), area), rgn.end()); + + init_area2region[area] = seed; + init_regions[seed].push_back(area); + + moves_made += 1; + changed_regions[seed] = 1; + changed_regions[old_region] = 1; + + // update candidates list after move in + member_dict[area] = true; + neighbors_dict[area] = false; + for (int k=0; k& block = init_regions[ init_area2region[ nbr ] ]; + if (check_floor(block, nbr)) { + if (check_contiguity(w, block, nbr)) { + candidates.push_back(nbr); + neighbors_dict[nbr] = true; + } + } + } + } + } } - attempts += 1; + } + total_move += moves_made; + if (moves_made == 0) { + swapping = false; + total_moves = total_move; + } else { + if (use_sa) use_sa = false; // a random move is made using SA + } + } + + if (local_best_solution.empty()) { + improved = 1; + local_best_solution = init_regions; + local_best_area2region = init_area2region; + local_best_ssd = objective_function(init_regions); + } else { + double current_ssd = objective_function(init_regions); + if ( current_ssd < local_best_ssd) { + improved = 1; + local_best_solution = init_regions; + local_best_area2region = init_area2region; + local_best_ssd = current_ssd; } } + if (improved == 1) { + use_sa = false; + T = 1; + maxit = 0; + } else { + maxit += 1; + T *= alpha; + use_sa = true; + } + } + // make sure tabu result is no worse than greedy research + double search_best_ssd = objective_function(init_regions); + if (local_best_ssd < search_best_ssd) { + init_regions = local_best_solution; + init_area2region = local_best_area2region; } } -void Maxp::swap() +void Maxp::tabu_search(vector >& init_regions, unordered_map& init_area2region, int tabuLength, uint64_t seed_local) { + vector > local_best_solution; + unordered_map local_best_area2region; + double local_best_ssd; + + int nr = init_regions.size(); + + vector changed_regions(nr, 1); + // tabuLength: Number of times a reverse move is prohibited. Default value tabuLength = 85. + int convTabu = 230 * sqrt((double)nr); + // convTabu=230*numpy.sqrt(maxP) + vector tabuList; + + bool use_tabu = false; + int c = 0; + + while ( c regionIds; + for (int r=0; r0 || use_tabu) { + regionIds.push_back(r); + //} + } + shuffle(regionIds, seed_local); + for (int r=0; r::iterator m_it, n_it; + unordered_map member_dict, neighbors_dict; + + for (int j=0; j candidates; + for (n_it=neighbors_dict.begin(); n_it!=neighbors_dict.end(); n_it++) { + int nbr = n_it->first; + vector& block = init_regions[ init_area2region[ nbr ] ]; + if (check_floor(block, nbr)) { + if (check_contiguity(w, block, nbr)) { + candidates.push_back(nbr); + } + } + } + // find the best local move to improve current region + if (use_tabu == false) { + double cv = 0.0; + int best = -1; + bool best_found = false; + for (int j=0; j& current_internal = init_regions[seed]; + vector& current_outter = init_regions[init_area2region[area]]; + if (!tabuList.empty()) { + TabuMove tabu(area, init_area2region[area], seed); + if ( find(tabuList.begin(), tabuList.end(), tabu) != tabuList.end() ) + continue; + } + double change = objective_function_change(area, current_internal, current_outter); + if (change <= cv) { + best = area; + cv = change; + best_found = true; + } + } + + if (best_found) { + int area = best; + if (init_area2region.find(area) != init_area2region.end()) { + int old_region = init_area2region[area]; + // make the move + move(area, old_region, seed, init_regions, init_area2region, tabuList,tabuLength); + num_move ++; + changed_regions[seed] = 1; + changed_regions[old_region] = 1; + } + } + } else { + double cv = 0.0; + int best = -1; + bool best_found = false; + for (int j=0; j& current_internal = init_regions[seed]; + vector& current_outter = init_regions[init_area2region[area]]; + // prohibit tabu + TabuMove tabu(area, init_area2region[area], seed); + if ( find(tabuList.begin(), tabuList.end(), tabu) != tabuList.end() ) + continue; + double change = objective_function_change(area, current_internal, current_outter); + if (j ==0 || change <= cv) { + best = area; + cv = change; + best_found = true; + } + } + + if (best_found) { + int area = best; + if (init_area2region.find(area) != init_area2region.end()) { + int old_region = init_area2region[area]; + // make the move + move(area, old_region, seed, init_regions, init_area2region, tabuList,tabuLength); + num_move ++; + changed_regions[seed] = 1; + changed_regions[old_region] = 1; + } + } + c++; + } + } + + // all regions are checked with possible moves + if (num_move ==0) { + // if no improving move can be made, then see if a tabu move can be made (relaxing its basic rule) which improves on the current local best (termed an aspiration move) + use_tabu = true; + + if (local_best_solution.empty()) { + local_best_solution = init_regions; + local_best_area2region = init_area2region; + local_best_ssd = objective_function(init_regions); + } else { + double current_ssd = objective_function(init_regions); + if ( current_ssd < local_best_ssd ) { + local_best_solution = init_regions; + local_best_area2region = init_area2region; + local_best_ssd = current_ssd; + } + } + + } else { + // some moves just made + if (use_tabu == true) + use_tabu = false; // switch from tabu to regular move + else + c = 0; // always reset tabu since a move is just made + } + } + // make sure tabu result is no worse than greedy research + double search_best_ssd = objective_function(init_regions); + if (local_best_ssd < search_best_ssd) { + init_regions = local_best_solution; + init_area2region = local_best_area2region; + } +} + + +void Maxp::move(int area, int from_region, int to_region, vector >& _regions, unordered_map& _area2region) +{ + vector& rgn = _regions[from_region]; + rgn.erase(remove(rgn.begin(),rgn.end(), area), rgn.end()); + + _area2region[area] = to_region; + _regions[to_region].push_back(area); +} + +void Maxp::move(int area, int from_region, int to_region, vector >& _regions, unordered_map& _area2region, vector& tabu_list, int max_labu_length) +{ + vector& rgn = _regions[from_region]; + rgn.erase(remove(rgn.begin(),rgn.end(), area), rgn.end()); + + _area2region[area] = to_region; + _regions[to_region].push_back(area); + + TabuMove tabu(area, from_region, to_region); + + if ( find(tabu_list.begin(), tabu_list.end(), tabu) == tabu_list.end() ) { + if (tabu_list.size() >= max_labu_length) { + tabu_list.pop_back(); + } + tabu_list.insert(tabu_list.begin(), tabu); + } +} + +void Maxp::swap(vector >& init_regions, unordered_map& init_area2region, uint64_t seed_local) +{ + // local search AZP + bool swapping = true; int swap_iteration = 0; - int total_moves = 0; - int k = regions.size(); + int total_move = 0; + int nr = init_regions.size(); vector::iterator iter; - vector changed_regions(k, 1); - while (swapping) { + vector changed_regions(nr, 1); + + // nr = range(k) + while (swapping && total_move<10000) { int moves_made = 0; + + //selects a neighbouring solution at random + // regionIds = [r for r in nr if changed_regions[r]] + vector regionIds; - for (int r=0; r0) { + for (int r=0; r0) { regionIds.push_back(r); - } + //} } - random_shuffle(regionIds.begin(), regionIds.end()); - for (int r=0; r=1; --i) { + int k = Gda::ThomasWangHashDouble(seed_local++) * (i+1); + while (k>=i) k = Gda::ThomasWangHashDouble(seed_local++) * (i+1); + if (k != i) std::iter_swap(regionIds.begin() + k, regionIds.begin()+i); + } + + for (int r=0; r neighbors; - vector& members = regions[seed]; - for (int j=0; j::iterator m_it, n_it; + unordered_map member_dict, neighbors_dict; + + for (int j=0; j candidates; + for (n_it=neighbors_dict.begin(); n_it!=neighbors_dict.end(); n_it++) { + int nbr = n_it->first; + vector& block = init_regions[ init_area2region[ nbr ] ]; + if (check_floor(block, nbr)) { + if (check_contiguity(w, block, nbr)) { + candidates.push_back(nbr); } } - for (int j=0; j block = regions[ area2region[ nbr ] ]; // deep copy - //if (check_contiguity(block, neighbor)) { - // block.erase(neighbor); - //} + } + // find the best local move + while (!candidates.empty()) { + double cv = 0.0; + int best = 0; + bool best_found = false; + for (int j=0; j& current_internal = init_regions[seed]; + vector& current_outter = init_regions[init_area2region[area]]; + double change = objective_function_change(area, current_internal, current_outter); + if (change <= cv) { + best = area; + cv = change; + best_found = true; + } + } + candidates.clear(); + if (best_found) { + // make the move + int area = best; + int old_region = init_area2region[area]; + vector& rgn = init_regions[old_region]; + rgn.erase(remove(rgn.begin(),rgn.end(), area), rgn.end()); + + init_area2region[area] = seed; + init_regions[seed].push_back(area); + + moves_made += 1; + changed_regions[seed] = 1; + changed_regions[old_region] = 1; + + // update candidates list after move in + + member_dict[area] = true; + neighbors_dict[area] = false; + for (int k=0; k& block = init_regions[ init_area2region[ nbr ] ]; + if (check_floor(block, nbr)) { + if (check_contiguity(w, block, nbr)) { + candidates.push_back(nbr); + neighbors_dict[nbr] = true; + } + } + } } } } + total_move += moves_made; + if (moves_made == 0) { + swapping = false; + swap_iterations = swap_iteration; + total_moves = total_move; + } + } +} + +bool Maxp::check_floor(const vector& region, int leaver) +{ + // selectionIDs = [self.w.id_order.index(i) for i in region] + double cv = 0; + for (size_t i=0; i= floor) + return true; + else + return false; +} + +bool Maxp::check_floor(const vector& region) +{ + // selectionIDs = [self.w.id_order.index(i) for i in region] + double cv = 0; + for (size_t i=0; i= floor) + return true; + else + return false; +} + +double Maxp::objective_function() +{ + return objective_function(regions); +} + +double Maxp::objective_function(vector& solution) +{ + //if (objval_dict.find(solution) != objval_dict.end()) { + // return objval_dict[solution]; + //} + + // solution is a list of region ids [1,7,2] + double wss = 0; + + int n_size = solution.size(); + + // for every variable, calc the variance using selected neighbors + for (int m=0; m selected_z(n_size); + + for (int i=0; i& region1, int leaver, vector& region2, int comer ) +{ + // solution is a list of region ids [1,7,2] + double wss = 0; + int j=0; + int n_size = region1.size(); + // for every variable, calc the variance using selected neighbors + for (int m=0; m selected_z(n_size-1); + j = 0; + for (int i=0; i selected_z(n_size+1); + for (int i=0; i >& solution) +{ + // solution is a list of lists of region ids [[1,7,2],[0,4,3],...] such + // that the first region has areas 1,7,2 the second region 0,4,3 and so + // on. solution does not have to be exhaustive + + double wss = 0; + + // for every variable, calc the variance using selected neighbors + + + for (int i=0; i > selected_z(num_vars); + for (int j=0; j& current_internal, vector& current_outter) +{ + vector > composed_region; + composed_region.push_back(current_internal); + composed_region.push_back(current_outter); + + return objective_function(composed_region); +} + + +double Maxp::objective_function_change(int area, vector& current_internal, vector& current_outter) +{ + double current = objective_function(current_internal) + objective_function(current_outter); + double new_val = objective_function(current_outter, area, current_internal, area); + double change = new_val - current; + return change; } bool Maxp::is_component(const GalElement *w, const vector &ids) { + //Check if the set of ids form a single connected component int components = 0; - map masks; - for (int i=0; i marks; + for (int i=0; i q; + list q; + list::iterator iter; for (int i=0; i 1) + return false; + } + while (!q.empty()) { + node = q.back(); + q.pop_back(); + marks[node] = components; + for (int n=0; n& ids, int leaver) +{ + //vector ids = neighbors; + //ids.erase(remove(ids.begin(),ids.end(), leaver), ids.end()); + //return is_component(w, ids); + list q; + unordered_map marks; + for (int i=0; i::iterator it; + for (it=marks.begin(); it!=marks.end(); it++) { + if (it->second == false) + return false; } - return false; + return true; } diff --git a/Algorithms/maxp.h b/Algorithms/maxp.h index 43fb99c1a..c8e616f0b 100644 --- a/Algorithms/maxp.h +++ b/Algorithms/maxp.h @@ -24,11 +24,12 @@ #include #include +#include #include "../ShapeOperations/GalWeight.h" - using namespace std; +using namespace boost; class qvector { @@ -42,11 +43,28 @@ class qvector protected: vector vdata; - map mdict; + unordered_map mdict; vector::iterator v_iter; - map::iterator m_iter; + unordered_map::iterator m_iter; }; +struct TabuMove +{ + int area; + int from_region; + int to_region; + + TabuMove(int _a, int _f, int _t) { + area = _a; + from_region = _f; + to_region = _t; + } + bool operator==(const TabuMove& t) const { + return t.area == area && + t.from_region == from_region && + t.to_region == to_region; + } +}; /*! A Max-p class */ class Maxp @@ -61,7 +79,7 @@ class Maxp \param initial int number of initial solutions to generate \param seed list ids of observations to form initial seeds. If len(ids) is less than the number of observations, the complementary ids are added to the end of seeds. Thus the specified seeds get priority in the solution */ - Maxp(const GalElement* w, const vector >& z, int floor, vector > floor_variable, int initial, vector seed); + Maxp(const GalElement* w, const vector >& z, double floor, double* floor_variable, int initial, vector seeds,int _method, int _tabu_lenght, double _cool_rate, int rnd_seed=-1, char dist='e', bool test=false); //! A Deconstructor @@ -71,6 +89,14 @@ class Maxp ~Maxp(); + //! xxx + /* ! + \param block + \param neighbor + \return boolean + */ + vector >& GetRegions(); + protected: //! A const spatial weights reference. /*! @@ -78,7 +104,15 @@ class Maxp */ const GalElement* w; + int method; + int tabu_length; + + double cooling_rate; + + char dist; + + int rnd_seed; bool feasible; @@ -88,17 +122,23 @@ class Maxp */ int num_obs; + //! A integer number of variables. + /*! + Details. + */ + int num_vars; + //! A vector of vector list of ids to form initial seeds. /*! Details. seed list ids of observations to form initial seeds. */ - vector > seed; + vector seeds; //! A n*1 vector of observations on variable for the floor /*! Details. */ - vector > floor_variable; + double* floor_variable; //! A n*m array of observations on m attributes across n areas. /*! @@ -110,7 +150,11 @@ class Maxp /*! Details. key is area id, value is region id. */ - map area2region; + unordered_map area2region; + + vector > area2region_group; + + unordered_map, double> objval_dict; //! A vector of vector list of lists of regions. /*! @@ -118,12 +162,24 @@ class Maxp */ vector > regions; + vector > > regions_group; + + double best_ss; + //! A integer number of regions. /*! Details. */ int p; + vector p_group; + + //! A integer number of initializations. + /*! + Details. + */ + int initial; + //! A integer number of swap iterations. /*! Details. @@ -140,7 +196,7 @@ class Maxp /*! Details. */ - int floor; + double floor; //! A const integer number of largest regions (=10 ** 6). /*! @@ -152,13 +208,55 @@ class Maxp /*! Details. */ - const int MAX_ATTEMPTS; + int MAX_ATTEMPTS; + + uint64_t seed_start; + + uint64_t seed_increment; + + vector initial_wss; + + //! A protected member function: init_solution(void). + /*! + Details. + */ + void init_solution(int solution_idx=-1); + + void run(int a, int b); + + void run_threaded(); //! A protected member function: init_solution(void). /*! Details. */ - void init_solution(); + void swap(vector >& init_regions, unordered_map& area2region, uint64_t seed_local); + + //! xxx + /* ! + \param + \param neighbor + \return boolean + */ + void tabu_search(vector >& init_regions, unordered_map& init_area2region, int tabuLength, uint64_t seed_local); + + //! xxx + /* ! + \param + \param neighbor + \return boolean + */ + void simulated_annealing(vector >& init_regions, unordered_map& init_area2region, double alpha, double temperature, uint64_t seed_local); + + //! xxx + /* ! + \param + \param neighbor + \return boolean + */ + void move(int area, int from_region, int to_region, vector >& regions, unordered_map& area2region); + + void move(int area, int from_region, int to_region, vector >& regions, unordered_map& area2region, vector& tabu_list, int max_tabu_length); //! A protected member function: init_solution(void). return /*! @@ -167,11 +265,37 @@ class Maxp */ bool check_floor(const vector& region); + bool check_floor(const vector& region, int leaver); + double objective_function(); - - void swap(); + + double objective_function(vector& solution); + + double objective_function(vector& region1, int leaver, vector& region2, int comer); + + double objective_function(vector >& solution); + + double objective_function(vector& current_internal, vector& current_outter); + + double objective_function_change(int area, vector& current_internal, vector& current_outter); + + wxString print_regions(vector >& _regions); + //! xxx + /* ! + \param block + \param neighbor + \return boolean + */ + bool check_contiguity(const GalElement* w, vector& block, int neighbor); bool is_component(const GalElement* w, const vector& ids); + + void shuffle(vector& arry, uint64_t& seed); + + bool test; + list test_random_numbers; + list enclave_random_number; + list > test_random_cand; }; #endif diff --git a/Algorithms/mds.cpp b/Algorithms/mds.cpp new file mode 100644 index 000000000..0617735c7 --- /dev/null +++ b/Algorithms/mds.cpp @@ -0,0 +1,200 @@ + + +#include +#include + +#include "DataUtils.h" +#include "mds.h" + +AbstractMDS::AbstractMDS(int _n, int _dim) +{ + n = _n; + dim = _dim; + result.resize(dim); + for (int i=0; i >& AbstractMDS::GetResult() +{ + return result; +} + +void AbstractMDS::fullmds(vector >& d, int dim, int maxiter) +{ + int k = d.size(); + int n = d[0].size(); + + DataUtils::doubleCenter(d); + DataUtils::squareEntries(d); + DataUtils::multiply(d, -0.5); + + DataUtils::randomize(result); + vector evals(dim); + + DataUtils::eigen(d, result, evals, maxiter); + for (int i = 0; i < dim; i++) { + evals[i] = sqrt(evals[i]); + for (int j = 0; j < k; j++) { + result[i][j] *= evals[i]; + } + } +} + +vector AbstractMDS::pivotmds(vector >& input, vector >& result) +{ + int k = input.size(); + int n = input[0].size(); + + result.empty(); + result.resize(k); + for (int i=0; i evals(k); + DataUtils::doubleCenter(input); + DataUtils::multiply(input, -0.5); + DataUtils::svd(input, result, evals); + for (int i = 0; i < k; i++) { + for (int j = 0; j < n; j++) { + result[i][j] *= sqrt(evals[i]); + } + } + return evals; +} + +FastMDS::FastMDS(vector >& distances, int dim, int maxiter) +: AbstractMDS(distances.size(), dim) +{ + int k = distances.size(); + result.resize(dim); + for (int i=0; i > FastMDS::classicalScaling(vector >& d, int dim, int maxiter) +{ + vector > dist = d; // deep copy + int n = d[0].size(); + /* + vector > dist(d.size()); + for(int i=0; i > result(dim); + for (int i=0; i lambds = lmds(dist, result, maxiter); + return result; +} + +vector FastMDS::lmds(vector >& P, vector >& result, int maxiter) +{ + + vector > distances = P; // deep copy + /* + vector > distances(P.size()); + for (int i=0; i mean(n); + for (int i = 0; i < n; i++) + for (int j = 0; j < k; j++) mean[i] += distances[j][i]; + for (int i = 0; i < n; i++) mean[i] /= k; + + vector lambda(d); + vector > temp(d); + for (int i=0; i > K = DataUtils::landmarkMatrix(P); + //DataUtils::squareEntries(K); + DataUtils::doubleCenter(K); + DataUtils::multiply(K, -0.5); + + vector > E = K; + + DataUtils::eigen(K, temp, lambda, maxiter); + for (int i = 0; i < temp.size(); i++) { + for (int j = 0; j < temp[0].size(); j++) { + temp[i][j] *= sqrt(lambda[i]); + } + } + + //result = temp; + for (int m = 0; m < d; m++) { + for (int i = 0; i < n; i++) { + result[m][i] = temp[m][i]; + } + } + return lambda; +} + +/* +vector > classicalScaling(vector > d, int dim) +{ + int n = d[0].size(); + vector > dist = new double[d.size()][d[0].size()]; + for (int i = 0; i < d.size(); i++) { + for (int j = 0; j < d[0].size(); j++) { + dist[i][j] = d[i][j]; + } + } + vector > result = new double[dim][n]; + DataUtils::randomize(result); + ClassicalScaling.lmds(dist, result); + return result; +} + +vector > classicalScaling(vector > d) +{ + return classicalScaling(d, 2); +} + +vector > stressMinimization(vector > d, vector > w) +{ + return stressMinimization(d, w, 2); +} + +vector > stressMinimization(vector > d, int dim) +{ + vector > x = classicalScaling(d, dim); + StressMinimization sm = new StressMinimization(d, x); + sm.iterate(0, 0, 5); + return x; +} + +vector > stressMinimization(vector > d, vector > w, int dim) +{ + vector > x = classicalScaling(d, dim); + StressMinimization sm = new StressMinimization(d, x, w); + sm.iterate(0, 0, 3); + return x; +} + +vector > stressMinimization(vector > d) +{ + return stressMinimization(d, 2); +} +*/ diff --git a/Algorithms/mds.h b/Algorithms/mds.h new file mode 100644 index 000000000..126e6d359 --- /dev/null +++ b/Algorithms/mds.h @@ -0,0 +1,46 @@ + + +#ifndef __GEODA_CENTER_ALG_MDS_H +#define __GEODA_CENTER_ALG_MDS_H + +#include +#include +#include "DataUtils.h" + +class AbstractMDS { +public: + AbstractMDS(int n, int dim); + ~AbstractMDS(); + + virtual void fullmds(vector >& d, int dim, int maxiter=100); + virtual vector pivotmds(vector >& input, vector >& result); + virtual vector >& GetResult(); + +protected: + int n; + int dim; + vector > result; +}; + +class FastMDS : public AbstractMDS { +public: + FastMDS(vector >& distances, int dim, int maxiter); + virtual ~FastMDS(); + + +protected: + vector > classicalScaling(vector >& d, int dim, int maxiter); + vector lmds(vector >& P, vector >& result, int maxiter); +}; + +/* +class LandmarkMDS : public AbstractMDS { + +}; + +class SMACOF : public AbstractMDS { + +}; +*/ + +#endif diff --git a/Algorithms/pca.cpp b/Algorithms/pca.cpp index acc37dc22..ed828d61a 100755 --- a/Algorithms/pca.cpp +++ b/Algorithms/pca.cpp @@ -9,109 +9,80 @@ using namespace std; using namespace Eigen; -int Pca::Calculate(vector &x, - const unsigned int &nrows, - const unsigned int &ncols, - const bool is_corr, - const bool is_center, - const bool is_scale) { - _ncols = ncols; - _nrows = nrows; - _is_corr = is_corr; - _is_center = is_center; - _is_scale = is_scale; - if (x.size()!= _nrows*_ncols) { - return -1; - } - if ((1 == _ncols) || (1 == nrows)) { - return -1; - } - // Convert vector to Eigen 2-dimensional matrix - //Map _xXf(x.data(), _nrows, _ncols); - _xXf.resize(_nrows, _ncols); - for (unsigned int i = 0; i < _nrows; ++i) { - for (unsigned int j = 0; j < _ncols; ++j) { - _xXf(i, j) = x[j + i*_ncols]; - } - } - // Mean and standard deviation for each column - VectorXf mean_vector(_ncols); - mean_vector = _xXf.colwise().mean(); - VectorXf sd_vector(_ncols); - unsigned int zero_sd_num = 0; - float denom = static_cast((_nrows > 1)? _nrows - 1: 1); - for (unsigned int i = 0; i < _ncols; ++i) { - VectorXf curr_col = VectorXf::Constant(_nrows, mean_vector(i)); // mean(x) for column x - curr_col = _xXf.col(i) - curr_col; // x - mean(x) - curr_col = curr_col.array().square(); // (x-mean(x))^2 - sd_vector(i) = sqrt((curr_col.sum())/denom); - if (0 == sd_vector(i)) { - zero_sd_num++; - } - } - // If colums with sd == 0 are too many, - // don't continue calculations - if (1 > _ncols-zero_sd_num) { - return -1; - } - // Delete columns where sd == 0 - MatrixXf tmp(_nrows, _ncols-zero_sd_num); - VectorXf tmp_mean_vector(_ncols-zero_sd_num); - unsigned int curr_col_num = 0; - for (unsigned int i = 0; i < _ncols; ++i) { - if (0 != sd_vector(i)) { - tmp.col(curr_col_num) = _xXf.col(i); - tmp_mean_vector(curr_col_num) = mean_vector(i); - curr_col_num++; - } else { - _eliminated_columns.push_back(i); - } - } - _ncols -= zero_sd_num; - _xXf = tmp; - mean_vector = tmp_mean_vector; - tmp.resize(0, 0); tmp_mean_vector.resize(0); - // Shift to zero - if (true == _is_center || true == _is_corr ) { - for (unsigned int i = 0; i < _ncols; ++i) { - _xXf.col(i) -= VectorXf::Constant(_nrows, mean_vector(i)); - } - } - // Scale to unit variance - //if ( (false == _is_corr) || (true == _is_scale)) { - if (true == _is_scale || true == _is_corr) { - for (unsigned int i = 0; i < _ncols; ++i) { - _xXf.col(i) /= sqrt(_xXf.col(i).array().square().sum()/denom); +Pca::Pca(double** x, const unsigned int &nrows, const unsigned int &ncols) +{ + _nrows = 0; + _ncols = 0; + // Variables will be scaled by default + _is_center = true; + _is_scale = true; + // By default will be used singular value decomposition + _method = "svd"; + _is_corr = false; + + _kaiser = 0; + _thresh95 = 1; + + _ncols = ncols; + _nrows = nrows; + + // Convert vector to Eigen 2-dimensional matrix + _xXf.resize(_nrows, _ncols); + for (unsigned int i = 0; i < _nrows; ++i) { + for (unsigned int j = 0; j < _ncols; ++j) { + _xXf(i, j) = x[i][j]; + } } - } - #ifdef DEBUG - cout << "\nScaled matrix:\n"; - cout << _xXf << endl; - cout << "\nMean before scaling:\n" << mean_vector.transpose(); - cout << "\nStandard deviation before scaling:\n" << sd_vector.transpose(); - #endif - // When _nrows < _ncols then svd will be used. - // If corr is true and _nrows > _ncols then will be used correlation matrix - // (TODO): What about covariance? - if ( (_nrows < _ncols) || (false == _is_corr)) { // Singular Value Decomposition is on +} + +Pca::~Pca(void) +{ + _xXf.resize(0, 0); + _x.clear(); +} + +std::vector Pca::sd(void) { return _sd; }; +std::vector Pca::prop_of_var(void) {return _prop_of_var; }; +std::vector Pca::cum_prop(void) { return _cum_prop; }; +std::vector Pca::scores(void) { return _scores; }; +std::vector Pca::eliminated_columns(void) { return _eliminated_columns; } +string Pca::method(void) { return _method; } +unsigned int Pca::kaiser(void) { return _kaiser; }; +unsigned int Pca::thresh95(void) { return _thresh95; }; +unsigned int Pca::ncols(void) { return _ncols; } +unsigned int Pca::nrows(void) { return _nrows; } +bool Pca::is_scale(void) { return _is_scale; } +bool Pca::is_center(void) { return _is_center; } + +int Pca::CalculateSVD() +{ + if ((1 == _ncols) || (1 == _nrows)) + return -1; + + float denom = static_cast((_nrows > 1)? _nrows - 1: 1); + + // Singular Value Decomposition is on _method = "svd"; JacobiSVD svd(_xXf, ComputeThinV); VectorXf eigen_singular_values = svd.singularValues(); + eigen_vectors = svd.matrixV(); + VectorXf tmp_vec = eigen_singular_values.array().square(); float tmp_sum = tmp_vec.sum(); tmp_vec /= tmp_sum; + // PC's standard deviation and // PC's proportion of variance _kaiser = 0; - unsigned int lim = (_nrows < _ncols)? _nrows : _ncols; + unsigned int lim = (_nrows < _ncols) ? _nrows : _ncols; eigen_values.resize(lim); for (unsigned int i = 0; i < lim; ++i) { - _sd.push_back(eigen_singular_values(i)/sqrt(denom)); - eigen_values[i] = _sd[i] * _sd[i]; - if (_sd[i] >= 1) { - _kaiser = i + 1; - } - _prop_of_var.push_back(tmp_vec(i)); + _sd.push_back(eigen_singular_values(i)/sqrt(denom)); + eigen_values[i] = _sd[i] * _sd[i]; + if (_sd[i] >= 1) { + _kaiser = i + 1; + } + _prop_of_var.push_back(tmp_vec(i)); } #ifdef DEBUG cout << "\n\nStandard deviations for PCs:\n"; @@ -119,33 +90,33 @@ int Pca::Calculate(vector &x, cout << "\n\nKaiser criterion: PC #" << _kaiser << endl; #endif tmp_vec.resize(0); + // PC's cumulative proportion _thresh95 = 1; _cum_prop.push_back(_prop_of_var[0]); for (unsigned int i = 1; i < _prop_of_var.size(); ++i) { - _cum_prop.push_back(_cum_prop[i-1]+_prop_of_var[i]); - if (_cum_prop[i] < 0.95) { - _thresh95 = i+1; - } + _cum_prop.push_back(_cum_prop[i-1]+_prop_of_var[i]); + if (_cum_prop[i] < 0.95) { + _thresh95 = i+1; + } } #ifdef DEBUG cout << "\nCumulative proportion:\n"; copy(_cum_prop.begin(), _cum_prop.end(),std::ostream_iterator(std::cout," ")); cout << "\n\nThresh95 criterion: PC #" << _thresh95 << endl; #endif + // Scores - eigen_vectors = svd.matrixV(); - MatrixXf eigen_scores = _xXf * eigen_vectors; - //MatrixXf eigen_scores = _xXf * svd.matrixV(); #ifdef DEBUG + cout << "\n\nEigen vectors:\n" << eigen_vectors; cout << "\n\nRotated values (scores):\n" << eigen_scores; #endif _scores.reserve(eigen_scores.rows()*eigen_scores.cols()); for (unsigned int i = 0; i < eigen_scores.rows(); ++i) { - for (unsigned int j = 0; j < eigen_scores.cols(); ++j) { - _scores.push_back(eigen_scores(i, j)); - } + for (unsigned int j = 0; j < eigen_scores.cols(); ++j) { + _scores.push_back(eigen_scores(i, j)); + } } eigen_scores.resize(0, 0); #ifdef DEBUG @@ -153,15 +124,24 @@ int Pca::Calculate(vector &x, copy(_scores.begin(), _scores.end(),std::ostream_iterator(std::cout," ")); cout << "\n"; #endif - } else { // COR OR COV MATRICES ARE HERE - /* Straight and simple: if the scales are similar use cov-PCA, if not, use corr-PCA; otherwise, you better have a defense for not. If in doubt, use an F-test for the equality of the variances (ANOVA). If it fails the F-test, use corr; otherwise, use cov. - */ - _method = "cor"; + return 0; +} + +int Pca::Calculate() +{ + if ((1 == _ncols) || (1 == _nrows)) + return -1; + // COR OR COV MATRICES ARE HERE + /* Straight and simple: if the scales are similar use cov-PCA, if not, use corr-PCA; otherwise, you better have a defense for not. If in doubt, use an F-test for the equality of the variances (ANOVA). If it fails the F-test, use corr; otherwise, use cov. + */ + _method = "eigen"; + // Calculate covariance matrix MatrixXf eigen_cov; // = MatrixXf::Zero(_ncols, _ncols); VectorXf sds; // (TODO) Should be weighted cov matrix, even if is_center == false eigen_cov = (1.0 /(_nrows/*-1*/)) * _xXf.transpose() * _xXf; + // diagnal are the variances sds = eigen_cov.diagonal().array().sqrt(); MatrixXf outer_sds = sds * sds.transpose(); #ifdef DEBUG @@ -173,16 +153,12 @@ int Pca::Calculate(vector &x, eigen_cov = eigen_cov.array() / outer_sds.array(); outer_sds.resize(0, 0); // ?If data matrix is scaled, covariance matrix is equal to correlation matrix - #ifdef DEBUG - cout << eigen_cov << endl; - #endif EigenSolver edc(eigen_cov); VectorXf eigen_eigenvalues = edc.eigenvalues().real(); + MatrixXf eigen_eigenvectors = edc.eigenvectors().real(); #ifdef DEBUG + cout << eigen_cov << endl; cout << endl << eigen_eigenvalues.transpose() << endl; - #endif - MatrixXf eigen_eigenvectors = edc.eigenvectors().real(); - #ifdef DEBUG cout << endl << eigen_eigenvectors << endl; #endif // The eigenvalues and eigenvectors are not sorted in any particular order. @@ -265,36 +241,7 @@ int Pca::Calculate(vector &x, copy(_scores.begin(), _scores.end(), std::ostream_iterator(std::cout," ")); cout << "\n"; #endif - } - - return 0; + return 0; } -std::vector Pca::sd(void) { return _sd; }; -std::vector Pca::prop_of_var(void) {return _prop_of_var; }; -std::vector Pca::cum_prop(void) { return _cum_prop; }; -std::vector Pca::scores(void) { return _scores; }; -std::vector Pca::eliminated_columns(void) { return _eliminated_columns; } -string Pca::method(void) { return _method; } -unsigned int Pca::kaiser(void) { return _kaiser; }; -unsigned int Pca::thresh95(void) { return _thresh95; }; -unsigned int Pca::ncols(void) { return _ncols; } -unsigned int Pca::nrows(void) { return _nrows; } -bool Pca::is_scale(void) { return _is_scale; } -bool Pca::is_center(void) { return _is_center; } -Pca::Pca(void) { - _nrows = 0; - _ncols = 0; - // Variables will be scaled by default - _is_center = true; - _is_scale = true; - // By default will be used singular value decomposition - _method = "svd"; - _is_corr = false; - _kaiser = 0; - _thresh95 = 1; -} -Pca::~Pca(void) { - _xXf.resize(0, 0); - _x.clear(); -} + diff --git a/Algorithms/pca.h b/Algorithms/pca.h index d0b13242a..413e090bb 100755 --- a/Algorithms/pca.h +++ b/Algorithms/pca.h @@ -9,124 +9,125 @@ class Pca { private: - std::vector _x; // Initial matrix as vector filled by rows. - Eigen::MatrixXf _xXf; // Initial matrix as Eigen MatrixXf structure - unsigned int _nrows, // Number of rows in matrix x. - _ncols; // Number of cols in matrix x. - bool _is_center, // Whether the variables should be shifted to be zero centered - _is_scale, // Whether the variables should be scaled to have unit variance - _is_corr; // PCA with correlation matrix, not covariance - std::string - _method; // svd, cor, cov - std::vector - _eliminated_columns; // Numbers of eliminated columns - std::vector _sd, // Standard deviation of each component - _prop_of_var, // Proportion of variance - _cum_prop, // Cumulative proportion - _scores; // Rotated values - unsigned int _kaiser, // Number of PC according Kaiser criterion - _thresh95; // Number of PC according 95% variance threshold + std::vector _x; // Initial matrix as vector filled by rows. + Eigen::MatrixXf _xXf; // Initial matrix as Eigen MatrixXf structure + unsigned int _nrows, // Number of rows in matrix x. + _ncols; // Number of cols in matrix x. + bool _is_center, // Whether the variables should be shifted to be zero centered + _is_scale, // Whether the variables should be scaled to have unit variance + _is_corr; // PCA with correlation matrix, not covariance + std::string + _method; // svd, cor, cov + std::vector + _eliminated_columns; // Numbers of eliminated columns + std::vector _sd, // Standard deviation of each component + _prop_of_var, // Proportion of variance + _cum_prop, // Cumulative proportion + _scores; // Rotated values + unsigned int _kaiser, // Number of PC according Kaiser criterion + _thresh95; // Number of PC according 95% variance threshold public: - //! Initializing values and performing PCA - /*! - The main method for performin Principal Component Analysis - \param x Initial data matrix - \param nrows Number of matrix rows - \param ncols Number of matrix cols - \param is_corr Correlation matrix will be used instead of covariance matrix - \param is_center Whether the variables should be shifted to be zero centered - \param is_scale Whether the variables should be scaled to have unit variance - \result - 0 if everything is Ok - -1 if there were some errors - */ - int Calculate(std::vector& x, const unsigned int& nrows, const unsigned int& ncols, - const bool is_corr = true, const bool is_center = true, const bool is_scale = true); - //! Return number of rows in initial matrix - /*! - \result Number of rows in initial matrix - */ - unsigned int nrows(void); - //! Return number of cols in initial matrix - /*! - \result Number of cols in initial matrix - */ - unsigned int ncols(void); - //! If variables are centered - /*! - \result - true - variables are centered - false - otherwise - */ - bool is_center(void); - //! If variables are scaled - /*! - \result - true - variables are scaled - false - otherwise - */ - bool is_scale(void); - //! Method for calculation of principal components - /*! - There are different methods used. The most used is SVD. - But in some cases it may be correlation or covariance matrices. - If - \result - "svd" - PCA with singular value decomposition - "cor" - PCA with correlation matrix - "cov" - PCA with covariance matrix - */ - std::string method(void); - //! Returns numbers of eliminated columns - /*! - If standard deviation of a column is equal to 0, the column shoud be rejected, - or PCA will fail. - \result Numbers of eliminated columns, empty vector otherwise - */ - std::vector eliminated_columns(void); - //! Standard deviation of each principal component - /*! - \result Vector of standard deviation for each principal component: - 1st element is sd for 1st PC, 2nd - for 2nd PC and so on. - */ - std::vector sd(void); - //! Proportion of variance - /*! - \result Vector of variances for each component - */ - std::vector prop_of_var(void); - //! Cumulative proportion - /*! - \result Vector of cumulative proportions for each components - */ - std::vector cum_prop(void); - //! Principal component by the Kaiser criterion - /*! - Number of the last component with eigenvalue greater than 1. - \result Number of the first components we should retain defined by the Kaiser criterion - */ - unsigned int kaiser(void); - //! 95% threshold - /*! - Retain only PC which cumulative proportion is less than 0.95 - \result Number of PCs should be retain with the 95% threshold criterion - */ - unsigned int thresh95(void); - //! Rotated values (scores) - /*! - Return calculated scores (coordinates in a new space) as vector. Matrix filled by rows. - \result Vector of scores - */ - std::vector scores(void); + //! Class constructor + Pca(double** x, const unsigned int &nrows, const unsigned int &ncols); + //! Class destructor + ~Pca(void); - Eigen::MatrixXf eigen_vectors; - Eigen::VectorXf eigen_values; + //! Initializing values and performing PCA + /*! + The main method for performin Principal Component Analysis + \param x Initial data matrix + \param nrows Number of matrix rows + \param ncols Number of matrix cols + \param is_corr Correlation matrix will be used instead of covariance matrix + \param is_center Whether the variables should be shifted to be zero centered + \param is_scale Whether the variables should be scaled to have unit variance + \result + 0 if everything is Ok + -1 if there were some errors + */ + int Calculate(); + int CalculateSVD(); - //! Class constructor - Pca(void); - //! Class destructor - ~Pca(void); + //! Return number of rows in initial matrix + /*! + \result Number of rows in initial matrix + */ + unsigned int nrows(void); + //! Return number of cols in initial matrix + /*! + \result Number of cols in initial matrix + */ + unsigned int ncols(void); + //! If variables are centered + /*! + \result + true - variables are centered + false - otherwise + */ + bool is_center(void); + //! If variables are scaled + /*! + \result + true - variables are scaled + false - otherwise + */ + bool is_scale(void); + //! Method for calculation of principal components + /*! + There are different methods used. The most used is SVD. + But in some cases it may be correlation or covariance matrices. + If + \result + "svd" - PCA with singular value decomposition + "cor" - PCA with correlation matrix + "cov" - PCA with covariance matrix + */ + std::string method(void); + //! Returns numbers of eliminated columns + /*! + If standard deviation of a column is equal to 0, the column shoud be rejected, + or PCA will fail. + \result Numbers of eliminated columns, empty vector otherwise + */ + std::vector eliminated_columns(void); + //! Standard deviation of each principal component + /*! + \result Vector of standard deviation for each principal component: + 1st element is sd for 1st PC, 2nd - for 2nd PC and so on. + */ + std::vector sd(void); + //! Proportion of variance + /*! + \result Vector of variances for each component + */ + std::vector prop_of_var(void); + //! Cumulative proportion + /*! + \result Vector of cumulative proportions for each components + */ + std::vector cum_prop(void); + //! Principal component by the Kaiser criterion + /*! + Number of the last component with eigenvalue greater than 1. + \result Number of the first components we should retain defined by the Kaiser criterion + */ + unsigned int kaiser(void); + //! 95% threshold + /*! + Retain only PC which cumulative proportion is less than 0.95 + \result Number of PCs should be retain with the 95% threshold criterion + */ + unsigned int thresh95(void); + //! Rotated values (scores) + /*! + Return calculated scores (coordinates in a new space) as vector. Matrix filled by rows. + \result Vector of scores + */ + std::vector scores(void); + + Eigen::MatrixXf eigen_vectors; + Eigen::VectorXf eigen_values; }; #endif diff --git a/Algorithms/redcap.cpp b/Algorithms/redcap.cpp new file mode 100644 index 000000000..2c7d12e86 --- /dev/null +++ b/Algorithms/redcap.cpp @@ -0,0 +1,1127 @@ +/** + * GeoDa TM, Copyright (C) 2011-2015 by Luc Anselin - all rights reserved + * + * This file is part of GeoDa. + * + * GeoDa is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * GeoDa is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * Created 5/30/2017 lixun910@gmail.com + */ + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "../ShapeOperations/GalWeight.h" +#include "../logger.h" +#include "../GenUtils.h" +#include "cluster.h" +#include "redcap.h" + +using namespace std; +using namespace boost; +using namespace SpanningTreeClustering; + +bool EdgeLess(Edge* a, Edge* b) +{ + if (a->length < b->length) { + return true; + } else if (a->length > b->length ) { + return false; + } else if (a->orig->id < b->orig->id) { + return true; + } else if (a->orig->id > b->orig->id) { + return false; + } else if (a->dest->id < b->dest->id) { + return true; + } else if (a->dest->id > b->dest->id) { + return false; + } + return true; +} + +///////////////////////////////////////////////////////////////////////// +// +// SSDUtils +// +///////////////////////////////////////////////////////////////////////// +void SSDUtils::MeasureSplit(double ssd, vector &ids, int split_position, Measure& result) +{ + int start1 = 0; + int end1 = split_position; + int start2 = split_position; + int end2 = ids.size(); + + double ssd1 = ComputeSSD(ids, start1, end1); + double ssd2 = ComputeSSD(ids, start2, end2); + + + result.measure_reduction = ssd - ssd1 - ssd2; + result.ssd = ssd; + result.ssd_part1 = ssd1; + result.ssd_part2 = ssd2; +} + +double SSDUtils::ComputeSSD(vector &visited_ids, int start, int end) +{ + int size = end - start; + double sum_squared = 0.0; + double val; + for (int i = 0; i < col; ++i) { + double sqsum = 0.0; + double sum = 0.0; + for (int j = start; j < end; ++j) { + val = raw_data[visited_ids[j]][i]; + sum += val; + sqsum += val * val; + } + double mean = sum / size; + sum_squared += sqsum - size * mean * mean; + } + return sum_squared / col; +} + +///////////////////////////////////////////////////////////////////////// +// +// Node +// +///////////////////////////////////////////////////////////////////////// +Node::Node(int _id) +{ + id = _id; +} + +DisjoinSet::DisjoinSet() +{ + +} + +DisjoinSet::DisjoinSet(int id) +{ + MakeSet(id); +} + +Node* DisjoinSet::FindSet(Node* node) +{ + Node* parent = node->parent; + if (parent == node) { + return parent; + } + node->parent = FindSet(node->parent); + return node->parent; +} + +Node* DisjoinSet::MakeSet(int id) +{ + Node* node = new Node(id); + node->parent = node; + node->rank = 0; + map[id] = node; + + return node; +} + +void DisjoinSet::Union(Node* n1, Node* n2) +{ + Node* parent1 = FindSet(n1); + Node* parent2 = FindSet(n2); + + if (parent1 == parent2) { + return; + } + + if (parent1->rank >= parent2->rank) { + parent1->rank = (parent1->rank == parent2->rank) ? parent1->rank +1 : parent1->rank; + parent2->parent = parent1; + } else { + parent1->parent = parent2; + } +} + +///////////////////////////////////////////////////////////////////////// +// +// Edge +// +///////////////////////////////////////////////////////////////////////// +Edge::Edge(Node* a, Node* b, double _length) +{ + orig = a; + dest = b; + length = _length; +} + + +///////////////////////////////////////////////////////////////////////// +// +// Tree +// +///////////////////////////////////////////////////////////////////////// +Tree::Tree(vector _ordered_ids, vector _edges, AbstractClusterFactory* _cluster) +: ordered_ids(_ordered_ids), edges(_edges), cluster(_cluster) +{ + ssd_reduce = 0; + ssd_utils = cluster->ssd_utils; + controls = cluster->controls; + control_thres = cluster->control_thres; + + int size = ordered_ids.size(); + int edge_size = edges.size(); + this->ssd = 0; + this->ssd_reduce = 0; + + if (ordered_ids.size() > 1) { + this->ssd = ssd_utils->ComputeSSD(ordered_ids, 0, size); + max_id = -1; + for (int i=0; i max_id) { + max_id = ordered_ids[i]; + } + } + + // use edges and ordered_ids to create nbr_dict and od_array + boost::unordered_map > nbr_dict; + od_array.resize(edge_size); + + int o_id, d_id; + for (int i=0; iorig->id; + d_id = edges[i]->dest->id; + + od_array[i].first = o_id; + od_array[i].second = d_id; + + nbr_dict[o_id].push_back(d_id); + nbr_dict[d_id].push_back(o_id); + } + + if (size < 1000) { + Partition(0, od_array.size()-1, ordered_ids, od_array, nbr_dict); + } else { + run_threads(ordered_ids, od_array, nbr_dict); + } + if (!split_cands.empty()) { + SplitSolution& ss = split_cands[0]; + this->split_ids = ss.split_ids; + this->split_pos = ss.split_pos; + this->ssd = ss.ssd; + this->ssd_reduce = ss.ssd_reduce; + + for (int j=1; j this->ssd_reduce) { + this->split_ids = tmp_ss.split_ids; + this->split_pos = tmp_ss.split_pos; + this->ssd = tmp_ss.ssd; + this->ssd_reduce = tmp_ss.ssd_reduce; + } + } + } + } +} + +Tree::~Tree() +{ +} + +void Tree::run_threads(vector& ids, + vector >& od_array, + boost::unordered_map >& nbr_dict) +{ + int n_jobs = od_array.size(); + + int nCPUs = boost::thread::hardware_concurrency();; + int quotient = n_jobs / nCPUs; + int remainder = n_jobs % nCPUs; + int tot_threads = (quotient > 0) ? nCPUs : remainder; + + boost::thread_group threadPool; + for (int i=0; i& ids, + vector >& od_array, + boost::unordered_map >& nbr_dict) +{ + int size = nbr_dict.size(); + int id, orig_id, dest_id; + int i, e_idx, k = 1, cnt=0; + + int best_edge = -1; + int evaluated = 0; + int best_pos = -1; + double tmp_ssd_reduce = 0, tmp_ssd=0; + + vector visited_ids(size), best_ids(size); + + // cut edge one by one + for ( i=start; i<=end; i++) { + orig_id = od_array[i].first; + dest_id = od_array[i].second; + + int idx = 0; + vector cand_ids(max_id+1, -1); + Split(orig_id, dest_id, nbr_dict, cand_ids); + + for (int j=0; jMeasureSplit(ssd, visited_ids, tmp_split_pos, result); + if (result.measure_reduction > tmp_ssd_reduce) { + tmp_ssd_reduce = result.measure_reduction; + tmp_ssd = result.ssd; + best_pos = tmp_split_pos; + best_ids = visited_ids; + } + } + } + } + + if (split_pos != -1) { + SplitSolution ss; + ss.split_pos = best_pos; + ss.split_ids = best_ids; + ss.ssd = tmp_ssd; + ss.ssd_reduce = tmp_ssd_reduce; + mutex.lock(); + split_cands.push_back(ss); + mutex.unlock(); + } +} + +void Tree::Split(int orig, int dest, boost::unordered_map >& nbr_dict, vector& cand_ids) +{ + stack visited_ids; + int cur_id, i, nbr_size, nbr; + + visited_ids.push(orig); + while (!visited_ids.empty()) { + cur_id = visited_ids.top(); + visited_ids.pop(); + cand_ids[cur_id] = 1; + vector& nbrs = nbr_dict[cur_id]; + nbr_size = nbrs.size(); + for (i=0; i& cand_ids, vector& ids, int flag) +{ + if (controls == NULL) { + return true; + } + + double val = 0; + for (int j=0; j control_thres; +} + +pair Tree::GetSubTrees() +{ + if (split_ids.empty()) { + return this->subtrees; + } + int size = this->split_ids.size(); + vector part1_ids(this->split_pos); + vector part2_ids(size -this->split_pos); + + int max_id = -1; + for (int i=0; i max_id) { + max_id = split_ids[i]; + } + } + + vector part1_edges(part1_ids.size()-1); + vector part2_edges(part2_ids.size()-1); + + vector part_index(max_id+1, 0); + for (int i=0; i< part1_ids.size(); i++) { + part_index[ part1_ids[i] ] = -1; + } + for (int i=0; i< part2_ids.size(); i++) { + part_index[ part2_ids[i] ] = 1; + } + int o_id, d_id; + int cnt1=0, cnt2=0, cnt=0; + for (int i=0; iedges.size(); i++) { + o_id = this->edges[i]->orig->id; + d_id = this->edges[i]->dest->id; + + if (part_index[o_id] == -1 && part_index[d_id] == -1) { + part1_edges[cnt1++] = this->edges[i]; + } else if (part_index[o_id] == 1 && part_index[d_id] == 1) { + part2_edges[cnt2++] = this->edges[i]; + } else { + cnt++; + } + } + + + Tree* left_tree = new Tree(part1_ids, part1_edges, cluster); + Tree* right_tree = new Tree(part2_ids, part2_edges, cluster); + subtrees.first = left_tree; + subtrees.second = right_tree; + return subtrees; +} + +//////////////////////////////////////////////////////////////////////////////// +// +// AbstractClusterFactory +// +//////////////////////////////////////////////////////////////////////////////// +AbstractClusterFactory::AbstractClusterFactory(int row, int col, double** _distances, double** _data, const vector& _undefs, GalElement * _w) +: rows(row), cols(col), dist_matrix(_distances), raw_data(_data), undefs(_undefs), w(_w) +{ +} + +AbstractClusterFactory::~AbstractClusterFactory() +{ + if (ssd_utils) { + delete ssd_utils; + } + + for (int i=0; idist_dict.resize(rows); + + Node* orig; + Node* dest; + double length; + boost::unordered_map, bool> access_dict; + + for (int i=0; i& nbrs = w[i].GetNbrs(); + for (int j=0; jid][dest->id]; + + if (access_dict.find(make_pair(i, nbr)) == access_dict.end()) { + edges.push_back(new Edge(orig, dest, length)); + access_dict[make_pair(i, nbr)] = true; + access_dict[make_pair(nbr, i)] = true; + } + this->dist_dict[i][nbr] = length; + } + } + + Clustering(); + +} + +vector >& AbstractClusterFactory::GetRegions() +{ + return cluster_ids; +} + +void AbstractClusterFactory::Partitioning(int k) +{ + wxStopWatch sw; + + vector not_split_trees; + Tree* current_tree = new Tree(ordered_ids, ordered_edges, this); + PriorityQueue sub_trees; + sub_trees.push(current_tree); + + + while (!sub_trees.empty() && sub_trees.size() < k) { + Tree* tmp_tree = sub_trees.top(); + //cout << tmp_tree->ssd_reduce << endl; + sub_trees.pop(); + + if (tmp_tree->ssd == 0) { + not_split_trees.push_back(tmp_tree); + k = k -1; + continue; + } + + pair children = tmp_tree->GetSubTrees(); + + Tree* left_tree = children.first; + Tree* right_tree = children.second; + + if (left_tree== NULL && right_tree ==NULL) { + not_split_trees.push_back(tmp_tree); + k = k -1; + continue; + } + + if (left_tree) { + sub_trees.push(left_tree); + } + if (right_tree) { + sub_trees.push(right_tree); + } + + //delete tmp_tree; + } + + cluster_ids.clear(); + + for (int i = 0; i< not_split_trees.size(); i++) { + sub_trees.push(not_split_trees[i]); + } + + PriorityQueue::iterator begin = sub_trees.begin(); + PriorityQueue::iterator end = sub_trees.end(); + boost::unordered_map::iterator node_it; + + for (PriorityQueue::iterator it = begin; it != end; ++it) { + Tree* tmp_tree = *it; + cluster_ids.push_back(tmp_tree->ordered_ids); + } + + for (int i = 0; i< not_split_trees.size(); i++) { + delete not_split_trees[i]; + } + wxString time = wxString::Format("The long running function took %ldms to execute", sw.Time()); +} + +//////////////////////////////////////////////////////////////////////////////// +// +// Skater +// +//////////////////////////////////////////////////////////////////////////////// +Skater::Skater(int rows, int cols, double** _distances, double** _data, const vector& _undefs, GalElement* w, double* _controls, double _control_thres) +: AbstractClusterFactory(rows, cols, _distances, _data, _undefs, w) +{ + controls = _controls; + control_thres = _control_thres; + init(); +} + +Skater::~Skater() +{ + +} + +void Skater::Clustering() +{ + Graph g(rows); + boost::unordered_map, bool> access_dict; + for (int i=0; i id_dict; + boost::unordered_map, Edge*> edge_dict; + for (int i=0; iorig->id, e->dest->id)] = e; + edge_dict[make_pair(e->dest->id, e->orig->id)] = e; + } + + //https://github.com/vinecopulib/vinecopulib/issues/22 + std::vector p(num_vertices(g)); + boost::prim_minimum_spanning_tree(g, p.data()); + + double sum_length=0; + + for (int source = 0; source < p.size(); ++source) { + int target = p[source]; + if (source != target) { + //boost::add_edge(source, p[source], mst); + //ordered_edges.push_back(new Edge(source, p[source])); + pair o_d(source, target); + pair d_o(target, source); + if (edge_dict.find(o_d) != edge_dict.end() && + edge_dict.find(d_o) != edge_dict.end()) + { + sum_length += edge_dict[ o_d]->length; + ordered_edges.push_back( edge_dict[ o_d]); + } + } + } + + //cout << "Skater mst sum length:" << sum_length << endl; + + for (int i=0; iorig->id; + int target = ordered_edges[i]->dest->id; + + if (id_dict.find(source)==id_dict.end()) { + ordered_ids.push_back(source); + id_dict[source] = true; + } + if (id_dict.find(target)==id_dict.end()) { + ordered_ids.push_back(target); + id_dict[target] = true; + } + } +} + + + +//////////////////////////////////////////////////////////////////////////////// +// +// 1 FirstOrderSLKRedCap +// +//////////////////////////////////////////////////////////////////////////////// +FirstOrderSLKRedCap::FirstOrderSLKRedCap(int rows, int cols, double** _distances, double** _data, const vector& _undefs, GalElement* w, double* _controls, double _control_thres) +: AbstractClusterFactory(rows, cols, _distances, _data, _undefs, w) +{ + controls = _controls; + control_thres = _control_thres; + init(); +} + +FirstOrderSLKRedCap::~FirstOrderSLKRedCap() +{ + +} + +void FirstOrderSLKRedCap::Clustering() +{ + std::sort(edges.begin(), edges.end(), EdgeLess); + + int num_nodes = nodes.size(); + + ordered_edges.resize(num_nodes-1); + int cnt = 0; + double sum_length = 0; + + for (int i=0; iorig; + Node* dest = edge->dest; + + Node* root1 = djset.FindSet(orig); + Node* root2 = djset.FindSet(dest); + + if (root1 == root2) { + continue; + } else { + ordered_edges[cnt] = edge; + djset.Union(orig, dest); + } + if ( ++cnt == num_nodes - 1) { + break; + } + } + //cout << "FO-SLK mst sum length:" << sum_length << endl; + + boost::unordered_map id_dict; + for (int i=0; iorig; + Node* dest = edge->dest; + + if (id_dict.find(orig->id)==id_dict.end()) { + ordered_ids.push_back(orig->id); + id_dict[orig->id] = true; + } + if (id_dict.find(dest->id)==id_dict.end()) { + ordered_ids.push_back(dest->id); + id_dict[dest->id] = true; + } + } +} + + +//////////////////////////////////////////////////////////////////////////////// +// +// 2 FirstOrderALKRedCap +// The First-Order-ALK method also starts with the spatially contiguous graph G*. However, after each merge, the distance between the new cluster and every other cluster is recalculated. Therefore, edges that connect the new cluster and every other cluster are updated with new length values. Edges in G* are then re-sorted and re-evaluated from the beginning. The procedure stops when all objects are in one cluster. The algorithm is shown in figure 3. The complexity is O(n2log n) due to the sorting after each merge. +// +//////////////////////////////////////////////////////////////////////////////// +FirstOrderALKRedCap::FirstOrderALKRedCap(int rows, int cols, double** _distances, double** _data, const vector& _undefs, GalElement * w, double* _controls, double _control_thres) +: AbstractClusterFactory(rows, cols, _distances, _data, _undefs, w) +{ + controls = _controls; + control_thres = _control_thres; + init(); +} + +FirstOrderALKRedCap::~FirstOrderALKRedCap() +{ + +} + + +void FirstOrderALKRedCap::Clustering() +{ + +} + +//////////////////////////////////////////////////////////////////////////////// +// +// 3 FirstOrderCLKRedCap +// +//////////////////////////////////////////////////////////////////////////////// +FirstOrderCLKRedCap::FirstOrderCLKRedCap(int rows, int cols, double** _distances, double** _data, const vector& _undefs, GalElement * w, double* _controls, double _control_thres) +: AbstractClusterFactory(rows, cols, _distances, _data, _undefs, w) +{ + controls = _controls; + control_thres = _control_thres; + init(); +} + +FirstOrderCLKRedCap::~FirstOrderCLKRedCap() +{ + +} + +void FirstOrderCLKRedCap::Clustering() +{ + +} + +//////////////////////////////////////////////////////////////////////////////// +// +// 4 FullOrderSLKRedCap +// +//////////////////////////////////////////////////////////////////////////////// +FullOrderSLKRedCap::FullOrderSLKRedCap(int rows, int cols, double** _distances, double** _data, const vector& _undefs, GalElement * w, double* _controls, double _control_thres) +: FullOrderALKRedCap(rows, cols, _distances, _data, _undefs, w, _controls, _control_thres, false) +{ + init(); +} + +FullOrderSLKRedCap::~FullOrderSLKRedCap() +{ + +} + +double FullOrderSLKRedCap::UpdateClusterDist(int cur_id, int o_id, int d_id, bool conn_c_o, bool conn_c_d, vector& clst_ids, vector& clst_startpos, vector& clst_nodenum) +{ + double new_dist; + if (conn_c_o && conn_c_d) { + double d_c_o = dist_dict[cur_id][o_id]; + double d_c_d = dist_dict[cur_id][d_id]; + if ((new_dist = d_c_o) > d_c_d) { + new_dist = d_c_d; + } + + } else if (conn_c_o || conn_c_d) { + if (conn_c_d) { + int tmp_id = o_id; + o_id = d_id; + d_id = tmp_id; + } + new_dist = dist_dict[cur_id][o_id]; + int c_endpos = clst_startpos[cur_id] + clst_nodenum[cur_id]; + int d_endpos = clst_startpos[d_id] + clst_nodenum[d_id]; + for (int i=clst_startpos[cur_id]; i& _undefs, GalElement * w, double* _controls, double _control_thres, bool init_flag) +: AbstractClusterFactory(rows, cols, _distances, _data, _undefs, w) +{ + controls = _controls; + control_thres = _control_thres; + if (init_flag) { + init(); + } +} + +FullOrderALKRedCap::~FullOrderALKRedCap() +{ + +} + +void FullOrderALKRedCap::Clustering() +{ + int num_nodes = nodes.size(); + vector ordered_nodes(num_nodes); + + for (int i=0; i< this->edges.size(); i++) { + Edge* edge = this->edges[i]; + Node* orig = edge->orig; + Node* dest = edge->dest; + ordered_nodes[ orig->id ] = orig; + ordered_nodes[ dest->id ] = dest; + } + + std::sort(edges.begin(), edges.end(), EdgeLess); + int num_edges = edges.size(); + vector edges_copy(num_edges); + for (int i=0; iordered_edges.resize(num_nodes-1); + + vector ids(num_nodes); + // number of nodes in a cluster + // the start position of a cluster + // the cluster id of each nodes + vector cluster_nodenum(num_nodes); + vector cluster_ids(num_nodes); + vector cluster_startpos(num_nodes); + for (int i=0; i access_flag(num_nodes, false); + vector counts(num_nodes); + vector new_edges; + + Edge* cur_edge = edges_copy[0]; + for (int k=0; korig; + Node* dest = cur_edge->dest; + int orig_id = ids[orig->id]; + int dest_id = ids[dest->id]; + + Node* root1 = djset.FindSet(orig); + Node* root2 = djset.FindSet(dest); + + if (root1 != root2) { + // find the shortest e in edges + for (int i=0; iedges.size(); i++) { + ++cnt; + Edge* tmp_edge = this->edges[i]; + int tmp_o_id = ids[tmp_edge->orig->id]; + int tmp_d_id = ids[tmp_edge->dest->id]; + if ((tmp_o_id==orig_id && tmp_d_id == dest_id) || + (tmp_d_id==orig_id && tmp_o_id == dest_id)) + { + // add edge + this->ordered_edges[index++] = tmp_edge; + break; + } + } + // add e to cluster + djset.Union(orig, dest); + + if (index == num_nodes -1) { + break; + } + + // remove edges(c,l) and edges(c, m) from copy + int i=0; + while (i < num_edges) { + ++cnt; + int tmp_o_id = ids[edges_copy[i]->orig->id]; + int tmp_d_id = ids[edges_copy[i]->dest->id]; + if (tmp_o_id==orig_id || tmp_o_id==dest_id || + tmp_d_id==orig_id || tmp_d_id==dest_id) + { + edges_copy[i] = edges_copy[--num_edges]; + } else { + ++i; + } + } + + for (i=0; i id_dict; + + for (int i=0; iorig; + Node* dest = e->dest; + + if (id_dict.find(orig->id)==id_dict.end()) { + ordered_ids.push_back(orig->id); + id_dict[orig->id] = true; + } + if (id_dict.find(dest->id)==id_dict.end()) { + ordered_ids.push_back(dest->id); + id_dict[dest->id] = true; + } + } + + for (int i=0; i& clst_ids, vector& clst_startpos, vector& clst_nodenum) +{ + double new_dist; + if (conn_c_o && conn_c_d) { + double d_c_o = dist_dict[cur_id][o_id]; + double d_c_d = dist_dict[cur_id][d_id]; + + // (avg_d(c,o) * numEdges(c,o) + avg_d(c,d)*numEdges(c,d)) / + // (numEdges(c, o) + numEdges(c, d)) + new_dist = (d_c_o * clst_nodenum[o_id] * clst_nodenum[cur_id] + d_c_d * clst_nodenum[d_id] * clst_nodenum[cur_id]) / ((clst_nodenum[o_id] + clst_nodenum[d_id]) * clst_nodenum[cur_id]); + + + } else if (conn_c_o || conn_c_d) { + if (conn_c_d) { + int tmp_id = o_id; + o_id = d_id; + d_id = tmp_id; + } + double d_c_o = dist_dict[cur_id][o_id]; + double sumval_c_d = 0; + int c_endpos = clst_startpos[cur_id] + clst_nodenum[cur_id]; + int d_endpos = clst_startpos[d_id] + clst_nodenum[d_id]; + + for (int i=clst_startpos[cur_id]; i& _edges, int start, int end) +{ + double len = DBL_MAX; + Edge* short_e = NULL; + for (int i=start; ilength < len) { + len = _edges[i]->length; + short_e = _edges[i]; + } + } + return short_e; +} +//////////////////////////////////////////////////////////////////////////////// +// +// 6 FullOrderCLKRedCap +// +//////////////////////////////////////////////////////////////////////////////// +FullOrderCLKRedCap::FullOrderCLKRedCap(int rows, int cols, double** _distances, double** _data, const vector& _undefs, GalElement * w, double* _controls, double _control_thres) +: FullOrderALKRedCap(rows, cols, _distances, _data, _undefs, w, _controls, _control_thres, false) +{ + init(); +} + +FullOrderCLKRedCap::~FullOrderCLKRedCap() +{ + +} + +double FullOrderCLKRedCap::UpdateClusterDist(int cur_id, int o_id, int d_id, bool conn_c_o, bool conn_c_d, vector& clst_ids, vector& clst_startpos, vector& clst_nodenum) +{ + double new_dist; + if (conn_c_o && conn_c_d) { + double d_c_o = dist_dict[cur_id][o_id]; + double d_c_d = dist_dict[cur_id][d_id]; + if ((new_dist = d_c_o) < d_c_d) { + new_dist = d_c_d; + } + + } else if (conn_c_o || conn_c_d) { + if (conn_c_d) { + int tmp_id = o_id; + o_id = d_id; + d_id = tmp_id; + } + new_dist = dist_dict[cur_id][o_id]; + int c_endpos = clst_startpos[cur_id] + clst_nodenum[cur_id]; + int d_endpos = clst_startpos[d_id] + clst_nodenum[d_id]; + for (int i=clst_startpos[cur_id]; i new_dist) { + new_dist = dist_dict[clst_ids[i]] [clst_ids[j]]; + } + } + } + } + return new_dist; +} + +//////////////////////////////////////////////////////////////////////////////// +FullOrderWardRedCap::FullOrderWardRedCap(int rows, int cols, double** _distances, double** _data, const vector& _undefs, GalElement * w, double* _controls, double _control_thres) +: AbstractClusterFactory(rows, cols, _distances, _data, _undefs, w) +{ + controls = _controls; + control_thres = _control_thres; + init(); +} + +FullOrderWardRedCap::~FullOrderWardRedCap() +{ + +} + +void FullOrderWardRedCap::Clustering() +{ + int num_nodes = nodes.size(); + vector ordered_nodes(num_nodes); + + for (int i=0; i< this->edges.size(); i++) { + Edge* edge = this->edges[i]; + Node* orig = edge->orig; + Node* dest = edge->dest; + ordered_nodes[ orig->id ] = orig; + ordered_nodes[ dest->id ] = dest; + } + + std::sort(edges.begin(), edges.end(), EdgeLess); + int num_edges = edges.size(); + vector edges_copy(num_edges); + for (int i=0; iordered_edges.resize(num_nodes-1); +} diff --git a/Algorithms/redcap.h b/Algorithms/redcap.h new file mode 100644 index 000000000..c2a7146a1 --- /dev/null +++ b/Algorithms/redcap.h @@ -0,0 +1,456 @@ +/** + * GeoDa TM, Copyright (C) 2011-2015 by Luc Anselin - all rights reserved + * + * This file is part of GeoDa. + * + * GeoDa is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * GeoDa is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * Created: 5/30/2017 lixun910@gmail.com + */ + +#ifndef __GEODA_CENTER_REDCAP_H__ +#define __GEODA_CENTER_REDCAP_H__ + +#include +#include +#include +#include +#include +#include +#include + +#include "../ShapeOperations/GalWeight.h" + + +using namespace std; +using namespace boost; + +namespace SpanningTreeClustering { + + class Node; + class Edge; + class Tree; + class AbstractClusterFactory; + + ///////////////////////////////////////////////////////////////////////// + // + // SSDUtils + // + ///////////////////////////////////////////////////////////////////////// + struct Measure + { + double ssd; + double ssd_part1; + double ssd_part2; + double measure_reduction; + }; + + class SSDUtils + { + double** raw_data; + int row; + int col; + + public: + SSDUtils(double** data, int _row, int _col) { + raw_data = data; + row = _row; + col = _col; + } + ~SSDUtils() {} + + double ComputeSSD(vector& visited_ids, int start, int end); + void MeasureSplit(double ssd, vector& visited_ids, int split_position, Measure& result); + + }; + + ///////////////////////////////////////////////////////////////////////// + // + // Node + // + ///////////////////////////////////////////////////////////////////////// + + struct NeighborInfo + { + Node* p; + Node* n1; + Node* n2; + Edge* e1; + Edge* e2; + + void SetDefault(Node* parent) { + p = parent; + n1 = NULL; + n2 = NULL; + e1 = NULL; + e2 = NULL; + } + + void AddNeighbor(Node* nbr, Edge* e) { + if (n1 == NULL) { + n1 = nbr; + e1 = e; + } else if (n2 == NULL) { + n2 = nbr; + e2 = e; + } else { + cout << "AddNeighbor() > 2" << endl; + } + } + }; + + class Node + { + public: + Node(int id); + ~Node() {} + + + int id; // mapping to record id + Node* parent; + int rank; + + //Cluster* container; + //NeighborInfo nbr_info; + }; + + class DisjoinSet + { + boost::unordered_map map; + public: + DisjoinSet(); + DisjoinSet(int id); + ~DisjoinSet() {}; + + Node* MakeSet(int id); + void Union(Node* n1, Node* n2); + Node* FindSet(Node* node); + }; + + ///////////////////////////////////////////////////////////////////////// + // + // Edge + // + ///////////////////////////////////////////////////////////////////////// + class Edge + { + public: + Edge(Node* a, Node* b, double length); + ~Edge() {} + + Node* orig; + Node* dest; + double length; // legnth of the edge |a.val - b.val| + }; + + ///////////////////////////////////////////////////////////////////////// + // + // Tree + // + ///////////////////////////////////////////////////////////////////////// + struct SplitSolution + { + int split_pos; + vector split_ids; + double ssd; + double ssd_reduce; + }; + + class Tree + { + public: + Tree(vector ordered_ids, + vector _edges, + AbstractClusterFactory* cluster); + + ~Tree(); + + void Partition(int start, int end, vector& ids, + vector >& od_array, + boost::unordered_map >& nbr_dict); + void Split(int orig, int dest, + boost::unordered_map >& nbr_dict, + vector& cand_ids); + bool checkControl(vector& cand_ids, vector& ids, int flag); + pair GetSubTrees(); + + double ssd_reduce; + double ssd; + + vector > od_array; + AbstractClusterFactory* cluster; + pair subtrees; + int max_id; + int split_pos; + vector split_ids; + vector edges; + vector ordered_ids; + SSDUtils* ssd_utils; + + double* controls; + double control_thres; + + // threads + boost::mutex mutex; + void run_threads(vector& ids, + vector >& od_array, + boost::unordered_map >& nbr_dict); + vector split_cands; + }; + + //////////////////////////////////////////////////////////////////////////////// + // + // AbstractRedcap + // + //////////////////////////////////////////////////////////////////////////////// + struct CompareTree + { + public: + bool operator() (const Tree* lhs, const Tree* rhs) const + { + return lhs->ssd_reduce < rhs->ssd_reduce; + } + }; + + typedef heap::priority_queue > PriorityQueue; + + class AbstractClusterFactory + { + public: + int rows; + int cols; + GalElement* w; + double** dist_matrix; + double** raw_data; + const vector& undefs; // undef = any one item is undef in all variables + double* controls; + double control_thres; + SSDUtils* ssd_utils; + + //Cluster* cluster; + DisjoinSet djset; + + vector nodes; + vector edges; + + vector ordered_ids; + vector ordered_edges; + + vector > dist_dict; + + vector > cluster_ids; + + AbstractClusterFactory(int row, int col, + double** distances, + double** data, + const vector& undefs, + GalElement * w); + virtual ~AbstractClusterFactory(); + + virtual void Clustering()=0; + + virtual double UpdateClusterDist(int cur_id, int orig_id, int dest_id, bool is_orig_nbr, bool is_dest_nbr, vector& clst_ids, vector& clst_startpos, vector& clst_nodenum) { return 0;} + + Edge* GetShortestEdge(vector& edges, int start, int end){ return NULL;} + + void init(); + void Partitioning(int k); + vector >& GetRegions(); + }; + + //////////////////////////////////////////////////////////////////////////////// + // + // 1 Skater + // + //////////////////////////////////////////////////////////////////////////////// + typedef adjacency_list < + vecS, + vecS, + undirectedS, + boost::no_property, //VertexProperties + property < edge_weight_t, double> //EdgeProperties + > Graph; + + class Skater : public AbstractClusterFactory + { + public: + Skater(int rows, int cols, + double** _distances, + double** data, + const vector& undefs, + GalElement * w, + double* controls, + double control_thres); + virtual ~Skater(); + virtual void Clustering(); + }; + + //////////////////////////////////////////////////////////////////////////////// + // + // 1 FirstOrderSLKRedCap + // + //////////////////////////////////////////////////////////////////////////////// + class FirstOrderSLKRedCap : public AbstractClusterFactory + { + public: + FirstOrderSLKRedCap(int rows, int cols, + double** _distances, + double** data, + const vector& undefs, + GalElement * w, + double* controls, + double control_thres); + virtual ~FirstOrderSLKRedCap(); + + virtual void Clustering(); + }; + + + //////////////////////////////////////////////////////////////////////////////// + // + // 2 FirstOrderALKRedCap + // + //////////////////////////////////////////////////////////////////////////////// + class FirstOrderALKRedCap : public AbstractClusterFactory + { + public: + FirstOrderALKRedCap(int rows, int cols, + double** _distances, + double** data, + const vector& undefs, + GalElement * w, + double* controls, + double control_thres); + + virtual ~FirstOrderALKRedCap(); + + virtual void Clustering(); + + }; + + //////////////////////////////////////////////////////////////////////////////// + // + // 3 FirstOrderCLKRedCap + // + //////////////////////////////////////////////////////////////////////////////// + class FirstOrderCLKRedCap : public AbstractClusterFactory + { + public: + FirstOrderCLKRedCap(int rows, int cols, + double** _distances, + double** data, + const vector& undefs, + GalElement * w, + double* controls, + double control_thres); + + virtual ~FirstOrderCLKRedCap(); + + virtual void Clustering(); + + }; + + //////////////////////////////////////////////////////////////////////////////// + // + // 5 FullOrderALKRedCap + // + //////////////////////////////////////////////////////////////////////////////// + class FullOrderALKRedCap : public AbstractClusterFactory + { + public: + FullOrderALKRedCap(int rows, int cols, + double** _distances, + double** data, + const vector& undefs, + GalElement * w, + double* controls, + double control_thres, + bool init=true); + + virtual ~FullOrderALKRedCap(); + + virtual void Clustering(); + + virtual double UpdateClusterDist(int cur_id, int orig_id, int dest_id, bool is_orig_nbr, bool is_dest_nbr, vector& clst_ids, vector& clst_startpos, vector& clst_nodenum); + + Edge* GetShortestEdge(vector& edges, int start, int end); + }; + + //////////////////////////////////////////////////////////////////////////////// + // + // 4 FullOrderSLKRedCap + // + //////////////////////////////////////////////////////////////////////////////// + class FullOrderSLKRedCap : public FullOrderALKRedCap + { + public: + FullOrderSLKRedCap(int rows, int cols, + double** _distances, + double** data, + const vector& undefs, + GalElement * w, + double* controls, + double control_thres); + virtual ~FullOrderSLKRedCap(); + + virtual double UpdateClusterDist(int cur_id, int orig_id, int dest_id, bool is_orig_nbr, bool is_dest_nbr, vector& clst_ids, vector& clst_startpos, vector& clst_nodenum); + + }; + + + //////////////////////////////////////////////////////////////////////////////// + // + // 6 FullOrderCLKRedCap + // + //////////////////////////////////////////////////////////////////////////////// + class FullOrderCLKRedCap : public FullOrderALKRedCap + { + public: + FullOrderCLKRedCap(int rows, int cols, + double** _distances, + double** data, + const vector& undefs, + GalElement * w, + double* controls, + double control_thres); + + virtual ~FullOrderCLKRedCap(); + + virtual double UpdateClusterDist(int cur_id, int orig_id, int dest_id, bool is_orig_nbr, bool is_dest_nbr, vector& clst_ids, vector& clst_startpos, vector& clst_nodenum); + + }; + + //////////////////////////////////////////////////////////////////////////////// + // + // 6 Ward + // + //////////////////////////////////////////////////////////////////////////////// + class FullOrderWardRedCap : public AbstractClusterFactory + { + public: + FullOrderWardRedCap(int rows, int cols, + double** _distances, + double** data, + const vector& undefs, + GalElement * w, + double* controls, + double control_thres); + + virtual ~FullOrderWardRedCap(); + + virtual void Clustering(); + }; +} + +#endif diff --git a/Algorithms/skater.cpp b/Algorithms/skater.cpp new file mode 100644 index 000000000..a7b0fcbb0 --- /dev/null +++ b/Algorithms/skater.cpp @@ -0,0 +1,356 @@ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +#include "../GenUtils.h" +#include "skater.h" + +Skater::Skater(int _num_obs, int _num_vars, int _num_clusters, double** _data, vector >& dist_matrix, bool _check_floor, double _floor, double* _floor_variable) +: num_obs(_num_obs), num_vars(_num_vars), num_clusters(_num_clusters),data(_data), check_floor(_check_floor), floor(_floor), floor_variable(_floor_variable) +{ + Graph g(num_obs); + for (int i=0; i= 0) { + boost::add_edge(i, j, dist_matrix[i][j], g); + } + } + } + get_MST(g); + + run(); + +} + +Skater::~Skater() +{ + +} + +void Skater::run_threads(vector tree, vector& scores, vector > >& cids, vector& candidates) +{ + int n_jobs = tree.size(); + + int nCPUs = boost::thread::hardware_concurrency();; + int quotient = n_jobs / nCPUs; + int remainder = n_jobs % nCPUs; + int tot_threads = (quotient > 0) ? nCPUs : remainder; + + boost::thread_group threadPool; + for (int i=0; i > Skater::GetRegions() +{ + vector > regions; + PriorityQueue::iterator begin = solution.begin(); + PriorityQueue::iterator end = solution.end(); + + set::iterator set_it; + for (PriorityQueue::iterator it = begin; it != end; ++it) { + const vector& c = (*it).second; + set ids; + for (int i=0; i< c.size(); i++) { + ids.insert(c[i].first); + ids.insert(c[i].second); + } + vector reg; + for (set_it=ids.begin(); set_it!=ids.end(); set_it++) { + reg.push_back(*set_it); + } + regions.push_back(reg); + } + return regions; +} + +void Skater::run() +{ + ClusterEl c(0, mst_edges); + + solution.push(c); + + while (solution.size() < num_clusters) { + const ClusterEl& cluster = solution.top(); + vector tree = cluster.second; + + double sswt = ssw(tree); + // check where to split + int tree_size = tree.size(); + vector scores(tree_size); + vector > > cids(tree_size); + vector candidates(tree_size); + + //prunecost(tree, 0, tree_size-1, scores, cids, candidates); + run_threads(tree, scores, cids, candidates); + + for (int i=0; i > best_cids = cids[0]; + ClusterPair best_pair = candidates[0]; + + for (int i=1; i best_score && !candidates[i].empty()) { + best_score = scores[i]; + best_cids = cids[i]; + best_pair = candidates[i]; + } + } + + if (best_pair.empty()) + break; + + solution.pop(); + + // subtree 1 + int t1_size = best_pair[0].size(); + vector scores1(t1_size); + vector > > cids1(t1_size); + vector cand1(t1_size); + run_threads(best_pair[0], scores1, cids1, cand1); + double best_score_1 = DBL_MAX; + for (int i=0; i& tmp_set = best_cids[0]; + int tmp_id = *tmp_set.begin(); + E tmp_e(tmp_id, tmp_id); + best_pair[0].push_back(tmp_e); + } + solution.push( ClusterEl(best_score_1, best_pair[0])); + + // subtree 2 + int t2_size = best_pair[1].size(); + vector scores2(t2_size); + vector > > cids2(t2_size); + vector cand2(t2_size); + run_threads(best_pair[1], scores2, cids2, cand2); + double best_score_2 = DBL_MAX; + for (int i=0; i& tmp_set = best_cids[1]; + if (!tmp_set.empty()) { + int tmp_id = *tmp_set.begin(); + E tmp_e(tmp_id, tmp_id); + best_pair[1].push_back(tmp_e); + } + } + solution.push( ClusterEl(best_score_2, best_pair[1])); + } +} + +void Skater::prunecost(vector tree, int start, int end, vector& scores, vector > >& cids, vector& candidates) +{ + //prune mst by removing one edge and get the best cut + + for (int i=start; i<=end; i++) { + // move i-th edge to top: used by prunemst() + E e_i = tree[i]; + tree.erase(tree.begin() + i); + tree.insert(tree.begin(), e_i); + + // prune tree to get two groups + set vex1, vex2; + vector part1, part2; + prunemst(tree, vex1, vex2, part1, part2); + + // compute objective function + double ssw1 = ssw(vex1); + double ssw2 = ssw(vex2); + scores[i] = ssw1 + ssw2; + + // check by bound + bool valid = true; + if (check_floor && valid) { + if (bound_check(vex1) == false || bound_check(vex2) == false) { + valid = false; + } + } + + if (valid) { + vector > pts; + pts.push_back(vex1); + pts.push_back(vex2); + cids[i] = pts; + + ClusterPair c; + c.push_back(part1); + c.push_back(part2); + candidates[i] = c; + } + // restore tree + tree.erase(tree.begin()); + tree.insert(tree.begin() + i, e_i); + } +} + +void Skater::get_MST(const Graph &in) +{ + //https://github.com/vinecopulib/vinecopulib/issues/22 + std::vector p(num_vertices(in)); + + prim_minimum_spanning_tree(in, p.data()); + + for (int source = 0; source < p.size(); ++source) + { + int target = p[source]; + if (source != target) { + //boost::add_edge(source, p[source], mst); + mst_edges.push_back(E(source, p[source])); + } + } +} + +double Skater::ssw(vector& cluster) +{ + set ids; + for (int i=0; i& ids) +{ + // This function computes the sum of dissimilarity between each + // observation and the mean (scalar of vector) of the observations. + // sum((x_i - x_min)^2) + + double n = ids.size(); + vector means(num_vars); + set::iterator it; + + for (int c=0; c 0 ? sum / n : 0; + means[c] = mean; + } + + double ssw_val = 0; + + for (it=ids.begin(); it!=ids.end(); it++) { + double sum = 0; + int i = *it; + for (int c=0; c& cluster) +{ + set::iterator it; + double sum=0; + for (it=cluster.begin(); it!=cluster.end(); it++) { + int i = *it; + sum += floor_variable[i]; + } + return sum >= floor; +} + +// This function deletes a first edge and makes two subsets of edges. Each +// subset is a Minimun Spanning Treee. +void Skater::prunemst(vector& edges, set& set1, set& set2, vector& part1, vector& part2) +{ + // first edge is going to be removed + int num_edges = edges.size(); + int i, j, n1=1, li=0, ls=1; + + vector no1(num_edges); + vector gr(num_edges); + + //no1[0] = e1[0]; + no1[0] = edges[0].first; + + for (i=0; i +#include +#include +#include +#include +#include +#include +#include +#include + + +using namespace std; +using namespace boost; + +typedef std::pair E; + +struct CompareCluster +{ +public: + bool operator() (const pair > & lhs, const pair > & rhs) const + { + return lhs.first < rhs.first; + } +}; + +typedef adjacency_list < + vecS, + vecS, + undirectedS, + boost::no_property, //VertexProperties + property < edge_weight_t, double> //EdgeProperties + > Graph; + +typedef std::vector > ClusterPair; +typedef std::pair > ClusterEl; +typedef heap::priority_queue > PriorityQueue; + +class Skater { +public: + Skater(int num_obs, int num_vars, int num_clusters, double** _data, + vector >& dist_matrix, + bool check_floor, double floor, double* floor_variable); + ~Skater(); + + vector > GetRegions(); + +protected: + int num_obs; + int num_clusters; + int num_vars; + double** data; + bool check_floor; + double floor; + double* floor_variable; + vector mst_edges; + + heap::priority_queue > solution; + + void get_MST(const Graph &in); + + void run(); + + void run_threads(vector tree, vector& scores, vector > >& cids, vector& candidates); + + void prunecost(vector tree, int start, int end, vector& scores, vector > >& cids, vector& candidates); + + void prunemst(vector& edges, set& vex1, set& vex2, vector& part1, vector& part2); + + double ssw(vector& cluster); + + double ssw(set& ids); + + bool bound_check(set& cluster); +}; + +#endif diff --git a/Algorithms/spectral.cpp b/Algorithms/spectral.cpp new file mode 100644 index 000000000..6ba268d30 --- /dev/null +++ b/Algorithms/spectral.cpp @@ -0,0 +1,322 @@ +// Modified by: lixun910@gmail.com July 20 2017 +// Originally from: Spectral clustering, by Tim Nugent 2014 + +#define NODEBUG +#include +#ifdef DEBUG +#include +#endif + +#include +#include +#include +#include +#include +#include + +#include "cluster.h" +#include "spectral.h" +#include "DataUtils.h" + +using namespace Eigen; +using namespace std; + + +void Spectral::set_data(double** input_data, int nrows, int ncols) +{ + X.resize(nrows, ncols); + for (unsigned int i = 0; i < nrows; ++i) { + for (unsigned int j = 0; j < ncols; ++j) { + X(i, j) = input_data[i][j]; + } + } +} + +double Spectral::kernel(const VectorXd& a, const VectorXd& b) +{ + //http://scikit-learn.org/stable/modules/generated/sklearn.cluster.SpectralClustering.html + // gamma : float, default=1.0 (Radial basis function kernel) + // Kernel coefficient for rbf, poly, sigmoid, laplacian and chi2 kernels. Ignored for + // affinity='nearest_neighbors + switch(kernel_type){ + case 1 : + return(pow(a.dot(b)+constant,order)); + default : + //return(exp(-gamma*((a-b).squaredNorm()))); + return exp(-((a-b).squaredNorm()/(2 * sigma * sigma)) ); + } + +} + +void Spectral::affinity_matrix() +{ + // Fill Laplacian matrix + K.resize(X.rows(),X.rows()); + for(unsigned int i = 0; i < X.rows(); i++){ + for(unsigned int j = i; j < X.rows(); j++){ + K(i,j) = K(j,i) = kernel(X.row(i),X.row(j)); + } + } + + // Normalise Laplacian + VectorXd d = K.rowwise().sum(); + MatrixXd _D = d.asDiagonal(); + MatrixXd U = _D - K; + + for(unsigned int i = 0; i < d.rows(); i++){ + d(i) = 1.0/sqrt(d(i)); + } + MatrixXd l = d.asDiagonal() * U * d.asDiagonal(); + K = l; +} + +void Spectral::generate_kernel_matrix() +{ + //If you have an affinity matrix, such as a distance matrix, for which 0 means identical elements, and high values means very dissimilar elements, it can be transformed in a similarity matrix that is well suited for the algorithm by applying the Gaussian (RBF, heat) kernel: + //np.exp(- X ** 2 / (2. * delta ** 2)) + //delta = X.maxCoeff() - X.minCoeff(); + + // Fill kernel matrix + K.resize(X.rows(),X.rows()); + for(unsigned int i = 0; i < X.rows(); i++){ + for(unsigned int j = i; j < X.rows(); j++){ + K(i,j) = K(j,i) = kernel(X.row(i),X.row(j)); + } + } + + // Normalise kernel matrix + VectorXd d = K.rowwise().sum(); + for(unsigned int i = 0; i < d.rows(); i++){ + d(i) = 1.0/sqrt(d(i)); + } + MatrixXd l = (K * d.asDiagonal()); + for(unsigned int i = 0; i < l.rows(); i++){ + for(unsigned int j = 0; j < l.cols(); j++){ + l(i,j) = l(i,j) * d(i); + } + } + K = l; +} + +struct CompareDist +{ + bool operator()(const pair& lhs, const pair& rhs) const { return lhs.second > rhs.second;} +}; + +void Spectral::generate_knn_matrix() +{ + typedef boost::heap::priority_queue, boost::heap::compare > PriorityQueue; + + // Fill euclidean dista matrix and filter using KNN + K.resize(X.rows(),X.rows()); + double squared_dist = 0; + for (unsigned int i = 0; i < X.rows(); i++){ + PriorityQueue top_K; + for(unsigned int j = i; j < X.rows(); j++){ + squared_dist = (X.row(i) - X.row(j)).norm(); + K(i,j) = K(j,i) = squared_dist; + if (i != j) top_K.push(std::make_pair(j,squared_dist)); + } + if (top_K.size() > knn) { + double min_dist = 0; + for (int j=0; j item = top_K.top(); + top_K.pop(); + min_dist = item.second; + } + for(unsigned int j = i; j < X.rows(); j++){ + if (K(j,i) > min_dist) { + K(i,j) = K(j,i) = 0; + } + } + for(unsigned int j = i; j < X.rows(); j++){ + if (K(j,i) != 0 ) { + K(i,j) = K(j,i) = 1; + } + } + } + } + + // Normalise kernel matrix + VectorXd d = K.rowwise().sum(); + for(unsigned int i = 0; i < d.rows(); i++){ + d(i) = 1.0/sqrt(d(i)); + } + MatrixXd l = (K * d.asDiagonal()); + for(unsigned int i = 0; i < l.rows(); i++){ + for(unsigned int j = 0; j < l.cols(); j++){ + l(i,j) = l(i,j) * d(i); + } + } + K = l; +} + +static bool inline eigen_greater(const pair& a, const pair& b) +{ + return a.first > b.first; +} + +void Spectral::fast_eigendecomposition() +{ + // get top N = centers eigen values/vectors + int n = K.rows(); + vector > matrix(n); + for (int i=0; i< n; i++) { + matrix[i].resize(n); + for (int j=0; j > evecs(centers); + for (int i=0; i lambda(centers); + DataUtils::eigen(matrix, evecs, lambda, power_iter); + for (int i = 0; i < evecs.size(); i++) { + for (int j = 0; j < evecs[0].size(); j++) { + evecs[i][j] *= sqrt(lambda[i]); + } + } + + // normalise eigenvectors + for (int i = 0; i < evecs.size(); i++) { + double norm = 0; + for (int j = 0; j < evecs[0].size(); j++) { + norm += evecs[i][j] * evecs[i][j]; + } + norm = sqrt(norm); + for (int j = 0; j < evecs[0].size(); j++) { + evecs[i][j] /= norm; + } + } + + eigenvectors.resize(n, centers); + eigenvalues.resize(centers); + + for (int c=0; c edecomp(K, true); + + EigenSolver edecomp(K); + eigenvalues = edecomp.eigenvalues().real(); + eigenvectors = edecomp.eigenvectors().real(); + for(unsigned int i = 0; i < eigenvalues.rows(); i++){ + cout << "Eigenvalue: " << eigenvalues(i) << endl; + } + cumulative.resize(eigenvalues.rows()); + vector > eigen_pairs; + double c = 0.0; + for(unsigned int i = 0; i < eigenvectors.cols(); i++){ + if(normalise){ + double norm = eigenvectors.col(i).norm(); + eigenvectors.col(i) /= norm; + } + eigen_pairs.push_back(make_pair(eigenvalues(i),eigenvectors.col(i))); + } + // http://stackoverflow.com/questions/5122804/sorting-with-lambda + sort(eigen_pairs.begin(),eigen_pairs.end(), eigen_greater); + + if(centers > eigen_pairs.size()) centers = eigen_pairs.size(); + + for(unsigned int i = 0; i < eigen_pairs.size(); i++){ + eigenvalues(i) = eigen_pairs[i].first; + c += eigenvalues(i); + cumulative(i) = c; + eigenvectors.col(i) = eigen_pairs[i].second; + } + cout << "Sorted eigenvalues:" << endl; + for(unsigned int i = 0; i < eigenvalues.rows(); i++){ + if(i<2){ + cout << "PC " << i+1 << ": Eigenvalue: " << eigenvalues(i); + printf("\t(%3.3f of variance, cumulative = %3.3f)\n",eigenvalues(i)/eigenvalues.sum(),cumulative(i)/eigenvalues.sum()); + cout << eigenvectors.col(i) << endl; + } + } + cout << endl; + MatrixXd tmp = eigenvectors; + + // Select top K eigenvectors where K = centers + eigenvectors = tmp.block(0,0,tmp.rows(),centers); + +} + + +void Spectral::cluster(int affinity_type) +{ + if (affinity_type == 0) { + // kernel + //affinity_matrix(); + generate_kernel_matrix(); + + } else { + // KNN + generate_knn_matrix(); + } + + if (power_iter>0) fast_eigendecomposition(); + else eigendecomposition(); + kmeans(); +} + +void Spectral::kmeans() +{ + int rows = eigenvectors.rows(); + int columns = eigenvectors.cols(); + + int transpose = 0; // row wise + int* clusterid = new int[rows]; + double* weight = new double[columns]; + for (int j=0; j 0) { + s2 = s1 + rows; + for (int i = 0; i < rows; i++) uniform(s1, s2); + } + kcluster(centers, rows, columns, input_data, mask, weight, transpose, npass, n_maxiter, method, dist, clusterid, &error, &ifound, NULL, 0, s1, s2); + + //vector clusters_undef; + + // clean memory + for (int i=0; i +#ifdef Success +#undef Success +#endif + +#include +#include +#include +#include +#include + +using namespace Eigen; +using namespace std; + +class Spectral{ + +public: + Spectral() : centers(2), kernel_type(1), normalise(1), max_iters(1000), sigma(0.001), constant(1.0), order(2.0), method('a'), dist('e'), npass(10), n_maxiter(300) {} + explicit Spectral(MatrixXd& d) : centers(2), kernel_type(1), normalise(1), max_iters(1000), sigma(0.001), constant(1.0), order(2.0), method('a'), dist('e'), npass(10), n_maxiter(300) {X = d;} + + + void set_data(double** input_data, int nrows, int ncols); + void set_centers(const unsigned int i){centers = i;}; + + void set_knn(const unsigned int i){knn = i;}; + void set_kernel(const unsigned int i){kernel_type = i;}; + void set_sigma(const double i){sigma = i;}; + + void set_normalise(const unsigned int i){normalise = i;}; + void set_constant(const double i){constant = i;}; + void set_order(const double i){order = i;}; + void set_max_iters(const unsigned int i){max_iters = i;}; + void set_power_iters(const unsigned int i){power_iter = i;}; + + void cluster(int affinity_type=0); + const std::vector &get_assignments() const {return assignments;}; + +private: + void affinity_matrix(); + void generate_kernel_matrix(); + double kernel(const VectorXd& a, const VectorXd& b); + + void generate_knn_matrix(); + + void eigendecomposition(); + void fast_eigendecomposition(); + void kmeans(); + + MatrixXd X, K, eigenvectors; + VectorXd eigenvalues, cumulative; + unsigned int centers, kernel_type, normalise, max_iters, knn; + double sigma, constant, order; + // parameters for KMeans + char method, dist; + int npass, n_maxiter; // max iteration of EM + int power_iter; + std::vector assignments; +}; + +#endif diff --git a/Algorithms/texttable.h b/Algorithms/texttable.h new file mode 100644 index 000000000..9461fb773 --- /dev/null +++ b/Algorithms/texttable.h @@ -0,0 +1,220 @@ +/** + * GeoDa TM, Copyright (C) 2011-2015 by Luc Anselin - all rights reserved + * + * This file is part of GeoDa. + * + * GeoDa is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * GeoDa is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * This texttable.h is modified from https://github.com/haarcuba/cpp-text-table + * + */ + +#ifndef __GEODA_CENTER_TEXTTABLE_H +#define __GEODA_CENTER_TEXTTABLE_H + +#include +#include +#include +#include +#include + +class TextTable { + +public: + enum Alignment { LEFT, RIGHT }; + enum MODE { ASCII, MD, LATEX }; + + typedef std::vector< std::string > Row; + TextTable( char horizontal = '-', char vertical = '|', char corner = '+' ) : + _horizontal( horizontal ), + _vertical( vertical ), + _corner( corner ), + mode( TextTable::MD ) + {} + + TextTable( MODE m ) : mode( m ) + { + if ( m == TextTable::MD ) { + _horizontal = '-'; + _vertical = '|'; + _corner = '|'; + } + } + + void setAlignment( unsigned i, Alignment alignment ) + { + _alignment[ i ] = alignment; + } + + Alignment alignment( unsigned i ) const + { return _alignment[ i ]; } + + char vertical() const + { return _vertical; } + + void setVertical( char c) + { _vertical = c;} + + char horizontal() const + { return _horizontal; } + void setHorizontal( char c) + { _horizontal = c; } + + void setCorner( char c) + { _corner = c; } + + void add( std::string const & content ) + { + _current.push_back( content ); + } + + void endOfRow() + { + _rows.push_back( _current ); + _current.assign( 0, "" ); + } + +/* + template + void addRow( Iterator begin, Iterator end ) + { + for( auto i = begin; i != end; ++i ) { + add( * i ); + } + endOfRow(); + } + + template + void addRow( Container const & container ) + { + addRow( container.begin(), container.end() ); + } + */ + std::vector< Row > const & rows() const + { + return _rows; + } + + void setup() const + { + determineWidths(); + setupAlignment(); + } + + std::string ruler() const + { + std::string result; + result += _corner; + std::vector::iterator width; + for( width = _width.begin(); width != _width.end(); ++ width ) { + result += repeat( * width, _horizontal ); + result += _corner; + } + + return result; + } + + int width( unsigned i ) const + { return _width[ i ]; } + + MODE mode; + +private: + char _horizontal; + char _vertical; + char _corner; + Row _current; + std::vector< Row > _rows; + std::vector< unsigned > mutable _width; + std::map< unsigned, Alignment > mutable _alignment; + + static std::string repeat( unsigned times, char c ) + { + std::string result; + for( ; times > 0; -- times ) + result += c; + + return result; + } + + unsigned columns() const + { + return _rows[ 0 ].size(); + } + + void determineWidths() const + { + _width.assign( columns(), 0 ); + for ( int r=0; r < _rows.size(); r++) { + Row const & row = _rows[r]; + for ( unsigned i = 0; i < row.size(); ++i ) { + _width[ i ] = _width[ i ] > row[ i ].size() ? _width[ i ] : row[ i ].size(); + } + } + } + + void setupAlignment() const + { + for ( unsigned i = 0; i < columns(); ++i ) { + if ( _alignment.find( i ) == _alignment.end() ) { + _alignment[ i ] = TextTable::LEFT; + } + } + } +}; + +std::ostream & operator<<( std::ostream & stream, TextTable const & table ) +{ + table.setup(); + if (table.mode == TextTable::ASCII) { + stream << table.ruler() << "\n"; + std::vector< TextTable::Row > const & rows = table.rows(); + for (int r=0; r const & rows = table.rows(); + for (int r=0; r<4F53><4E2D><6587> +LanguageID=$0804 +LanguageCodePage=936 +; If the language you are translating to requires special font faces or +; sizes, uncomment any of the following entries and change them accordingly. +DialogFontName= +DialogFontSize=9 +WelcomeFontName= +WelcomeFontSize=12 +TitleFontName= +;TitleFontSize=29 +CopyrightFontName= +;CopyrightFontSize=8 + +[Messages] + +; *** Application titles +SetupAppTitle=װ +SetupWindowTitle=װ - %1 +UninstallAppTitle=ж +UninstallAppFullTitle=ж - %1 + +; *** Misc. common +InformationTitle=ʾ +ConfirmTitle=ȷ +ErrorTitle= + +; *** SetupLdr messages +SetupLdrStartupMessage=װ %1ȷҪ +LdrCannotCreateTemp=ܴʱļװֹ +LdrCannotExecTemp=ʱĿ¼ִļװֹ + +; *** Startup error messages +LastErrorMessage=%1.%n%nError %2: %3 +SetupFileMissing=ȱļ %1 ȷȷ°汾 +SetupFileCorrupt=װļ𻵣°汾 +SetupFileCorruptOrWrongVer=װļ, 򲻼ݵǰ汾ȷȷ°汾 +NotOnThisPlatform=ڣ %1ϡ +OnlyOnThisPlatform=ڡ%1ϡ +WinVersionTooLowError=Ҫ %1 İ汾 %2 ϡ +WinVersionTooHighError=ܰװڡ %1 %2 ϰ汾 +AdminPrivilegesRequired=ԡϵͳԱ¼ܰװ +PowerUserPrivilegesRequired=ԡϵͳԱPower UsersԱ¼ܰװ +SetupAppRunningError=װ⵽ %1 У%n%nرոó, Ȼȷȡ˳װ +UninstallAppRunningError=װ⵽ %1 У%n%nرոó, Ȼȷȡ˳װ + +; *** Misc. errors +ErrorCreatingDir=װܴĿ¼"%1" +ErrorTooManyFilesInDir=Ŀ¼"%1"а̫ļٴļ + +; *** Setup common messages +ExitSetupTitle=˳װ +ExitSetupMessage=װδɣ˳ϵͳװ%n%nʱгɰװ.%n%nȷ˳װ +AboutSetupMenuItem=(&A)װ... +AboutSetupTitle=ڰװ +AboutSetupMessage=%1 汾 %2%n%3%n%n%1 ҳ:%n%4 +AboutSetupNote= + +; *** Buttons +ButtonBack=< һ(&B) +ButtonNext=һ(&N) > +ButtonInstall=װ(&I) +ButtonOK=ȷ +ButtonCancel=ȡ +ButtonYes=(&Y) +ButtonYesToAll=ȫ(&A) +ButtonNo=(&N) +ButtonNoToAll=ȫ(&o) +ButtonFinish=(&F) +ButtonBrowse=(&B) +ButtonWizardBrowse=(&r)... +ButtonNewFolder=Ŀ¼(&M) + +; *** "Select Language" dialog messages +SelectLanguageTitle=ѡװ +SelectLanguageLabel=ѡװʱʾԣ + +; *** Common wizard text +ClickNext=һȡ˳װ +BeveledLabel= +BrowseDialogTitle=Ŀ¼ +BrowseDialogLabel=ѡĿ¼бȻȷ +NewFolderName=½Ŀ¼ + +; *** "Welcome" wizard page +WelcomeLabel1=ӭʹ [name] װ +WelcomeLabel2=װ [name/ver] ļϣ%n%nڼװǰرȫ + +; *** "Password" wizard page +WizardPassword= +PasswordLabel1=װ뱣 +PasswordLabel3=룬ȻһִСд +PasswordEditLabel=(&P): +IncorrectPassword=벻ȷ + +; *** "License Agreement" wizard page +WizardLicense=Э +LicenseLabel=ڰװǰҪϢ +LicenseLabel3=Э飬ܼװ +LicenseAccepted=ܴЭ(&A) +LicenseNotAccepted=ܴЭ(&D) + +; *** "Information" wizard pages +WizardInfoBefore=ʾ +InfoBeforeLabel=ڰװǰҪϢ +InfoBeforeClickLabel=׼üװһ +WizardInfoAfter=ʾ +InfoAfterLabel=ڼǰҪϢ +InfoAfterClickLabel=׼üһ + +; *** "User Information" wizard page +WizardUserInfo=ûϢ +UserInfoDesc=Ϣ +UserInfoName=û(&U): +UserInfoOrg=˾(&O): +UserInfoSerial=к(&S): +UserInfoNameRequired= + +; *** "Select Destination Location" wizard page +WizardSelectDir=ѡĿ· +SelectDirDesc=ȷ [name] װ +SelectDirLabel3=򽫰װ [name] Ŀ¼ +SelectDirBrowseLabel=һѡͬĿ¼ +DiskSpaceMBLabel=Ҫ [mb] MB ̿ռ +ToUNCPathname=ܰװһ UNC ·밲װϣҪӳ· +InvalidPath=һ̷·; :%n%nC:\APP%n%:%n%n\\server\share +InvalidDrive=ѡUNCڻܷʣѡ +DiskSpaceWarningTitle=û㹻Ĵ̿ռ +DiskSpaceWarning=װҪ%1KB̿ռ, Ŀ̽%2KB.%n%nװ +DirNameTooLong=Ŀ¼·̫ +InvalidDirName=Ŀ¼Ч +BadDirName32=Ŀ¼ַܰ:%n%n%1 +DirExistsTitle=Ŀ¼Ѿ +DirExists=Ŀ¼:%n%n%1%n%nѾڣ밲װĿ¼ +DirDoesntExistTitle=Ŀ¼ +DirDoesntExist=Ŀ¼:%n%n%1%n%nڣ봴Ŀ¼ + +; *** "Select Components" wizard page +WizardSelectComponents=ѡ +SelectComponentsDesc=Щװ +SelectComponentsLabel2=ѡ밲װ밲װɺһ +FullInstallation=ȫװ +; if possible don't translate 'Compact' as 'Minimal' (I mean 'Minimal' in your language) +CompactInstallation=Сװ +CustomInstallation=Զ尲װ +NoUninstallWarningTitle=Ѿ +NoUninstallWarning=װѾװļ:%n%n%1%n%nȡѡж.%n%n +ComponentSize1=%1 KB +ComponentSize2=%1 MB +ComponentsDiskSpaceMBLabel=ǰѡҪ [mb] MB ̿ռ + +; *** "Select Additional Tasks" wizard page +WizardSelectTasks=ѡ񸽼 +SelectTasksDesc=һ񽫱ִУ +SelectTasksLabel2=ѡ񵱰װ [name] ʱϣִеĸȻ㡾һ + +; *** "Select Start Menu Folder" wizard page +WizardSelectProgramGroup=ѡ˵Ŀ¼ +SelectStartMenuFolderDesc=ӿݷʽ˵ +SelectStartMenuFolderLabel3=װ˵ݷʽ +SelectStartMenuFolderBrowseLabel=һѡͬĿ¼ +NoIconsCheck=κͼ(&D) +MustEnterGroupName=һĿ¼ +GroupNameTooLong=Ŀ¼·̫ +InvalidGroupName=Ŀ¼Ч +BadGroupName=Ŀ¼ַܰ:%n%n%1 +NoProgramGroupCheck2=ܴĿ¼(&D) + +; *** "Ready to Install" wizard page +WizardReady=׼ðװ +ReadyLabel1=Ѿ׼ðװ [name] ļ +ReadyLabel2a=װԼװ,鿴޸ãһ +ReadyLabel2b=װԼװ +ReadyMemoUserInfo=ûϢ +ReadyMemoDir=װĿ¼ +ReadyMemoType=װͣ +ReadyMemoComponents=ѡ +ReadyMemoGroup=ʼ˵Ŀ¼ +ReadyMemoTasks= + +; *** "Preparing to Install" wizard page +WizardPreparing=׼װ +PreparingDesc=װΪ [name] װļ׼ +PreviousInstallNotCompleted=װ/ж ԭijδɡΪɰװҪ%n%nаװɰװ[name] +CannotContinue=װܼȡ˳ + +; *** "Installing" wizard page +WizardInstalling=װ +InstallingLabel=ȴڰװ [name] ļ + +; *** "Setup Completed" wizard page +FinishedHeadingLabel= [name] װ +FinishedLabelNoIcons=װѾ [name] װļ +FinishedLabel=װѾ [name] װļϡͨӦͼװõij +ClickFinish=ɡ˳װ +FinishedRestartLabel= [name] װ, װļ +FinishedRestartMessage=Ϊ [name] İװװļ%n%n +ShowReadmeCheck=ǵģ鿴 README ļ +YesRadio=(&Y) +NoRadio=(&N)ҽԺ +; used for example as 'Run MyProg.exe' +RunEntryExec= %1 +; used for example as 'View Readme.txt' +RunEntryShellExec=鿴 %1 + +; *** "Setup Needs the Next Disk" stuff +ChangeDiskTitle=װҪһ +SelectDiskLabel2= %1 Ȼȷ%n%nļĿ¼ȷ· +PathLabel=·(&) +FileNotInDir2=ļ "%1" ûĿ¼ "%2" бҵȷ̻ѡĿ¼ +SelectDirectoryLabel=ָһ̵λ + +; *** Installation phase messages +SetupAborted=װδɡ%n%nٰװ +EntryAbortRetryIgnore=ԡԣԡֹȡװ + +; *** Installation status messages +StatusCreateDirs=Ŀ¼... +StatusExtractFiles=ѹļ... +StatusCreateIcons=ݷʽ... +StatusCreateIniEntries= INI Ŀ... +StatusCreateRegistryEntries=עĿ... +StatusRegisterFiles=עļ... +StatusSavingUninstall=жϢ... +StatusRunProgram=ɰװ... +StatusRollback=ع޸... + +; *** Misc. errors +ErrorInternal2=ڲ%1 +ErrorFunctionFailedNoCode=%1 ʧ +ErrorFunctionFailed=%1 ʧܣ %2 +ErrorFunctionFailedWithMessage=%1 ʧܣ %2.%n%3 +ErrorExecutingProgram=ִļ%n%1 + +; *** Registry errors +ErrorRegOpenKey=ע%n%1\%2 +ErrorRegCreateKey=ע%n%1\%2 +ErrorRegWriteKey=дע%n%1\%2 + +; *** INI errors +ErrorIniEntry=ļ"%1"дINIĿ + +; *** File copying errors +FileAbortRetryIgnore=ԡԣԡԸļ()ֹȡװ +FileAbortRetryIgnore2=ԡԣԡ()ֹȡװ +SourceIsCorrupted=Դļ +SourceDoesntExist=Դļ "%1" +ExistingFileReadOnly=ļѴұʶΪֻ.%n%nԡƳֻԺԣֹȡװ +ErrorReadingExistingDest=ԶѴļʱһ +FileExists=ļѾڡ%n%n븲 +ExistingFileNewer=ѾڵļҪװļ£ļ%n%n뱣еļ +ErrorChangingAttr=޸Ĵļʱ +ErrorCreatingTemp=Ŀ·ļʱ +ErrorReadingSource=Դļʱ +ErrorCopying=ļʱ +ErrorReplacingExistingFile=滻ļʱ +ErrorRestartReplace=滻ʧܣ +ErrorRenamingTemp=ĿĿ¼޸ļʱ +ErrorRegisterServer=ע DLL/OCX: %1 +ErrorRegisterServerMissingExport=DllRegisterServer ûз +ErrorRegisterTypeLib=ע⣺%1 + +; *** Post-installation errors +ErrorOpeningReadme= README ļʱ +ErrorRestartingComputer=װֹ + +; *** Uninstaller messages +UninstallNotFound=ļ "%1" ڣж +UninstallOpenError=ļ "%1" ܱ򿪣ж +UninstallUnsupportedVer=жؼ¼ļ "%1"ʽ뵱ǰжس򲻷ж +UninstallUnknownEntry=жؼ¼ļδ֪Ŀ (%1) +ConfirmUninstall=ȷʵȫƳ %1 +OnlyAdminCanUninstall=ûϵͳԱȨʱжظó +UninstallStatusLabel=ڴļƳ %1 ȴ +UninstalledAll=%1 ȫĴļƳ +UninstalledMost=%1 жɣ%n%nϲܱɾֹɾ +UninstalledAndNeedsRestart=Ϊ %1 İװļ%n%n +UninstallDataCorrupted="%1" ļ𻵣ж + +; *** Uninstallation phase messages +ConfirmDeleteSharedFileTitle=Ƴļ +ConfirmDeleteSharedFile2=¹ļϵͳʾΪٱʹã%n%nκγȻҪʹЩļDZƳЩпܲȷѡ񡾷񡿣Щļϵͳﲻκ˺ +SharedFileNameLabel=ļ: +SharedFileLocationLabel=λ: +WizardUninstalling=ж״̬ +StatusUninstalling=ж %1... + +; The custom messages below aren't used by Setup itself, but if you make +; use of them in your scripts, you'll want to translate them. + +[CustomMessages] + +NameAndVersion=%1 汾 %2 +AdditionalIcons=ͼ꣺ +CreateDesktopIcon=ͼ +CreateQuickLaunchIcon=ͼ(&Q) +ProgramOnTheWeb=%1 Web +UninstallProgram=ж %1 +LaunchProgram= %1 +AssocFileExtension= %1 %2 ļչ(&A) +AssocingFileExtension= %1 %2 ļչ... diff --git a/BuildTools/CommonDistFiles/cartodb/GNUmakefile b/BuildTools/CommonDistFiles/cartodb/GNUmakefile new file mode 100644 index 000000000..cd4507a0d --- /dev/null +++ b/BuildTools/CommonDistFiles/cartodb/GNUmakefile @@ -0,0 +1,14 @@ + + +include ../../../GDALmake.opt + +OBJ = ogrcartodbdriver.o ogrcartodbdatasource.o ogrcartodblayer.o ogrcartodbtablelayer.o ogrcartodbresultlayer.o + +CPPFLAGS := $(JSON_INCLUDE) -I.. -I../.. -I../pgdump $(CPPFLAGS) + +default: $(O_OBJ:.o=.$(OBJ_EXT)) + +clean: + rm -f *.o $(O_OBJ) + +$(O_OBJ): ogr_cartodb.h \ No newline at end of file diff --git a/BuildTools/CommonDistFiles/cartodb/drv_cartodb.html b/BuildTools/CommonDistFiles/cartodb/drv_cartodb.html new file mode 100644 index 000000000..b5014251a --- /dev/null +++ b/BuildTools/CommonDistFiles/cartodb/drv_cartodb.html @@ -0,0 +1,158 @@ + + +CartoDB + + + + +

CartoDB

+ +(GDAL/OGR >= 1.11)

+ +This driver can connect to the services implementing the CartoDB API. +GDAL/OGR must be built with Curl support in order for the +CartoDB driver to be compiled.

+ +The driver supports read and write operations.

+ +

Dataset name syntax

+ +The minimal syntax to open a CartoDB datasource is :
CartoDB:[connection_name]

+ +For single-user accounts, connection name is the account name. +For multi-user accounts, connection_name must be the user name, not the account name. + +Additionnal optional parameters can be specified after the ':' sign. +Currently the following one is supported :

+ +

    +
  • tables=table_name1[,table_name2]*: A list of table names. +This is necessary when you need to access to public tables for example. +
+ +If several parameters are specified, they must be separated by a space.

+ +

Configuration options

+ +The following configuration options are available : +
    +
  • CARTODB_API_URL: defaults to https://[account_name].cartodb.com/api/v2/sql. +Can be used to point to another server.
  • +
  • CARTODB_HTTPS: can be set to NO to use http:// protocol instead of +https:// (only if CARTODB_API_URL is not defined).
  • +
  • CARTODB_API_KEY: see following paragraph.
  • +
+ + +

Authentication

+ +Most operations, in particular write operations, require an authenticated +access. The only exception is read-only access to public tables.

+ +Authenticated access is obtained by specifying the API key given in the +management interface of the CartoDB service. It is specified with the +CARTODB_API_KEY configuration option.

+ +

Geometry

+ +The OGR driver will report as many geometry fields as available in the +layer (except the 'the_geom_webmercator' field), following RFC 41. + +

Filtering

+ +The driver will forward any spatial filter set with SetSpatialFilter() to +the server. It also makes the same for attribute +filters set with SetAttributeFilter().

+ +

Paging

+ +Features are retrieved from the server by chunks of 500 by default. +This number can be altered with the CARTODB_PAGE_SIZE +configuration option.

+ +

Write support

+ +Table creation and deletion is possible.

+ +Write support is only enabled when the datasource is opened in update mode.

+ +The mapping between the operations of the CartoDB service and the OGR concepts is the following : +

    +
  • OGRFeature::CreateFeature() <==> INSERT operation
  • +
  • OGRFeature::SetFeature() <==> UPDATE operation
  • +
  • OGRFeature::DeleteFeature() <==> DELETE operation
  • +
  • OGRDataSource::CreateLayer() <==> CREATE TABLE operation
  • +
  • OGRDataSource::DeleteLayer() <==> DROP TABLE operation
  • +
+ +When inserting a new feature with CreateFeature(), and if the command is successful, OGR will fetch the +returned rowid and use it as the OGR FID.

+ +The above operations are by default issued to the server synchronously with the OGR API call. This however +can cause performance penalties when issuing a lot of commands due to many client/server exchanges.

+ +So, on a newly created layer, the INSERT of CreateFeature() operations are grouped together +in chunks until they reach 15 MB (can be changed with the CARTODB_MAX_CHUNK_SIZE +configuration option, with a value in MB), at which point they are transferred +to the server. By setting CARTODB_MAX_CHUNK_SIZE to 0, immediate transfer occurs.

+ +

SQL

+ +SQL commands provided to the OGRDataSource::ExecuteSQL() call are executed on the server side, unless the OGRSQL +dialect is specified. You can use the full power of PostgreSQL + PostGIS SQL +capabilities.

+ +

Open options

+ +

Starting with GDAL 2.0, the following open options are available:

+
    +
  • BATCH_INSERT=YES/NO: Whether to group feature insertions in a batch. +Defaults to YES. Only apply in creation or update mode.
  • +
+ +

Layer creation options

+ +

The following layer creation options are available:

+
    +
  • OVERWRITE=YES/NO: Whether to overwrite an existing table with the +layer name to be created. Defaults to NO.
  • + +
  • GEOMETRY_NULLABLE=YES/NO: Whether the values of the geometry column +can be NULL. Defaults to YES.
  • + +
  • CARTODBFY=YES/NO: Whether the created layer should be "CartoDBifi'ed" + (i.e. registered in dashboard). Defaults to YES.
  • + +
  • LAUNDER=YES/NO: This may be "YES" to force new fields created on this +layer to have their field names "laundered" into a form more compatible with +PostgreSQL. This converts to lower case and converts some special characters +like "-" and "#" to "_". If "NO" exact names are preserved. +The default value is "YES". If enabled the table (layer) name will also be laundered.
  • + +
+ + +

Examples

+ +
  • +Acceccing data from a public table: +
    +ogrinfo -ro "CartoDB:gdalautotest2 tables=tm_world_borders_simpl_0_3"
    +
    +

    + +

  • +Creating and populating a table from a shapefile: +
    +ogr2ogr --config CARTODB_API_KEY abcdefghijklmnopqrstuvw -f CartoDB "CartoDB:myaccount" myshapefile.shp
    +
    +

    + +

    See Also

    + + + + + diff --git a/BuildTools/CommonDistFiles/cartodb/makefile.vc b/BuildTools/CommonDistFiles/cartodb/makefile.vc new file mode 100644 index 000000000..0a7c1cdc0 --- /dev/null +++ b/BuildTools/CommonDistFiles/cartodb/makefile.vc @@ -0,0 +1,16 @@ + +OBJ = ogrcartodbdriver.obj ogrcartodbdatasource.obj ogrcartodblayer.obj ogrcartodbtablelayer.obj ogrcartodbresultlayer.obj + +EXTRAFLAGS = -I.. -I..\.. -I..\geojson\libjson -I..\pgdump + +GDAL_ROOT = ..\..\.. + +!INCLUDE $(GDAL_ROOT)\nmake.opt + +default: $(OBJ) + +clean: + -del *.obj *.pdb + + + diff --git a/BuildTools/CommonDistFiles/cartodb/ogr_cartodb.h b/BuildTools/CommonDistFiles/cartodb/ogr_cartodb.h new file mode 100644 index 000000000..00f94689e --- /dev/null +++ b/BuildTools/CommonDistFiles/cartodb/ogr_cartodb.h @@ -0,0 +1,278 @@ +/****************************************************************************** + * $Id$ + * + * Project: CARTODB Translator + * Purpose: Definition of classes for OGR CartoDB driver. + * Author: Even Rouault, even dot rouault at mines dash paris dot org + * + ****************************************************************************** + * Copyright (c) 2013, Even Rouault + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + ****************************************************************************/ + +#ifndef OGR_CARTODB_H_INCLUDED +#define OGR_CARTODB_H_INCLUDED + +#include "ogrsf_frmts.h" +#include "cpl_http.h" + +#include +#include + +json_object* OGRCARTODBGetSingleRow(json_object* poObj); +CPLString OGRCARTODBEscapeIdentifier(const char* pszStr); +CPLString OGRCARTODBEscapeLiteral(const char* pszStr); + +/************************************************************************/ +/* OGRCartoDBGeomFieldDefn */ +/************************************************************************/ + +class OGRCartoDBGeomFieldDefn: public OGRGeomFieldDefn +{ + public: + int nSRID; + + OGRCartoDBGeomFieldDefn(const char* pszNameIn, OGRwkbGeometryType eType) : + OGRGeomFieldDefn(pszNameIn, eType), nSRID(0) + { + } +}; + +/************************************************************************/ +/* OGRCARTODBLayer */ +/************************************************************************/ +class OGRCARTODBDataSource; + +class OGRCARTODBLayer : public OGRLayer +{ +protected: + OGRCARTODBDataSource* poDS; + + OGRFeatureDefn *poFeatureDefn; + CPLString osBaseSQL; + CPLString osFIDColName; + + int bEOF; + int nFetchedObjects; + int iNextInFetchedObjects; + GIntBig iNext; + json_object *poCachedObj; + + virtual OGRFeature *GetNextRawFeature(); + OGRFeature *BuildFeature(json_object* poRowObj); + + void EstablishLayerDefn(const char* pszLayerName, + json_object* poObjIn); + OGRSpatialReference *GetSRS(const char* pszGeomCol, int *pnSRID); + virtual CPLString GetSRS_SQL(const char* pszGeomCol) = 0; + + public: + OGRCARTODBLayer(OGRCARTODBDataSource* poDS); + ~OGRCARTODBLayer(); + + virtual void ResetReading(); + virtual OGRFeature * GetNextFeature(); + + virtual OGRFeatureDefn * GetLayerDefn(); + virtual OGRFeatureDefn * GetLayerDefnInternal(json_object* poObjIn) = 0; + virtual json_object* FetchNewFeatures(GIntBig iNext); + + virtual const char* GetFIDColumn() { return osFIDColName.c_str(); } + + virtual int TestCapability( const char * ); + + int GetFeaturesToFetch() { return atoi(CPLGetConfigOption("CARTODB_PAGE_SIZE", "500")); } +}; + +typedef enum +{ + INSERT_UNINIT, + INSERT_SINGLE_FEATURE, + INSERT_MULTIPLE_FEATURE +} InsertState; + +/************************************************************************/ +/* OGRCARTODBTableLayer */ +/************************************************************************/ + +class OGRCARTODBTableLayer : public OGRCARTODBLayer +{ + CPLString osName; + CPLString osQuery; + CPLString osWHERE; + CPLString osSELECTWithoutWHERE; + + int bLaunderColumnNames; + + int bInDeferedInsert; + InsertState eDeferedInsertState; + CPLString osDeferedInsertSQL; + GIntBig nNextFID; + + int bDeferedCreation; + int bCartoDBify; + int nMaxChunkSize; + + void BuildWhere(); + + virtual CPLString GetSRS_SQL(const char* pszGeomCol); + + public: + OGRCARTODBTableLayer(OGRCARTODBDataSource* poDS, const char* pszName); + ~OGRCARTODBTableLayer(); + + virtual const char* GetName() { return osName.c_str(); } + virtual OGRFeatureDefn * GetLayerDefnInternal(json_object* poObjIn); + virtual json_object* FetchNewFeatures(GIntBig iNext); + + virtual GIntBig GetFeatureCount( int bForce = TRUE ); + virtual OGRFeature *GetFeature( GIntBig nFeatureId ); + + virtual int TestCapability( const char * ); + + virtual OGRErr CreateField( OGRFieldDefn *poField, + int bApproxOK = TRUE ); + + virtual OGRErr DeleteField( int iField ); + + virtual OGRFeature *GetNextRawFeature(); + + virtual OGRErr ICreateFeature( OGRFeature *poFeature ); + virtual OGRErr ISetFeature( OGRFeature *poFeature ); + virtual OGRErr DeleteFeature( GIntBig nFID ); + + virtual void SetSpatialFilter( OGRGeometry *poGeom ) { SetSpatialFilter(0, poGeom); } + virtual void SetSpatialFilter( int iGeomField, OGRGeometry *poGeom ); + virtual OGRErr SetAttributeFilter( const char * ); + + virtual OGRErr GetExtent( OGREnvelope *psExtent, int bForce ) { return GetExtent(0, psExtent, bForce); } + virtual OGRErr GetExtent( int iGeomField, OGREnvelope *psExtent, int bForce ); + + void SetLaunderFlag( int bFlag ) + { bLaunderColumnNames = bFlag; } + void SetDeferedCreation( OGRwkbGeometryType eGType, + OGRSpatialReference* poSRS, + int bGeomNullable, + int bCartoDBify); + OGRErr RunDeferedCreationIfNecessary(); + int GetDeferedCreation() const { return bDeferedCreation; } + void CancelDeferedCreation() { bDeferedCreation = FALSE; bCartoDBify = FALSE; } + + OGRErr FlushDeferedInsert(bool bReset = true); + void RunDeferedCartoDBfy(); +}; + +/************************************************************************/ +/* OGRCARTODBResultLayer */ +/************************************************************************/ + +class OGRCARTODBResultLayer : public OGRCARTODBLayer +{ + OGRFeature *poFirstFeature; + + virtual CPLString GetSRS_SQL(const char* pszGeomCol); + + public: + OGRCARTODBResultLayer( OGRCARTODBDataSource* poDS, + const char * pszRawStatement ); + virtual ~OGRCARTODBResultLayer(); + + virtual OGRFeatureDefn *GetLayerDefnInternal(json_object* poObjIn); + virtual OGRFeature *GetNextRawFeature(); + + int IsOK(); +}; + +/************************************************************************/ +/* OGRCARTODBDataSource */ +/************************************************************************/ + +class OGRCARTODBDataSource : public OGRDataSource +{ + char* pszName; + char* pszAccount; + + OGRCARTODBTableLayer** papoLayers; + int nLayers; + + int bReadWrite; + int bBatchInsert; + + int bUseHTTPS; + + CPLString osAPIKey; + + int bMustCleanPersistant; + + CPLString osCurrentSchema; + + int bHasOGRMetadataFunction; + + int nPostGISMajor, nPostGISMinor; + + public: + OGRCARTODBDataSource(); + ~OGRCARTODBDataSource(); + + int Open( const char * pszFilename, + char** papszOpenOptions, + int bUpdate ); + + virtual const char* GetName() { return pszName; } + + virtual int GetLayerCount() { return nLayers; } + virtual OGRLayer* GetLayer( int ); + virtual OGRLayer *GetLayerByName(const char *); + + virtual int TestCapability( const char * ); + + virtual OGRLayer *ICreateLayer( const char *pszName, + OGRSpatialReference *poSpatialRef = NULL, + OGRwkbGeometryType eGType = wkbUnknown, + char ** papszOptions = NULL ); + virtual OGRErr DeleteLayer(int); + + virtual OGRLayer * ExecuteSQL( const char *pszSQLCommand, + OGRGeometry *poSpatialFilter, + const char *pszDialect ); + virtual void ReleaseResultSet( OGRLayer * poLayer ); + + const char* GetAPIURL() const; + int IsReadWrite() const { return bReadWrite; } + int DoBatchInsert() const { return bBatchInsert; } + char** AddHTTPOptions(); + json_object* RunSQL(const char* pszUnescapedSQL); + const CPLString& GetCurrentSchema() { return osCurrentSchema; } + int FetchSRSId( OGRSpatialReference * poSRS ); + + int IsAuthenticatedConnection() { return osAPIKey.size() != 0; } + int HasOGRMetadataFunction() { return bHasOGRMetadataFunction; } + void SetOGRMetadataFunction(int bFlag) { bHasOGRMetadataFunction = bFlag; } + + OGRLayer * ExecuteSQLInternal( const char *pszSQLCommand, + OGRGeometry *poSpatialFilter = NULL, + const char *pszDialect = NULL, + int bRunDeferedActions = FALSE ); + + int GetPostGISMajor() const { return nPostGISMajor; } + int GetPostGISMinor() const { return nPostGISMinor; } +}; + +#endif /* ndef OGR_CARTODB_H_INCLUDED */ diff --git a/BuildTools/CommonDistFiles/cartodb/ogrcartodbdatasource.cpp b/BuildTools/CommonDistFiles/cartodb/ogrcartodbdatasource.cpp new file mode 100644 index 000000000..958f8de13 --- /dev/null +++ b/BuildTools/CommonDistFiles/cartodb/ogrcartodbdatasource.cpp @@ -0,0 +1,774 @@ +/****************************************************************************** + * $Id$ + * + * Project: CartoDB Translator + * Purpose: Implements OGRCARTODBDataSource class + * Author: Even Rouault, even dot rouault at mines dash paris dot org + * + ****************************************************************************** + * Copyright (c) 2013, Even Rouault + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + ****************************************************************************/ + +#include "ogr_cartodb.h" +#include "ogr_pgdump.h" + +CPL_CVSID("$Id$"); + +/************************************************************************/ +/* OGRCARTODBDataSource() */ +/************************************************************************/ + +OGRCARTODBDataSource::OGRCARTODBDataSource() + +{ + papoLayers = NULL; + nLayers = 0; + + pszName = NULL; + pszAccount = NULL; + + bReadWrite = FALSE; + bBatchInsert = TRUE; + bUseHTTPS = FALSE; + + bMustCleanPersistant = FALSE; + bHasOGRMetadataFunction = -1; + nPostGISMajor = 2; + nPostGISMinor = 0; +} + +/************************************************************************/ +/* ~OGRCARTODBDataSource() */ +/************************************************************************/ + +OGRCARTODBDataSource::~OGRCARTODBDataSource() + +{ + for( int i = 0; i < nLayers; i++ ) + delete papoLayers[i]; + CPLFree( papoLayers ); + + if (bMustCleanPersistant) + { + char** papszOptions = NULL; + papszOptions = CSLSetNameValue(papszOptions, "CLOSE_PERSISTENT", CPLSPrintf("CARTO:%p", this)); + CPLHTTPDestroyResult( CPLHTTPFetch( GetAPIURL(), papszOptions) ); + CSLDestroy(papszOptions); + } + + CPLFree( pszName ); + CPLFree( pszAccount ); +} + +/************************************************************************/ +/* TestCapability() */ +/************************************************************************/ + +int OGRCARTODBDataSource::TestCapability( const char * pszCap ) + +{ + if( bReadWrite && EQUAL(pszCap,ODsCCreateLayer) ) + return TRUE; + else if( bReadWrite && EQUAL(pszCap,ODsCDeleteLayer) ) + return TRUE; + else + return FALSE; +} + +/************************************************************************/ +/* GetLayer() */ +/************************************************************************/ + +OGRLayer *OGRCARTODBDataSource::GetLayer( int iLayer ) + +{ + if( iLayer < 0 || iLayer >= nLayers ) + return NULL; + else + return papoLayers[iLayer]; +} + +/************************************************************************/ +/* GetLayerByName() */ +/************************************************************************/ + +OGRLayer *OGRCARTODBDataSource::GetLayerByName(const char * pszLayerName) +{ + OGRLayer* poLayer = OGRDataSource::GetLayerByName(pszLayerName); + return poLayer; +} + +/************************************************************************/ +/* OGRCARTODBGetOptionValue() */ +/************************************************************************/ + +static CPLString OGRCARTODBGetOptionValue(const char* pszFilename, + const char* pszOptionName) +{ + CPLString osOptionName(pszOptionName); + osOptionName += "="; + const char* pszOptionValue = strstr(pszFilename, osOptionName); + if (!pszOptionValue) + return ""; + + CPLString osOptionValue(pszOptionValue + strlen(osOptionName)); + const char* pszSpace = strchr(osOptionValue.c_str(), ' '); + if (pszSpace) + osOptionValue.resize(pszSpace - osOptionValue.c_str()); + return osOptionValue; +} + +/************************************************************************/ +/* Open() */ +/************************************************************************/ + +int OGRCARTODBDataSource::Open( const char * pszFilename, + char** papszOpenOptionsIn, + int bUpdateIn ) + +{ + bReadWrite = bUpdateIn; + bBatchInsert = CSLTestBoolean(CSLFetchNameValueDef(papszOpenOptionsIn, "BATCH_INSERT", "YES")); + + pszName = CPLStrdup( pszFilename ); + if( CSLFetchNameValue(papszOpenOptionsIn, "ACCOUNT") ) + pszAccount = CPLStrdup(CSLFetchNameValue(papszOpenOptionsIn, "ACCOUNT")); + else + { + pszAccount = CPLStrdup(pszFilename + strlen("CARTO:")); + char* pchSpace = strchr(pszAccount, ' '); + if( pchSpace ) + *pchSpace = '\0'; + if( pszAccount[0] == 0 ) + { + CPLError(CE_Failure, CPLE_AppDefined, "Missing account name"); + return FALSE; + } + } + + osAPIKey = CSLFetchNameValueDef(papszOpenOptionsIn, "API_KEY", + CPLGetConfigOption("CARTODB_API_KEY", "")); + + CPLString osTables = OGRCARTODBGetOptionValue(pszFilename, "tables"); + + /*if( osTables.size() == 0 && osAPIKey.size() == 0 ) + { + CPLError(CE_Failure, CPLE_AppDefined, + "When not specifying tables option, CARTODB_API_KEY must be defined"); + return FALSE; + }*/ + + bUseHTTPS = CSLTestBoolean(CPLGetConfigOption("CARTODB_HTTPS", "YES")); + + OGRLayer* poSchemaLayer = ExecuteSQLInternal("SELECT current_schema()"); + if( poSchemaLayer ) + { + OGRFeature* poFeat = poSchemaLayer->GetNextFeature(); + if( poFeat ) + { + if( poFeat->GetFieldCount() == 1 ) + { + osCurrentSchema = poFeat->GetFieldAsString(0); + } + delete poFeat; + } + ReleaseResultSet(poSchemaLayer); + } + if( osCurrentSchema.size() == 0 ) + return FALSE; + +/* -------------------------------------------------------------------- */ +/* Find out PostGIS version */ +/* -------------------------------------------------------------------- */ + if( bReadWrite ) + { + OGRLayer* poPostGISVersionLayer = ExecuteSQLInternal("SELECT postgis_version()"); + if( poPostGISVersionLayer ) + { + OGRFeature* poFeat = poPostGISVersionLayer->GetNextFeature(); + if( poFeat ) + { + if( poFeat->GetFieldCount() == 1 ) + { + const char* pszVersion = poFeat->GetFieldAsString(0); + nPostGISMajor = atoi(pszVersion); + const char* pszDot = strchr(pszVersion, '.'); + nPostGISMinor = 0; + if( pszDot ) + nPostGISMinor = atoi(pszDot + 1); + } + delete poFeat; + } + ReleaseResultSet(poPostGISVersionLayer); + } + } + + if( osAPIKey.size() && bUpdateIn ) + { + ExecuteSQLInternal( + "DROP FUNCTION IF EXISTS ogr_table_metadata(TEXT,TEXT); " + "CREATE OR REPLACE FUNCTION ogr_table_metadata(schema_name TEXT, table_name TEXT) RETURNS TABLE " + "(attname TEXT, typname TEXT, attlen INT, format_type TEXT, " + "attnum INT, attnotnull BOOLEAN, indisprimary BOOLEAN, " + "defaultexpr TEXT, dim INT, srid INT, geomtyp TEXT, srtext TEXT) AS $$ " + "SELECT a.attname::text, t.typname::text, a.attlen::int, " + "format_type(a.atttypid,a.atttypmod)::text, " + "a.attnum::int, " + "a.attnotnull::boolean, " + "i.indisprimary::boolean, " + "pg_get_expr(def.adbin, c.oid)::text AS defaultexpr, " + "(CASE WHEN t.typname = 'geometry' THEN postgis_typmod_dims(a.atttypmod) ELSE NULL END)::int dim, " + "(CASE WHEN t.typname = 'geometry' THEN postgis_typmod_srid(a.atttypmod) ELSE NULL END)::int srid, " + "(CASE WHEN t.typname = 'geometry' THEN postgis_typmod_type(a.atttypmod) ELSE NULL END)::text geomtyp, " + "srtext " + "FROM pg_class c " + "JOIN pg_attribute a ON a.attnum > 0 AND " + "a.attrelid = c.oid AND c.relname = $2 " + "AND c.relname IN (SELECT CDB_UserTables())" + "JOIN pg_type t ON a.atttypid = t.oid " + "JOIN pg_namespace n ON c.relnamespace=n.oid AND n.nspname = $1 " + "LEFT JOIN pg_index i ON c.oid = i.indrelid AND " + "i.indisprimary = 't' AND a.attnum = ANY(i.indkey) " + "LEFT JOIN pg_attrdef def ON def.adrelid = c.oid AND " + "def.adnum = a.attnum " + "LEFT JOIN spatial_ref_sys srs ON srs.srid = postgis_typmod_srid(a.atttypmod) " + "ORDER BY a.attnum " + "$$ LANGUAGE SQL"); + } + + if (osTables.size() != 0) + { + char** papszTables = CSLTokenizeString2(osTables, ",", 0); + for(int i=0;papszTables && papszTables[i];i++) + { + papoLayers = (OGRCARTODBTableLayer**) CPLRealloc( + papoLayers, (nLayers + 1) * sizeof(OGRCARTODBTableLayer*)); + papoLayers[nLayers ++] = new OGRCARTODBTableLayer(this, papszTables[i]); + } + CSLDestroy(papszTables); + return TRUE; + } + + OGRLayer* poTableListLayer = ExecuteSQLInternal("SELECT CDB_UserTables()"); + if( poTableListLayer ) + { + OGRFeature* poFeat; + while( (poFeat = poTableListLayer->GetNextFeature()) != NULL ) + { + if( poFeat->GetFieldCount() == 1 ) + { + papoLayers = (OGRCARTODBTableLayer**) CPLRealloc( + papoLayers, (nLayers + 1) * sizeof(OGRCARTODBTableLayer*)); + papoLayers[nLayers ++] = new OGRCARTODBTableLayer( + this, poFeat->GetFieldAsString(0)); + } + delete poFeat; + } + ReleaseResultSet(poTableListLayer); + } + else if( osCurrentSchema == "public" ) + return FALSE; + + /* There's currently a bug with CDB_UserTables() on multi-user accounts */ + if( nLayers == 0 && osCurrentSchema != "public" ) + { + CPLString osSQL; + osSQL.Printf("SELECT c.relname FROM pg_class c, pg_namespace n " + "WHERE c.relkind in ('r', 'v') AND c.relname !~ '^pg_' AND c.relnamespace=n.oid AND n.nspname = '%s'", + OGRCARTODBEscapeLiteral(osCurrentSchema).c_str()); + poTableListLayer = ExecuteSQLInternal(osSQL); + if( poTableListLayer ) + { + OGRFeature* poFeat; + while( (poFeat = poTableListLayer->GetNextFeature()) != NULL ) + { + if( poFeat->GetFieldCount() == 1 ) + { + papoLayers = (OGRCARTODBTableLayer**) CPLRealloc( + papoLayers, (nLayers + 1) * sizeof(OGRCARTODBTableLayer*)); + papoLayers[nLayers ++] = new OGRCARTODBTableLayer( + this, poFeat->GetFieldAsString(0)); + } + delete poFeat; + } + ReleaseResultSet(poTableListLayer); + } + else + return FALSE; + } + + return TRUE; +} + +/************************************************************************/ +/* GetAPIURL() */ +/************************************************************************/ + +const char* OGRCARTODBDataSource::GetAPIURL() const +{ + const char* pszAPIURL = CPLGetConfigOption("CARTODB_API_URL", NULL); + if (pszAPIURL) + return pszAPIURL; + else if (bUseHTTPS) + return CPLSPrintf("https://%s.carto.com/api/v2/sql", pszAccount); + else + return CPLSPrintf("http://%s.carto.com/api/v2/sql", pszAccount); +} + +/************************************************************************/ +/* FetchSRSId() */ +/************************************************************************/ + +int OGRCARTODBDataSource::FetchSRSId( OGRSpatialReference * poSRS ) + +{ + const char* pszAuthorityName; + + if( poSRS == NULL ) + return 0; + + OGRSpatialReference oSRS(*poSRS); + poSRS = NULL; + + pszAuthorityName = oSRS.GetAuthorityName(NULL); + + if( pszAuthorityName == NULL || strlen(pszAuthorityName) == 0 ) + { +/* -------------------------------------------------------------------- */ +/* Try to identify an EPSG code */ +/* -------------------------------------------------------------------- */ + oSRS.AutoIdentifyEPSG(); + + pszAuthorityName = oSRS.GetAuthorityName(NULL); + if (pszAuthorityName != NULL && EQUAL(pszAuthorityName, "EPSG")) + { + const char* pszAuthorityCode = oSRS.GetAuthorityCode(NULL); + if ( pszAuthorityCode != NULL && strlen(pszAuthorityCode) > 0 ) + { + /* Import 'clean' SRS */ + oSRS.importFromEPSG( atoi(pszAuthorityCode) ); + + pszAuthorityName = oSRS.GetAuthorityName(NULL); + } + } + } +/* -------------------------------------------------------------------- */ +/* Check whether the EPSG authority code is already mapped to a */ +/* SRS ID. */ +/* -------------------------------------------------------------------- */ + if( pszAuthorityName != NULL && EQUAL( pszAuthorityName, "EPSG" ) ) + { + int nAuthorityCode; + + /* For the root authority name 'EPSG', the authority code + * should always be integral + */ + nAuthorityCode = atoi( oSRS.GetAuthorityCode(NULL) ); + + return nAuthorityCode; + } + + return 0; +} + +/************************************************************************/ +/* ICreateLayer() */ +/************************************************************************/ + +OGRLayer *OGRCARTODBDataSource::ICreateLayer( const char *pszNameIn, + OGRSpatialReference *poSpatialRef, + OGRwkbGeometryType eGType, + char ** papszOptions ) +{ + if (!bReadWrite) + { + CPLError(CE_Failure, CPLE_AppDefined, "Operation not available in read-only mode"); + return NULL; + } + +/* -------------------------------------------------------------------- */ +/* Do we already have this layer? If so, should we blow it */ +/* away? */ +/* -------------------------------------------------------------------- */ + int iLayer; + + for( iLayer = 0; iLayer < nLayers; iLayer++ ) + { + if( EQUAL(pszNameIn,papoLayers[iLayer]->GetName()) ) + { + if( CSLFetchNameValue( papszOptions, "OVERWRITE" ) != NULL + && !EQUAL(CSLFetchNameValue(papszOptions,"OVERWRITE"),"NO") ) + { + DeleteLayer( iLayer ); + } + else + { + CPLError( CE_Failure, CPLE_AppDefined, + "Layer %s already exists, CreateLayer failed.\n" + "Use the layer creation option OVERWRITE=YES to " + "replace it.", + pszNameIn ); + return NULL; + } + } + } + + CPLString osName(pszNameIn); + if( CSLFetchBoolean(papszOptions,"LAUNDER", TRUE) ) + { + char* pszTmp = OGRPGCommonLaunderName(pszNameIn); + osName = pszTmp; + CPLFree(pszTmp); + } + + + OGRCARTODBTableLayer* poLayer = new OGRCARTODBTableLayer(this, osName); + int bGeomNullable = CSLFetchBoolean(papszOptions, "GEOMETRY_NULLABLE", TRUE); + int nSRID = (poSpatialRef && eGType != wkbNone) ? FetchSRSId( poSpatialRef ) : 0; + int bCartoDBify = CSLFetchBoolean(papszOptions, "CARTODBFY", + CSLFetchBoolean(papszOptions, "CARTODBIFY", + TRUE)); + if( bCartoDBify ) + { + if( nSRID != 4326 ) + { + if( eGType != wkbNone ) + { + CPLError(CE_Warning, CPLE_AppDefined, + "Cannot register table in dashboard with " + "cdb_cartodbfytable() since its SRS is not EPSG:4326"); + } + bCartoDBify = FALSE; + } + } + + poLayer->SetLaunderFlag( CSLFetchBoolean(papszOptions,"LAUNDER",TRUE) ); + poLayer->SetDeferedCreation(eGType, poSpatialRef, bGeomNullable, bCartoDBify); + papoLayers = (OGRCARTODBTableLayer**) CPLRealloc( + papoLayers, (nLayers + 1) * sizeof(OGRCARTODBTableLayer*)); + papoLayers[nLayers ++] = poLayer; + + return poLayer; +} + +/************************************************************************/ +/* DeleteLayer() */ +/************************************************************************/ + +OGRErr OGRCARTODBDataSource::DeleteLayer(int iLayer) +{ + if (!bReadWrite) + { + CPLError(CE_Failure, CPLE_AppDefined, + "Operation not available in read-only mode"); + return OGRERR_FAILURE; + } + + if( iLayer < 0 || iLayer >= nLayers ) + { + CPLError( CE_Failure, CPLE_AppDefined, + "Layer %d not in legal range of 0 to %d.", + iLayer, nLayers-1 ); + return OGRERR_FAILURE; + } + +/* -------------------------------------------------------------------- */ +/* Blow away our OGR structures related to the layer. This is */ +/* pretty dangerous if anything has a reference to this layer! */ +/* -------------------------------------------------------------------- */ + CPLString osLayerName = papoLayers[iLayer]->GetLayerDefn()->GetName(); + + CPLDebug( "CARTODB", "DeleteLayer(%s)", osLayerName.c_str() ); + + int bDeferedCreation = papoLayers[iLayer]->GetDeferedCreation(); + papoLayers[iLayer]->CancelDeferedCreation(); + delete papoLayers[iLayer]; + memmove( papoLayers + iLayer, papoLayers + iLayer + 1, + sizeof(void *) * (nLayers - iLayer - 1) ); + nLayers--; + + if (osLayerName.size() == 0) + return OGRERR_NONE; + + if( !bDeferedCreation ) + { + CPLString osSQL; + osSQL.Printf("DROP TABLE %s", + OGRCARTODBEscapeIdentifier(osLayerName).c_str()); + + json_object* poObj = RunSQL(osSQL); + if( poObj == NULL ) + return OGRERR_FAILURE; + json_object_put(poObj); + } + + return OGRERR_NONE; +} + +/************************************************************************/ +/* AddHTTPOptions() */ +/************************************************************************/ + +char** OGRCARTODBDataSource::AddHTTPOptions() +{ + bMustCleanPersistant = TRUE; + + return CSLAddString(NULL, CPLSPrintf("PERSISTENT=CARTO:%p", this)); +} + +/************************************************************************/ +/* RunSQL() */ +/************************************************************************/ + +json_object* OGRCARTODBDataSource::RunSQL(const char* pszUnescapedSQL) +{ + CPLString osSQL("POSTFIELDS=q="); + /* Do post escaping */ + for(int i=0;pszUnescapedSQL[i] != 0;i++) + { + const int ch = ((unsigned char*)pszUnescapedSQL)[i]; + if (ch != '&' && ch >= 32 && ch < 128) + osSQL += (char)ch; + else + osSQL += CPLSPrintf("%%%02X", ch); + } + +/* -------------------------------------------------------------------- */ +/* Provide the API Key */ +/* -------------------------------------------------------------------- */ + if( osAPIKey.size() ) + { + osSQL += "&api_key="; + osSQL += osAPIKey; + } + +/* -------------------------------------------------------------------- */ +/* Collection the header options and execute request. */ +/* -------------------------------------------------------------------- */ + const char* pszAPIURL = GetAPIURL(); + char** papszOptions = CSLAddString( + !STARTS_WITH(pszAPIURL, "/vsimem/") ? AddHTTPOptions(): NULL, osSQL); + CPLHTTPResult * psResult = CPLHTTPFetch( GetAPIURL(), papszOptions); + CSLDestroy(papszOptions); + if( psResult == NULL ) + return NULL; + +/* -------------------------------------------------------------------- */ +/* Check for some error conditions and report. HTML Messages */ +/* are transformed info failure. */ +/* -------------------------------------------------------------------- */ + if (psResult->pszContentType && + STARTS_WITH(psResult->pszContentType, "text/html")) + { + CPLDebug( "CARTO", "RunSQL HTML Response:%s", psResult->pabyData ); + CPLError(CE_Failure, CPLE_AppDefined, + "HTML error page returned by server"); + CPLHTTPDestroyResult(psResult); + return NULL; + } + if (psResult->pszErrBuf != NULL) + { + CPLError(CE_Failure, CPLE_AppDefined, + "RunSQL Error Message:%s", psResult->pszErrBuf ); + } + else if (psResult->nStatus != 0) + { + CPLError(CE_Failure, CPLE_AppDefined, + "RunSQL Error Status:%d", psResult->nStatus ); + } + + if( psResult->pabyData == NULL ) + { + CPLHTTPDestroyResult(psResult); + return NULL; + } + + if( strlen((const char*)psResult->pabyData) < 1000 ) + CPLDebug( "CARTO", "RunSQL Response:%s", psResult->pabyData ); + + json_tokener* jstok = NULL; + json_object* poObj = NULL; + + jstok = json_tokener_new(); + poObj = json_tokener_parse_ex(jstok, (const char*) psResult->pabyData, -1); + if( jstok->err != json_tokener_success) + { + CPLError( CE_Failure, CPLE_AppDefined, + "JSON parsing error: %s (at offset %d)", + json_tokener_error_desc(jstok->err), jstok->char_offset); + json_tokener_free(jstok); + CPLHTTPDestroyResult(psResult); + return NULL; + } + json_tokener_free(jstok); + + CPLHTTPDestroyResult(psResult); + + if( poObj != NULL ) + { + if( json_object_get_type(poObj) == json_type_object ) + { + json_object* poError = json_object_object_get(poObj, "error"); + if( poError != NULL && json_object_get_type(poError) == json_type_array && + json_object_array_length(poError) > 0 ) + { + poError = json_object_array_get_idx(poError, 0); + if( poError != NULL && json_object_get_type(poError) == json_type_string ) + { + CPLError(CE_Failure, CPLE_AppDefined, + "Error returned by server : %s", json_object_get_string(poError)); + json_object_put(poObj); + return NULL; + } + } + } + else + { + json_object_put(poObj); + return NULL; + } + } + + return poObj; +} + +/************************************************************************/ +/* OGRCARTODBGetSingleRow() */ +/************************************************************************/ + +json_object* OGRCARTODBGetSingleRow(json_object* poObj) +{ + if( poObj == NULL ) + { + return NULL; + } + + json_object* poRows = json_object_object_get(poObj, "rows"); + if( poRows == NULL || + json_object_get_type(poRows) != json_type_array || + json_object_array_length(poRows) != 1 ) + { + return NULL; + } + + json_object* poRowObj = json_object_array_get_idx(poRows, 0); + if( poRowObj == NULL || json_object_get_type(poRowObj) != json_type_object ) + { + return NULL; + } + + return poRowObj; +} + +/************************************************************************/ +/* ExecuteSQL() */ +/************************************************************************/ + +OGRLayer * OGRCARTODBDataSource::ExecuteSQL( const char *pszSQLCommand, + OGRGeometry *poSpatialFilter, + const char *pszDialect ) + +{ + return ExecuteSQLInternal(pszSQLCommand, poSpatialFilter, pszDialect, + TRUE); +} + +OGRLayer * OGRCARTODBDataSource::ExecuteSQLInternal( const char *pszSQLCommand, + OGRGeometry *poSpatialFilter, + const char *pszDialect, + int bRunDeferedActions ) + +{ + if( bRunDeferedActions ) + { + for( int iLayer = 0; iLayer < nLayers; iLayer++ ) + { + papoLayers[iLayer]->RunDeferedCreationIfNecessary(); + CPL_IGNORE_RET_VAL(papoLayers[iLayer]->FlushDeferedInsert()); + papoLayers[iLayer]->RunDeferedCartoDBfy(); + } + } + + /* Skip leading spaces */ + while(*pszSQLCommand == ' ') + pszSQLCommand ++; + +/* -------------------------------------------------------------------- */ +/* Use generic implementation for recognized dialects */ +/* -------------------------------------------------------------------- */ + if( IsGenericSQLDialect(pszDialect) ) + return OGRDataSource::ExecuteSQL( pszSQLCommand, + poSpatialFilter, + pszDialect ); + +/* -------------------------------------------------------------------- */ +/* Special case DELLAYER: command. */ +/* -------------------------------------------------------------------- */ + if( STARTS_WITH_CI(pszSQLCommand, "DELLAYER:") ) + { + const char *pszLayerName = pszSQLCommand + 9; + + while( *pszLayerName == ' ' ) + pszLayerName++; + + for( int iLayer = 0; iLayer < nLayers; iLayer++ ) + { + if( EQUAL(papoLayers[iLayer]->GetName(), + pszLayerName )) + { + DeleteLayer( iLayer ); + break; + } + } + return NULL; + } + + if( !STARTS_WITH_CI(pszSQLCommand, "SELECT") && + !STARTS_WITH_CI(pszSQLCommand, "EXPLAIN") && + !STARTS_WITH_CI(pszSQLCommand, "WITH") ) + { + RunSQL(pszSQLCommand); + return NULL; + } + + OGRCARTODBResultLayer* poLayer = new OGRCARTODBResultLayer( this, pszSQLCommand ); + + if( poSpatialFilter != NULL ) + poLayer->SetSpatialFilter( poSpatialFilter ); + + if( !poLayer->IsOK() ) + { + delete poLayer; + return NULL; + } + + return poLayer; +} + +/************************************************************************/ +/* ReleaseResultSet() */ +/************************************************************************/ + +void OGRCARTODBDataSource::ReleaseResultSet( OGRLayer * poLayer ) + +{ + delete poLayer; +} diff --git a/BuildTools/CommonDistFiles/cartodb/ogrcartodbdatasource.obj b/BuildTools/CommonDistFiles/cartodb/ogrcartodbdatasource.obj new file mode 100644 index 000000000..7b1b5589c Binary files /dev/null and b/BuildTools/CommonDistFiles/cartodb/ogrcartodbdatasource.obj differ diff --git a/BuildTools/CommonDistFiles/cartodb/ogrcartodbdriver.cpp b/BuildTools/CommonDistFiles/cartodb/ogrcartodbdriver.cpp new file mode 100644 index 000000000..31c6c1b74 --- /dev/null +++ b/BuildTools/CommonDistFiles/cartodb/ogrcartodbdriver.cpp @@ -0,0 +1,143 @@ +/****************************************************************************** + * $Id$ + * + * Project: CartoDB Translator + * Purpose: Implements OGRCARTODBDriver. + * Author: Even Rouault, even dot rouault at mines dash paris dot org + * + ****************************************************************************** + * Copyright (c) 2013, Even Rouault + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + ****************************************************************************/ + +#include "ogr_cartodb.h" + +// g++ -g -Wall -fPIC -shared -o ogr_CARTODB.so -Iport -Igcore -Iogr -Iogr/ogrsf_frmts -Iogr/ogrsf_frmts/cartodb ogr/ogrsf_frmts/cartodb/*.c* -L. -lgdal -Iogr/ogrsf_frmts/geojson/libjson + +CPL_CVSID("$Id$"); + +extern "C" void RegisterOGRCartoDB(); + +/************************************************************************/ +/* OGRCartoDBDriverIdentify() */ +/************************************************************************/ + +static int OGRCartoDBDriverIdentify( GDALOpenInfo* poOpenInfo ) +{ + return STARTS_WITH_CI(poOpenInfo->pszFilename, "CARTO:"); +} + +/************************************************************************/ +/* OGRCartoDBDriverOpen() */ +/************************************************************************/ + +static GDALDataset *OGRCartoDBDriverOpen( GDALOpenInfo* poOpenInfo ) + +{ + if( !OGRCartoDBDriverIdentify(poOpenInfo) ) + return NULL; + + OGRCARTODBDataSource *poDS = new OGRCARTODBDataSource(); + + if( !poDS->Open( poOpenInfo->pszFilename, poOpenInfo->papszOpenOptions, + poOpenInfo->eAccess == GA_Update ) ) + { + delete poDS; + poDS = NULL; + } + + return poDS; +} + +/************************************************************************/ +/* OGRCartoDBDriverCreate() */ +/************************************************************************/ + +static GDALDataset *OGRCartoDBDriverCreate( const char * pszName, + CPL_UNUSED int nBands, + CPL_UNUSED int nXSize, + CPL_UNUSED int nYSize, + CPL_UNUSED GDALDataType eDT, + CPL_UNUSED char **papszOptions ) + +{ + OGRCARTODBDataSource *poDS = new OGRCARTODBDataSource(); + + if( !poDS->Open( pszName, NULL, TRUE ) ) + { + delete poDS; + CPLError( CE_Failure, CPLE_AppDefined, + "Carto driver doesn't support database creation." ); + return NULL; + } + + return poDS; +} + +/************************************************************************/ +/* RegisterOGRCARTODB() */ +/************************************************************************/ + +void RegisterOGRCartoDB() + +{ + if( GDALGetDriverByName( "Carto" ) != NULL ) + return; + + GDALDriver* poDriver = new GDALDriver(); + + poDriver->SetDescription( "Carto" ); + poDriver->SetMetadataItem( GDAL_DMD_LONGNAME, + "Carto" ); + poDriver->SetMetadataItem( GDAL_DCAP_VECTOR, "YES" ); + poDriver->SetMetadataItem( GDAL_DMD_HELPTOPIC, + "drv_cartodb.html" ); + + poDriver->SetMetadataItem( GDAL_DMD_CONNECTION_PREFIX, "CARTO:" ); + + poDriver->SetMetadataItem( GDAL_DMD_OPENOPTIONLIST, + "" + " "); + + poDriver->SetMetadataItem( GDAL_DMD_CREATIONOPTIONLIST, ""); + + poDriver->SetMetadataItem( GDAL_DS_LAYER_CREATIONOPTIONLIST, + "" + " "); + + poDriver->SetMetadataItem( GDAL_DMD_CREATIONFIELDDATATYPES, "Integer Integer64 Real String Date DateTime Time" ); + poDriver->SetMetadataItem( GDAL_DCAP_NOTNULL_FIELDS, "YES" ); + poDriver->SetMetadataItem( GDAL_DCAP_DEFAULT_FIELDS, "YES" ); + poDriver->SetMetadataItem( GDAL_DCAP_NOTNULL_GEOMFIELDS, "YES" ); + + poDriver->pfnOpen = OGRCartoDBDriverOpen; + poDriver->pfnIdentify = OGRCartoDBDriverIdentify; + poDriver->pfnCreate = OGRCartoDBDriverCreate; + + GetGDALDriverManager()->RegisterDriver( poDriver ); +} + diff --git a/BuildTools/CommonDistFiles/cartodb/ogrcartodbdriver.obj b/BuildTools/CommonDistFiles/cartodb/ogrcartodbdriver.obj new file mode 100644 index 000000000..04925328b Binary files /dev/null and b/BuildTools/CommonDistFiles/cartodb/ogrcartodbdriver.obj differ diff --git a/BuildTools/CommonDistFiles/cartodb/ogrcartodblayer.cpp b/BuildTools/CommonDistFiles/cartodb/ogrcartodblayer.cpp new file mode 100644 index 000000000..8ab664edb --- /dev/null +++ b/BuildTools/CommonDistFiles/cartodb/ogrcartodblayer.cpp @@ -0,0 +1,461 @@ +/****************************************************************************** + * $Id$ + * + * Project: CartoDB Translator + * Purpose: Implements OGRCARTODBLayer class. + * Author: Even Rouault, + * + ****************************************************************************** + * Copyright (c) 2013, Even Rouault + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + ****************************************************************************/ + +#include "ogr_cartodb.h" +#include "ogr_p.h" + +CPL_CVSID("$Id$"); + +/************************************************************************/ +/* OGRCARTODBLayer() */ +/************************************************************************/ + +OGRCARTODBLayer::OGRCARTODBLayer(OGRCARTODBDataSource* poDSIn) + +{ + this->poDS = poDSIn; + + poFeatureDefn = NULL; + + poCachedObj = NULL; + + ResetReading(); +} + +/************************************************************************/ +/* ~OGRCARTODBLayer() */ +/************************************************************************/ + +OGRCARTODBLayer::~OGRCARTODBLayer() + +{ + if( poCachedObj != NULL ) + json_object_put(poCachedObj); + + if( poFeatureDefn != NULL ) + poFeatureDefn->Release(); +} + +/************************************************************************/ +/* ResetReading() */ +/************************************************************************/ + +void OGRCARTODBLayer::ResetReading() + +{ + if( poCachedObj != NULL ) + json_object_put(poCachedObj); + poCachedObj = NULL; + bEOF = FALSE; + nFetchedObjects = -1; + iNextInFetchedObjects = 0; + iNext = 0; +} + +/************************************************************************/ +/* GetLayerDefn() */ +/************************************************************************/ + +OGRFeatureDefn * OGRCARTODBLayer::GetLayerDefn() +{ + return GetLayerDefnInternal(NULL); +} + +/************************************************************************/ +/* BuildFeature() */ +/************************************************************************/ + +OGRFeature *OGRCARTODBLayer::BuildFeature(json_object* poRowObj) +{ + OGRFeature* poFeature = NULL; + if( poRowObj != NULL && + json_object_get_type(poRowObj) == json_type_object ) + { + //CPLDebug("CartoDB", "Row: %s", json_object_to_json_string(poRowObj)); + poFeature = new OGRFeature(poFeatureDefn); + + if( osFIDColName.size() ) + { + json_object* poVal = json_object_object_get(poRowObj, osFIDColName); + if( poVal != NULL && + json_object_get_type(poVal) == json_type_int ) + { + poFeature->SetFID(json_object_get_int64(poVal)); + } + } + else + { + poFeature->SetFID(iNext); + } + + for(int i=0;iGetFieldCount();i++) + { + json_object* poVal = json_object_object_get(poRowObj, + poFeatureDefn->GetFieldDefn(i)->GetNameRef()); + if( poVal != NULL && + json_object_get_type(poVal) == json_type_string ) + { + if( poFeatureDefn->GetFieldDefn(i)->GetType() == OFTDateTime ) + { + OGRField sField; + if( OGRParseXMLDateTime( json_object_get_string(poVal), + &sField) ) + { + poFeature->SetField(i, &sField); + } + } + else + { + poFeature->SetField(i, json_object_get_string(poVal)); + } + } + else if( poVal != NULL && + (json_object_get_type(poVal) == json_type_int || + json_object_get_type(poVal) == json_type_boolean) ) + { + poFeature->SetField(i, (GIntBig)json_object_get_int64(poVal)); + } + else if( poVal != NULL && + json_object_get_type(poVal) == json_type_double ) + { + poFeature->SetField(i, json_object_get_double(poVal)); + } + } + + for(int i=0;iGetGeomFieldCount();i++) + { + OGRGeomFieldDefn* poGeomFldDefn = poFeatureDefn->GetGeomFieldDefn(i); + json_object* poVal = json_object_object_get(poRowObj, + poGeomFldDefn->GetNameRef()); + if( poVal != NULL && + json_object_get_type(poVal) == json_type_string ) + { + OGRGeometry* poGeom = OGRGeometryFromHexEWKB( + json_object_get_string(poVal), NULL, FALSE); + if( poGeom != NULL ) + poGeom->assignSpatialReference(poGeomFldDefn->GetSpatialRef()); + poFeature->SetGeomFieldDirectly(i, poGeom); + } + } + } + return poFeature; +} + +/************************************************************************/ +/* FetchNewFeatures() */ +/************************************************************************/ + +json_object* OGRCARTODBLayer::FetchNewFeatures(GIntBig iNextIn) +{ + CPLString osSQL = osBaseSQL; + if( osSQL.ifind("SELECT") != std::string::npos && + osSQL.ifind(" LIMIT ") == std::string::npos ) + { + osSQL += " LIMIT "; + osSQL += CPLSPrintf("%d", GetFeaturesToFetch()); + osSQL += " OFFSET "; + osSQL += CPLSPrintf(CPL_FRMT_GIB, iNextIn); + } + return poDS->RunSQL(osSQL); +} + +/************************************************************************/ +/* GetNextRawFeature() */ +/************************************************************************/ + +OGRFeature *OGRCARTODBLayer::GetNextRawFeature() +{ + if( bEOF ) + return NULL; + + if( iNextInFetchedObjects >= nFetchedObjects ) + { + if( nFetchedObjects > 0 && nFetchedObjects < GetFeaturesToFetch() ) + { + bEOF = TRUE; + return NULL; + } + + if( poFeatureDefn == NULL && osBaseSQL.size() == 0 ) + { + GetLayerDefn(); + } + + json_object* poObj = FetchNewFeatures(iNext); + if( poObj == NULL ) + { + bEOF = TRUE; + return NULL; + } + + if( poFeatureDefn == NULL ) + { + GetLayerDefnInternal(poObj); + } + + json_object* poRows = json_object_object_get(poObj, "rows"); + if( poRows == NULL || + json_object_get_type(poRows) != json_type_array || + json_object_array_length(poRows) == 0 ) + { + json_object_put(poObj); + bEOF = TRUE; + return NULL; + } + + if( poCachedObj != NULL ) + json_object_put(poCachedObj); + poCachedObj = poObj; + + nFetchedObjects = json_object_array_length(poRows); + iNextInFetchedObjects = 0; + } + + json_object* poRows = json_object_object_get(poCachedObj, "rows"); + json_object* poRowObj = json_object_array_get_idx(poRows, iNextInFetchedObjects); + + iNextInFetchedObjects ++; + + OGRFeature* poFeature = BuildFeature(poRowObj); + iNext = poFeature->GetFID() + 1; + + return poFeature; +} + +/************************************************************************/ +/* GetNextFeature() */ +/************************************************************************/ + +OGRFeature *OGRCARTODBLayer::GetNextFeature() +{ + OGRFeature *poFeature; + + while( true ) + { + poFeature = GetNextRawFeature(); + if (poFeature == NULL) + return NULL; + + if((m_poFilterGeom == NULL + || FilterGeometry( poFeature->GetGeometryRef() ) ) + && (m_poAttrQuery == NULL + || m_poAttrQuery->Evaluate( poFeature )) ) + { + return poFeature; + } + else + delete poFeature; + } +} + +/************************************************************************/ +/* TestCapability() */ +/************************************************************************/ + +int OGRCARTODBLayer::TestCapability( const char * pszCap ) + +{ + if ( EQUAL(pszCap, OLCStringsAsUTF8) ) + return TRUE; + return FALSE; +} + +/************************************************************************/ +/* EstablishLayerDefn() */ +/************************************************************************/ + +void OGRCARTODBLayer::EstablishLayerDefn(const char* pszLayerName, + json_object* poObjIn) +{ + poFeatureDefn = new OGRFeatureDefn(pszLayerName); + poFeatureDefn->Reference(); + poFeatureDefn->SetGeomType(wkbNone); + + CPLString osSQL; + size_t nPos = osBaseSQL.ifind(" LIMIT "); + if( nPos != std::string::npos ) + { + osSQL = osBaseSQL; + size_t nSize = osSQL.size(); + for(size_t i = nPos + strlen(" LIMIT "); i < nSize; i++) + { + if( osSQL[i] == ' ' ) + break; + osSQL[i] = '0'; + } + } + else + osSQL.Printf("%s LIMIT 0", osBaseSQL.c_str()); + json_object* poObj; + if( poObjIn != NULL ) + poObj = poObjIn; + else + { + poObj = poDS->RunSQL(osSQL); + if( poObj == NULL ) + { + return; + } + } + + json_object* poFields = json_object_object_get(poObj, "fields"); + if( poFields == NULL || json_object_get_type(poFields) != json_type_object) + { + if( poObjIn == NULL ) + json_object_put(poObj); + return; + } + + json_object_iter it; + it.key = NULL; + it.val = NULL; + it.entry = NULL; + json_object_object_foreachC( poFields, it ) + { + const char* pszColName = it.key; + if( it.val != NULL && json_object_get_type(it.val) == json_type_object) + { + json_object* poType = json_object_object_get(it.val, "type"); + if( poType != NULL && json_object_get_type(poType) == json_type_string ) + { + const char* pszType = json_object_get_string(poType); + CPLDebug("CARTO", "%s : %s", pszColName, pszType); + if( EQUAL(pszType, "string") || + EQUAL(pszType, "unknown(19)") /* name */ ) + { + OGRFieldDefn oFieldDefn(pszColName, OFTString); + poFeatureDefn->AddFieldDefn(&oFieldDefn); + } + else if( EQUAL(pszType, "number") ) + { + if( !EQUAL(pszColName, "cartodb_id") ) + { + OGRFieldDefn oFieldDefn(pszColName, OFTReal); + poFeatureDefn->AddFieldDefn(&oFieldDefn); + } + else + osFIDColName = pszColName; + } + else if( EQUAL(pszType, "date") ) + { + if( !EQUAL(pszColName, "created_at") && + !EQUAL(pszColName, "updated_at") ) + { + OGRFieldDefn oFieldDefn(pszColName, OFTDateTime); + poFeatureDefn->AddFieldDefn(&oFieldDefn); + } + } + else if( EQUAL(pszType, "geometry") ) + { + if( !EQUAL(pszColName, "the_geom_webmercator") ) + { + OGRCartoDBGeomFieldDefn *poFieldDefn = + new OGRCartoDBGeomFieldDefn(pszColName, wkbUnknown); + poFeatureDefn->AddGeomFieldDefn(poFieldDefn, FALSE); + OGRSpatialReference* l_poSRS = GetSRS(pszColName, &poFieldDefn->nSRID); + if( l_poSRS != NULL ) + { + poFeatureDefn->GetGeomFieldDefn( + poFeatureDefn->GetGeomFieldCount() - 1)->SetSpatialRef(l_poSRS); + l_poSRS->Release(); + } + } + } + else if( EQUAL(pszType, "boolean") ) + { + OGRFieldDefn oFieldDefn(pszColName, OFTInteger); + oFieldDefn.SetSubType(OFSTBoolean); + poFeatureDefn->AddFieldDefn(&oFieldDefn); + } + else + { + CPLDebug("CARTODB", "Unhandled type: %s. Defaulting to string", pszType); + OGRFieldDefn oFieldDefn(pszColName, OFTString); + poFeatureDefn->AddFieldDefn(&oFieldDefn); + } + } + else if( poType != NULL && json_object_get_type(poType) == json_type_int ) + { + /* FIXME? manual creations of geometry columns return integer types */ + OGRCartoDBGeomFieldDefn *poFieldDefn = + new OGRCartoDBGeomFieldDefn(pszColName, wkbUnknown); + poFeatureDefn->AddGeomFieldDefn(poFieldDefn, FALSE); + OGRSpatialReference* l_poSRS = GetSRS(pszColName, &poFieldDefn->nSRID); + if( l_poSRS != NULL ) + { + poFeatureDefn->GetGeomFieldDefn( + poFeatureDefn->GetGeomFieldCount() - 1)->SetSpatialRef(l_poSRS); + l_poSRS->Release(); + } + } + } + } + if( poObjIn == NULL ) + json_object_put(poObj); +} + +/************************************************************************/ +/* GetSRS() */ +/************************************************************************/ + +OGRSpatialReference* OGRCARTODBLayer::GetSRS(const char* pszGeomCol, + int *pnSRID) +{ + json_object* poObj = poDS->RunSQL(GetSRS_SQL(pszGeomCol)); + json_object* poRowObj = OGRCARTODBGetSingleRow(poObj); + if( poRowObj == NULL ) + { + if( poObj != NULL ) + json_object_put(poObj); + return NULL; + } + + json_object* poSRID = json_object_object_get(poRowObj, "srid"); + if( poSRID != NULL && json_object_get_type(poSRID) == json_type_int ) + { + *pnSRID = json_object_get_int(poSRID); + } + + json_object* poSRTEXT = json_object_object_get(poRowObj, "srtext"); + OGRSpatialReference* l_poSRS = NULL; + if( poSRTEXT != NULL && json_object_get_type(poSRTEXT) == json_type_string ) + { + const char* pszSRTEXT = json_object_get_string(poSRTEXT); + l_poSRS = new OGRSpatialReference(); + char* pszTmp = (char* )pszSRTEXT; + if( l_poSRS->importFromWkt(&pszTmp) != OGRERR_NONE ) + { + delete l_poSRS; + l_poSRS = NULL; + } + } + json_object_put(poObj); + + return l_poSRS; +} diff --git a/BuildTools/CommonDistFiles/cartodb/ogrcartodblayer.obj b/BuildTools/CommonDistFiles/cartodb/ogrcartodblayer.obj new file mode 100644 index 000000000..fea0c6016 Binary files /dev/null and b/BuildTools/CommonDistFiles/cartodb/ogrcartodblayer.obj differ diff --git a/BuildTools/CommonDistFiles/cartodb/ogrcartodbresultlayer.cpp b/BuildTools/CommonDistFiles/cartodb/ogrcartodbresultlayer.cpp new file mode 100644 index 000000000..90a3c1ed3 --- /dev/null +++ b/BuildTools/CommonDistFiles/cartodb/ogrcartodbresultlayer.cpp @@ -0,0 +1,133 @@ +/****************************************************************************** + * $Id + * + * Project: CartoDB Translator + * Purpose: Implements OGRCARTODBResultLayer class. + * Author: Even Rouault, + * + ****************************************************************************** + * Copyright (c) 2013, Even Rouault + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + ****************************************************************************/ + +#include "ogr_cartodb.h" + +CPL_CVSID("$Id"); + +/************************************************************************/ +/* OGRCARTODBResultLayer() */ +/************************************************************************/ + +OGRCARTODBResultLayer::OGRCARTODBResultLayer( OGRCARTODBDataSource* poDSIn, + const char * pszRawQueryIn ) : + OGRCARTODBLayer(poDSIn) +{ + osBaseSQL = pszRawQueryIn; + SetDescription( "result" ); + poFirstFeature = NULL; +} + +/************************************************************************/ +/* ~OGRCARTODBResultLayer() */ +/************************************************************************/ + +OGRCARTODBResultLayer::~OGRCARTODBResultLayer() + +{ + delete poFirstFeature; +} + +/************************************************************************/ +/* GetLayerDefnInternal() */ +/************************************************************************/ + +OGRFeatureDefn * OGRCARTODBResultLayer::GetLayerDefnInternal(json_object* poObjIn) +{ + if( poFeatureDefn != NULL ) + return poFeatureDefn; + + EstablishLayerDefn("result", poObjIn); + + return poFeatureDefn; +} + +/************************************************************************/ +/* GetNextRawFeature() */ +/************************************************************************/ + +OGRFeature *OGRCARTODBResultLayer::GetNextRawFeature() +{ + if( poFirstFeature ) + { + OGRFeature* poRet = poFirstFeature; + poFirstFeature = NULL; + return poRet; + } + else + return OGRCARTODBLayer::GetNextRawFeature(); +} + +/************************************************************************/ +/* IsOK() */ +/************************************************************************/ + +int OGRCARTODBResultLayer::IsOK() +{ + CPLErrorReset(); + poFirstFeature = GetNextFeature(); + return CPLGetLastErrorType() == 0; +} + +/************************************************************************/ +/* GetSRS_SQL() */ +/************************************************************************/ + +CPLString OGRCARTODBResultLayer::GetSRS_SQL(const char* pszGeomCol) +{ + CPLString osSQL; + CPLString osLimitedSQL; + + size_t nPos = osBaseSQL.ifind(" LIMIT "); + if( nPos != std::string::npos ) + { + osLimitedSQL = osBaseSQL; + size_t nSize = osLimitedSQL.size(); + for(size_t i = nPos + strlen(" LIMIT "); i < nSize; i++) + { + if( osLimitedSQL[i] == ' ' && osLimitedSQL[i-1] == '0') + { + osLimitedSQL[i-1] = '1'; + break; + } + osLimitedSQL[i] = '0'; + } + } + else + osLimitedSQL.Printf("%s LIMIT 1", osBaseSQL.c_str()); + + /* Assuming that the SRID of the first non-NULL geometry applies */ + /* to geometries of all rows. */ + osSQL.Printf("SELECT srid, srtext FROM spatial_ref_sys WHERE srid IN " + "(SELECT ST_SRID(%s) FROM (%s) ogr_subselect)", + OGRCARTODBEscapeIdentifier(pszGeomCol).c_str(), + osLimitedSQL.c_str()); + + return osSQL; +} diff --git a/BuildTools/CommonDistFiles/cartodb/ogrcartodbresultlayer.obj b/BuildTools/CommonDistFiles/cartodb/ogrcartodbresultlayer.obj new file mode 100644 index 000000000..a44fa1587 Binary files /dev/null and b/BuildTools/CommonDistFiles/cartodb/ogrcartodbresultlayer.obj differ diff --git a/BuildTools/CommonDistFiles/cartodb/ogrcartodbtablelayer.cpp b/BuildTools/CommonDistFiles/cartodb/ogrcartodbtablelayer.cpp new file mode 100644 index 000000000..c70a2b80c --- /dev/null +++ b/BuildTools/CommonDistFiles/cartodb/ogrcartodbtablelayer.cpp @@ -0,0 +1,1486 @@ +/****************************************************************************** + * $Id$ + * + * Project: CartoDB Translator + * Purpose: Implements OGRCARTODBTableLayer class. + * Author: Even Rouault, + * + ****************************************************************************** + * Copyright (c) 2013, Even Rouault + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + ****************************************************************************/ + +#include "ogr_cartodb.h" +#include "ogr_p.h" +#include "ogr_pgdump.h" + +CPL_CVSID("$Id$"); + +/************************************************************************/ +/* OGRCARTODBEscapeIdentifier( ) */ +/************************************************************************/ + +CPLString OGRCARTODBEscapeIdentifier(const char* pszStr) +{ + CPLString osStr; + + osStr += "\""; + + char ch; + for(int i=0; (ch = pszStr[i]) != '\0'; i++) + { + if (ch == '"') + osStr.append(1, ch); + osStr.append(1, ch); + } + + osStr += "\""; + + return osStr; +} + +/************************************************************************/ +/* OGRCARTODBEscapeLiteral( ) */ +/************************************************************************/ + +CPLString OGRCARTODBEscapeLiteral(const char* pszStr) +{ + CPLString osStr; + + char ch; + for(int i=0; (ch = pszStr[i]) != '\0'; i++) + { + if (ch == '\'') + osStr.append(1, ch); + osStr.append(1, ch); + } + + return osStr; +} + +/************************************************************************/ +/* OGRCARTODBTableLayer() */ +/************************************************************************/ + +OGRCARTODBTableLayer::OGRCARTODBTableLayer(OGRCARTODBDataSource* poDSIn, + const char* pszName) : + OGRCARTODBLayer(poDSIn) + +{ + osName = pszName; + SetDescription( osName ); + bLaunderColumnNames = TRUE; + bInDeferedInsert = poDS->DoBatchInsert(); + eDeferedInsertState = INSERT_UNINIT; + nNextFID = -1; + bDeferedCreation = FALSE; + bCartoDBify = FALSE; + nMaxChunkSize = atoi(CPLGetConfigOption("CARTODB_MAX_CHUNK_SIZE", "15")) * 1024 * 1024; +} + +/************************************************************************/ +/* ~OGRCARTODBTableLayer() */ +/************************************************************************/ + +OGRCARTODBTableLayer::~OGRCARTODBTableLayer() + +{ + if( bDeferedCreation ) RunDeferedCreationIfNecessary(); + CPL_IGNORE_RET_VAL(FlushDeferedInsert()); + RunDeferedCartoDBfy(); +} + +/************************************************************************/ +/* GetLayerDefnInternal() */ +/************************************************************************/ + +OGRFeatureDefn * OGRCARTODBTableLayer::GetLayerDefnInternal(CPL_UNUSED json_object* poObjIn) +{ + if( poFeatureDefn != NULL ) + return poFeatureDefn; + + CPLString osCommand; + if( poDS->IsAuthenticatedConnection() ) + { + // Get everything ! + osCommand.Printf( + "SELECT a.attname, t.typname, a.attlen, " + "format_type(a.atttypid,a.atttypmod), " + "a.attnum, " + "a.attnotnull, " + "i.indisprimary, " + "pg_get_expr(def.adbin, c.oid) AS defaultexpr, " + "postgis_typmod_dims(a.atttypmod) dim, " + "postgis_typmod_srid(a.atttypmod) srid, " + "postgis_typmod_type(a.atttypmod)::text geomtyp, " + "srtext " + "FROM pg_class c " + "JOIN pg_attribute a ON a.attnum > 0 AND " + "a.attrelid = c.oid AND c.relname = '%s' " + "JOIN pg_type t ON a.atttypid = t.oid " + "JOIN pg_namespace n ON c.relnamespace=n.oid AND n.nspname= '%s' " + "LEFT JOIN pg_index i ON c.oid = i.indrelid AND " + "i.indisprimary = 't' AND a.attnum = ANY(i.indkey) " + "LEFT JOIN pg_attrdef def ON def.adrelid = c.oid AND " + "def.adnum = a.attnum " + "LEFT JOIN spatial_ref_sys srs ON srs.srid = postgis_typmod_srid(a.atttypmod) " + "ORDER BY a.attnum", + OGRCARTODBEscapeLiteral(osName).c_str(), + OGRCARTODBEscapeLiteral(poDS->GetCurrentSchema()).c_str()); + } + else if( poDS->HasOGRMetadataFunction() != FALSE ) + { + osCommand.Printf( "SELECT * FROM ogr_table_metadata('%s', '%s')", + OGRCARTODBEscapeLiteral(poDS->GetCurrentSchema()).c_str(), + OGRCARTODBEscapeLiteral(osName).c_str() ); + } + + if( osCommand.size() ) + { + if( !poDS->IsAuthenticatedConnection() && poDS->HasOGRMetadataFunction() < 0 ) + CPLPushErrorHandler(CPLQuietErrorHandler); + OGRLayer* poLyr = poDS->ExecuteSQLInternal(osCommand); + if( !poDS->IsAuthenticatedConnection() && poDS->HasOGRMetadataFunction() < 0 ) + { + CPLPopErrorHandler(); + if( poLyr == NULL ) + { + CPLDebug("CARTODB", "ogr_table_metadata(text, text) not available"); + CPLErrorReset(); + } + else if( poLyr->GetLayerDefn()->GetFieldCount() != 12 ) + { + CPLDebug("CARTODB", "ogr_table_metadata(text, text) has unexpected column count"); + poDS->ReleaseResultSet(poLyr); + poLyr = NULL; + } + poDS->SetOGRMetadataFunction(poLyr != NULL); + } + if( poLyr ) + { + OGRFeature* poFeat; + while( (poFeat = poLyr->GetNextFeature()) != NULL ) + { + if( poFeatureDefn == NULL ) + { + // We could do that outside of the while() loop, but + // by doing that here, we are somewhat robust to + // ogr_table_metadata() returning suddenly an empty result set + // for example if CDB_UserTables() no longer works + poFeatureDefn = new OGRFeatureDefn(osName); + poFeatureDefn->Reference(); + poFeatureDefn->SetGeomType(wkbNone); + } + + const char* pszAttname = poFeat->GetFieldAsString("attname"); + const char* pszType = poFeat->GetFieldAsString("typname"); + int nWidth = poFeat->GetFieldAsInteger("attlen"); + const char* pszFormatType = poFeat->GetFieldAsString("format_type"); + int bNotNull = poFeat->GetFieldAsInteger("attnotnull"); + int bIsPrimary = poFeat->GetFieldAsInteger("indisprimary"); + int iDefaultExpr = poLyr->GetLayerDefn()->GetFieldIndex("defaultexpr"); + const char* pszDefault = (iDefaultExpr >= 0 && poFeat->IsFieldSet(iDefaultExpr)) ? + poFeat->GetFieldAsString(iDefaultExpr) : NULL; + + if( bIsPrimary && + (EQUAL(pszType, "int2") || + EQUAL(pszType, "int4") || + EQUAL(pszType, "int8") || + EQUAL(pszType, "serial") || + EQUAL(pszType, "bigserial")) ) + { + osFIDColName = pszAttname; + } + else if( strcmp(pszAttname, "created_at") == 0 || + strcmp(pszAttname, "updated_at") == 0 || + strcmp(pszAttname, "the_geom_webmercator") == 0) + { + /* ignored */ + } + else + { + if( EQUAL(pszType,"geometry") ) + { + int nDim = poFeat->GetFieldAsInteger("dim"); + int nSRID = poFeat->GetFieldAsInteger("srid"); + const char* pszGeomType = poFeat->GetFieldAsString("geomtyp"); + const char* pszSRText = (poFeat->IsFieldSet( + poLyr->GetLayerDefn()->GetFieldIndex("srtext"))) ? + poFeat->GetFieldAsString("srtext") : NULL; + OGRwkbGeometryType eType = OGRFromOGCGeomType(pszGeomType); + if( nDim == 3 ) + eType = wkbSetZ(eType); + OGRCartoDBGeomFieldDefn *poFieldDefn = + new OGRCartoDBGeomFieldDefn(pszAttname, eType); + if( bNotNull ) + poFieldDefn->SetNullable(FALSE); + OGRSpatialReference* l_poSRS = NULL; + if( pszSRText != NULL ) + { + l_poSRS = new OGRSpatialReference(); + char* pszTmp = (char* )pszSRText; + if( l_poSRS->importFromWkt(&pszTmp) != OGRERR_NONE ) + { + delete l_poSRS; + l_poSRS = NULL; + } + if( l_poSRS != NULL ) + { + poFieldDefn->SetSpatialRef(l_poSRS); + l_poSRS->Release(); + } + } + poFieldDefn->nSRID = nSRID; + poFeatureDefn->AddGeomFieldDefn(poFieldDefn, FALSE); + } + else + { + OGRFieldDefn oField(pszAttname, OFTString); + if( bNotNull ) + oField.SetNullable(FALSE); + OGRPGCommonLayerSetType(oField, pszType, pszFormatType, nWidth); + if( pszDefault ) + OGRPGCommonLayerNormalizeDefault(&oField, pszDefault); + + poFeatureDefn->AddFieldDefn( &oField ); + } + } + delete poFeat; + } + + poDS->ReleaseResultSet(poLyr); + } + } + + if( poFeatureDefn == NULL ) + { + osBaseSQL.Printf("SELECT * FROM %s", OGRCARTODBEscapeIdentifier(osName).c_str()); + EstablishLayerDefn(osName, NULL); + osBaseSQL = ""; + } + + if( osFIDColName.size() > 0 ) + { + osBaseSQL = "SELECT "; + osBaseSQL += OGRCARTODBEscapeIdentifier(osFIDColName); + } + for(int i=0; iGetGeomFieldCount(); i++) + { + if( osBaseSQL.size() == 0 ) + osBaseSQL = "SELECT "; + else + osBaseSQL += ", "; + osBaseSQL += OGRCARTODBEscapeIdentifier(poFeatureDefn->GetGeomFieldDefn(i)->GetNameRef()); + } + for(int i=0; iGetFieldCount(); i++) + { + if( osBaseSQL.size() == 0 ) + osBaseSQL = "SELECT "; + else + osBaseSQL += ", "; + osBaseSQL += OGRCARTODBEscapeIdentifier(poFeatureDefn->GetFieldDefn(i)->GetNameRef()); + } + if( osBaseSQL.size() == 0 ) + osBaseSQL = "SELECT *"; + osBaseSQL += " FROM "; + osBaseSQL += OGRCARTODBEscapeIdentifier(osName); + + osSELECTWithoutWHERE = osBaseSQL; + + return poFeatureDefn; +} + +/************************************************************************/ +/* FetchNewFeatures() */ +/************************************************************************/ + +json_object* OGRCARTODBTableLayer::FetchNewFeatures(GIntBig iNextIn) +{ + if( osFIDColName.size() > 0 ) + { + CPLString osSQL; + osSQL.Printf("%s WHERE %s%s >= " CPL_FRMT_GIB " ORDER BY %s ASC LIMIT %d", + osSELECTWithoutWHERE.c_str(), + ( osWHERE.size() ) ? CPLSPrintf("%s AND ", osWHERE.c_str()) : "", + OGRCARTODBEscapeIdentifier(osFIDColName).c_str(), + iNext, + OGRCARTODBEscapeIdentifier(osFIDColName).c_str(), + GetFeaturesToFetch()); + return poDS->RunSQL(osSQL); + } + else + return OGRCARTODBLayer::FetchNewFeatures(iNextIn); +} + +/************************************************************************/ +/* GetNextRawFeature() */ +/************************************************************************/ + +OGRFeature *OGRCARTODBTableLayer::GetNextRawFeature() +{ + if( bDeferedCreation && RunDeferedCreationIfNecessary() != OGRERR_NONE ) + return NULL; + if( FlushDeferedInsert() != OGRERR_NONE ) + return NULL; + return OGRCARTODBLayer::GetNextRawFeature(); +} + +/************************************************************************/ +/* SetAttributeFilter() */ +/************************************************************************/ + +OGRErr OGRCARTODBTableLayer::SetAttributeFilter( const char *pszQuery ) + +{ + GetLayerDefn(); + + if( pszQuery == NULL ) + osQuery = ""; + else + { + osQuery = "("; + osQuery += pszQuery; + osQuery += ")"; + } + + BuildWhere(); + + ResetReading(); + + return OGRERR_NONE; +} + +/************************************************************************/ +/* SetSpatialFilter() */ +/************************************************************************/ + +void OGRCARTODBTableLayer::SetSpatialFilter( int iGeomField, OGRGeometry * poGeomIn ) + +{ + if( iGeomField < 0 || iGeomField >= GetLayerDefn()->GetGeomFieldCount() || + GetLayerDefn()->GetGeomFieldDefn(iGeomField)->GetType() == wkbNone ) + { + if( iGeomField != 0 ) + { + CPLError(CE_Failure, CPLE_AppDefined, + "Invalid geometry field index : %d", iGeomField); + } + return; + } + m_iGeomFieldFilter = iGeomField; + + if( InstallFilter( poGeomIn ) ) + { + BuildWhere(); + + ResetReading(); + } +} + +/************************************************************************/ +/* RunDeferedCartoDBfy() */ +/************************************************************************/ + + +void OGRCARTODBTableLayer::RunDeferedCartoDBfy() + +{ + if( bCartoDBify ) + { + bCartoDBify = FALSE; + + CPLString osSQL; + if( poDS->GetCurrentSchema() == "public" ) + osSQL.Printf("SELECT cdb_cartodbfytable('%s')", + OGRCARTODBEscapeLiteral(osName).c_str()); + else + osSQL.Printf("SELECT cdb_cartodbfytable('%s', '%s')", + OGRCARTODBEscapeLiteral(poDS->GetCurrentSchema()).c_str(), + OGRCARTODBEscapeLiteral(osName).c_str()); + + json_object* poObj = poDS->RunSQL(osSQL); + if( poObj != NULL ) + json_object_put(poObj); + } +} + +/************************************************************************/ +/* FlushDeferedInsert() */ +/************************************************************************/ + +OGRErr OGRCARTODBTableLayer::FlushDeferedInsert(bool bReset) + +{ + OGRErr eErr = OGRERR_NONE; + if( bInDeferedInsert && osDeferedInsertSQL.size() > 0 ) + { + osDeferedInsertSQL = "BEGIN;" + osDeferedInsertSQL; + if( eDeferedInsertState == INSERT_MULTIPLE_FEATURE ) + { + osDeferedInsertSQL += ";"; + eDeferedInsertState = INSERT_UNINIT; + } + osDeferedInsertSQL += "COMMIT;"; + + json_object* poObj = poDS->RunSQL(osDeferedInsertSQL); + if( poObj != NULL ) + { + json_object_put(poObj); + } + else + { + bInDeferedInsert = FALSE; + eErr = OGRERR_FAILURE; + } + } + + osDeferedInsertSQL = ""; + if( bReset ) + { + bInDeferedInsert = FALSE; + nNextFID = -1; + } + return eErr; +} + +/************************************************************************/ +/* CreateField() */ +/************************************************************************/ + +OGRErr OGRCARTODBTableLayer::CreateField( OGRFieldDefn *poFieldIn, + CPL_UNUSED int bApproxOK ) +{ + GetLayerDefn(); + + if (!poDS->IsReadWrite()) + { + CPLError(CE_Failure, CPLE_AppDefined, + "Operation not available in read-only mode"); + return OGRERR_FAILURE; + } + + if( eDeferedInsertState == INSERT_MULTIPLE_FEATURE ) + { + if( FlushDeferedInsert() != OGRERR_NONE ) + return OGRERR_FAILURE; + } + + OGRFieldDefn oField(poFieldIn); + if( bLaunderColumnNames ) + { + char* pszName = OGRPGCommonLaunderName(oField.GetNameRef()); + oField.SetName(pszName); + CPLFree(pszName); + } + +/* -------------------------------------------------------------------- */ +/* Create the new field. */ +/* -------------------------------------------------------------------- */ + + if( !bDeferedCreation ) + { + CPLString osSQL; + osSQL.Printf( "ALTER TABLE %s ADD COLUMN %s %s", + OGRCARTODBEscapeIdentifier(osName).c_str(), + OGRCARTODBEscapeIdentifier(oField.GetNameRef()).c_str(), + OGRPGCommonLayerGetType(oField, FALSE, TRUE).c_str() ); + if( !oField.IsNullable() ) + osSQL += " NOT NULL"; + if( oField.GetDefault() != NULL && !oField.IsDefaultDriverSpecific() ) + { + osSQL += " DEFAULT "; + osSQL += OGRPGCommonLayerGetPGDefault(&oField); + } + + json_object* poObj = poDS->RunSQL(osSQL); + if( poObj == NULL ) + return OGRERR_FAILURE; + json_object_put(poObj); + } + + poFeatureDefn->AddFieldDefn( &oField ); + + return OGRERR_NONE; +} + +/************************************************************************/ +/* DeleteField() */ +/************************************************************************/ + +OGRErr OGRCARTODBTableLayer::DeleteField( int iField ) +{ + CPLString osSQL; + + if (!poDS->IsReadWrite()) + { + CPLError(CE_Failure, CPLE_AppDefined, + "Operation not available in read-only mode"); + return OGRERR_FAILURE; + } + + if (iField < 0 || iField >= poFeatureDefn->GetFieldCount()) + { + CPLError( CE_Failure, CPLE_NotSupported, + "Invalid field index"); + return OGRERR_FAILURE; + } + + if( eDeferedInsertState == INSERT_MULTIPLE_FEATURE ) + { + if( FlushDeferedInsert() != OGRERR_NONE ) + return OGRERR_FAILURE; + } + +/* -------------------------------------------------------------------- */ +/* Drop the field. */ +/* -------------------------------------------------------------------- */ + + osSQL.Printf( "ALTER TABLE %s DROP COLUMN %s", + OGRCARTODBEscapeIdentifier(osName).c_str(), + OGRCARTODBEscapeIdentifier(poFeatureDefn->GetFieldDefn(iField)->GetNameRef()).c_str() ); + + json_object* poObj = poDS->RunSQL(osSQL); + if( poObj == NULL ) + return OGRERR_FAILURE; + json_object_put(poObj); + + return poFeatureDefn->DeleteFieldDefn( iField ); +} + +/************************************************************************/ +/* ICreateFeature() */ +/************************************************************************/ + +OGRErr OGRCARTODBTableLayer::ICreateFeature( OGRFeature *poFeature ) + +{ + int i; + + if( bDeferedCreation ) + { + if( RunDeferedCreationIfNecessary() != OGRERR_NONE ) + return OGRERR_FAILURE; + } + + GetLayerDefn(); + int bHasUserFieldMatchingFID = FALSE; + if( osFIDColName.size() ) + bHasUserFieldMatchingFID = poFeatureDefn->GetFieldIndex(osFIDColName) >= 0; + + if (!poDS->IsReadWrite()) + { + CPLError(CE_Failure, CPLE_AppDefined, + "Operation not available in read-only mode"); + return OGRERR_FAILURE; + } + + CPLString osSQL; + + int bHasJustGotNextFID = FALSE; + if( !bHasUserFieldMatchingFID && bInDeferedInsert && nNextFID < 0 && osFIDColName.size() ) + { + osSQL.Printf("SELECT nextval('%s') AS nextid", + OGRCARTODBEscapeLiteral(CPLSPrintf("%s_%s_seq", osName.c_str(), osFIDColName.c_str())).c_str()); + + json_object* poObj = poDS->RunSQL(osSQL); + json_object* poRowObj = OGRCARTODBGetSingleRow(poObj); + if( poRowObj != NULL ) + { + json_object* poID = json_object_object_get(poRowObj, "nextid"); + if( poID != NULL && json_object_get_type(poID) == json_type_int ) + { + nNextFID = json_object_get_int64(poID); + bHasJustGotNextFID = TRUE; + } + } + + if( poObj != NULL ) + json_object_put(poObj); + } + + // Check if we can go on with multiple insertion mode + if( eDeferedInsertState == INSERT_MULTIPLE_FEATURE ) + { + if( !bHasUserFieldMatchingFID && osFIDColName.size() && + (poFeature->GetFID() != OGRNullFID || (nNextFID >= 0 && bHasJustGotNextFID)) ) + { + if( FlushDeferedInsert(false) != OGRERR_NONE ) + return OGRERR_FAILURE; + } + } + + bool bWriteInsertInto = (eDeferedInsertState != INSERT_MULTIPLE_FEATURE); + bool bResetToUninitInsertStateAfterwards = false; + if( eDeferedInsertState == INSERT_UNINIT ) + { + if( !bInDeferedInsert ) + { + eDeferedInsertState = INSERT_SINGLE_FEATURE; + } + else if( !bHasUserFieldMatchingFID && osFIDColName.size() && + (poFeature->GetFID() != OGRNullFID || (nNextFID >= 0 && bHasJustGotNextFID)) ) + { + eDeferedInsertState = INSERT_SINGLE_FEATURE; + bResetToUninitInsertStateAfterwards = true; + } + else + { + eDeferedInsertState = INSERT_MULTIPLE_FEATURE; + for(i = 0; i < poFeatureDefn->GetFieldCount(); i++) + { + if( poFeatureDefn->GetFieldDefn(i)->GetDefault() != NULL ) + eDeferedInsertState = INSERT_SINGLE_FEATURE; + } + } + } + + int bMustComma = FALSE; + if( bWriteInsertInto ) + { + osSQL.Printf("INSERT INTO %s ", OGRCARTODBEscapeIdentifier(osName).c_str()); + for(i = 0; i < poFeatureDefn->GetFieldCount(); i++) + { + if( eDeferedInsertState != INSERT_MULTIPLE_FEATURE && + !poFeature->IsFieldSet(i) ) + continue; + + if( bMustComma ) + osSQL += ", "; + else + { + osSQL += "("; + bMustComma = TRUE; + } + + osSQL += OGRCARTODBEscapeIdentifier(poFeatureDefn->GetFieldDefn(i)->GetNameRef()); + } + + for(i = 0; i < poFeatureDefn->GetGeomFieldCount(); i++) + { + if( eDeferedInsertState != INSERT_MULTIPLE_FEATURE && + poFeature->GetGeomFieldRef(i) == NULL ) + continue; + + if( bMustComma ) + osSQL += ", "; + else + { + osSQL += "("; + bMustComma = TRUE; + } + + osSQL += OGRCARTODBEscapeIdentifier(poFeatureDefn->GetGeomFieldDefn(i)->GetNameRef()); + } + + if( !bHasUserFieldMatchingFID && + osFIDColName.size() && (poFeature->GetFID() != OGRNullFID || (nNextFID >= 0 && bHasJustGotNextFID)) ) + { + if( bMustComma ) + osSQL += ", "; + else + { + osSQL += "("; + bMustComma = TRUE; + } + + osSQL += OGRCARTODBEscapeIdentifier(osFIDColName); + } + + if( !bMustComma && eDeferedInsertState == INSERT_MULTIPLE_FEATURE ) + eDeferedInsertState = INSERT_SINGLE_FEATURE; + } + + if( !bMustComma && eDeferedInsertState == INSERT_SINGLE_FEATURE ) + osSQL += "DEFAULT VALUES"; + else + { + if( !bWriteInsertInto && eDeferedInsertState == INSERT_MULTIPLE_FEATURE ) + osSQL += ", ("; + else + osSQL += ") VALUES ("; + + bMustComma = FALSE; + for(i = 0; i < poFeatureDefn->GetFieldCount(); i++) + { + if( !poFeature->IsFieldSet(i) ) + { + if( eDeferedInsertState == INSERT_MULTIPLE_FEATURE ) + { + if( bMustComma ) + osSQL += ", "; + else + bMustComma = TRUE; + osSQL += "NULL"; + } + continue; + } + + if( bMustComma ) + osSQL += ", "; + else + bMustComma = TRUE; + + OGRFieldType eType = poFeatureDefn->GetFieldDefn(i)->GetType(); + if( eType == OFTString || eType == OFTDateTime || eType == OFTDate || eType == OFTTime ) + { + osSQL += "'"; + osSQL += OGRCARTODBEscapeLiteral(poFeature->GetFieldAsString(i)); + osSQL += "'"; + } + else if( (eType == OFTInteger || eType == OFTInteger64) && + poFeatureDefn->GetFieldDefn(i)->GetSubType() == OFSTBoolean ) + { + osSQL += poFeature->GetFieldAsInteger(i) ? "'t'" : "'f'"; + } + else + osSQL += poFeature->GetFieldAsString(i); + } + + for(i = 0; i < poFeatureDefn->GetGeomFieldCount(); i++) + { + OGRGeometry* poGeom = poFeature->GetGeomFieldRef(i); + if( poGeom == NULL ) + { + if( eDeferedInsertState == INSERT_MULTIPLE_FEATURE ) + { + if( bMustComma ) + osSQL += ", "; + else + bMustComma = TRUE; + osSQL += "NULL"; + } + continue; + } + + if( bMustComma ) + osSQL += ", "; + else + bMustComma = TRUE; + + OGRCartoDBGeomFieldDefn* poGeomFieldDefn = + (OGRCartoDBGeomFieldDefn *)poFeatureDefn->GetGeomFieldDefn(i); + int nSRID = poGeomFieldDefn->nSRID; + if( nSRID == 0 ) + nSRID = 4326; + char* pszEWKB; + if( wkbFlatten(poGeom->getGeometryType()) == wkbPolygon && + wkbFlatten(GetGeomType()) == wkbMultiPolygon ) + { + OGRMultiPolygon* poNewGeom = new OGRMultiPolygon(); + poNewGeom->addGeometry(poGeom); + pszEWKB = OGRGeometryToHexEWKB(poNewGeom, nSRID, + poDS->GetPostGISMajor(), + poDS->GetPostGISMinor()); + delete poNewGeom; + } + else + pszEWKB = OGRGeometryToHexEWKB(poGeom, nSRID, + poDS->GetPostGISMajor(), + poDS->GetPostGISMinor()); + osSQL += "'"; + osSQL += pszEWKB; + osSQL += "'"; + CPLFree(pszEWKB); + } + + if( !bHasUserFieldMatchingFID ) + { + if( osFIDColName.size() && nNextFID >= 0 ) + { + if( bHasJustGotNextFID ) + { + if( bMustComma ) + osSQL += ", "; + else + bMustComma = TRUE; + + osSQL += CPLSPrintf(CPL_FRMT_GIB, nNextFID); + } + } + else if( osFIDColName.size() && poFeature->GetFID() != OGRNullFID ) + { + if( bMustComma ) + osSQL += ", "; + else + bMustComma = TRUE; + + osSQL += CPLSPrintf(CPL_FRMT_GIB, poFeature->GetFID()); + } + } + + osSQL += ")"; + } + + if( !bHasUserFieldMatchingFID && osFIDColName.size() && nNextFID >= 0 ) + { + poFeature->SetFID(nNextFID); + nNextFID ++; + } + + if( bInDeferedInsert ) + { + OGRErr eRet = OGRERR_NONE; + if( eDeferedInsertState == INSERT_SINGLE_FEATURE && /* in multiple mode, this would require rebuilding the osSQL buffer. Annoying... */ + osDeferedInsertSQL.size() != 0 && + (int)osDeferedInsertSQL.size() + (int)osSQL.size() > nMaxChunkSize ) + { + eRet = FlushDeferedInsert(false); + } + + osDeferedInsertSQL += osSQL; + if( eDeferedInsertState == INSERT_SINGLE_FEATURE ) + osDeferedInsertSQL += ";"; + + if( (int)osDeferedInsertSQL.size() > nMaxChunkSize ) + { + eRet = FlushDeferedInsert(false); + } + + if( bResetToUninitInsertStateAfterwards ) + eDeferedInsertState = INSERT_UNINIT; + + return eRet; + } + + if( osFIDColName.size() ) + { + osSQL += " RETURNING "; + osSQL += OGRCARTODBEscapeIdentifier(osFIDColName); + + json_object* poObj = poDS->RunSQL(osSQL); + json_object* poRowObj = OGRCARTODBGetSingleRow(poObj); + if( poRowObj == NULL ) + { + if( poObj != NULL ) + json_object_put(poObj); + return OGRERR_FAILURE; + } + + json_object* poID = json_object_object_get(poRowObj, osFIDColName); + if( poID != NULL && json_object_get_type(poID) == json_type_int ) + { + poFeature->SetFID(json_object_get_int64(poID)); + } + + if( poObj != NULL ) + json_object_put(poObj); + + return OGRERR_NONE; + } + else + { + OGRErr eRet = OGRERR_FAILURE; + json_object* poObj = poDS->RunSQL(osSQL); + if( poObj != NULL ) + { + json_object* poTotalRows = json_object_object_get(poObj, "total_rows"); + if( poTotalRows != NULL && json_object_get_type(poTotalRows) == json_type_int ) + { + int nTotalRows = json_object_get_int(poTotalRows); + if( nTotalRows == 1 ) + { + eRet = OGRERR_NONE; + } + } + json_object_put(poObj); + } + + return eRet; + } +} + +/************************************************************************/ +/* ISetFeature() */ +/************************************************************************/ + +OGRErr OGRCARTODBTableLayer::ISetFeature( OGRFeature *poFeature ) + +{ + int i; + + if( bDeferedCreation && RunDeferedCreationIfNecessary() != OGRERR_NONE ) + return OGRERR_FAILURE; + if( FlushDeferedInsert() != OGRERR_NONE ) + return OGRERR_FAILURE; + + GetLayerDefn(); + + if (!poDS->IsReadWrite()) + { + CPLError(CE_Failure, CPLE_AppDefined, + "Operation not available in read-only mode"); + return OGRERR_FAILURE; + } + + if (poFeature->GetFID() == OGRNullFID) + { + CPLError( CE_Failure, CPLE_AppDefined, + "FID required on features given to SetFeature()." ); + return OGRERR_FAILURE; + } + + CPLString osSQL; + osSQL.Printf("UPDATE %s SET ", OGRCARTODBEscapeIdentifier(osName).c_str()); + int bMustComma = FALSE; + for(i = 0; i < poFeatureDefn->GetFieldCount(); i++) + { + if( bMustComma ) + osSQL += ", "; + else + bMustComma = TRUE; + + osSQL += OGRCARTODBEscapeIdentifier(poFeatureDefn->GetFieldDefn(i)->GetNameRef()); + osSQL += " = "; + + if( !poFeature->IsFieldSet(i) ) + { + osSQL += "NULL"; + } + else + { + OGRFieldType eType = poFeatureDefn->GetFieldDefn(i)->GetType(); + if( eType == OFTString || eType == OFTDateTime || eType == OFTDate || eType == OFTTime ) + { + osSQL += "'"; + osSQL += OGRCARTODBEscapeLiteral(poFeature->GetFieldAsString(i)); + osSQL += "'"; + } + else if( (eType == OFTInteger || eType == OFTInteger64) && + poFeatureDefn->GetFieldDefn(i)->GetSubType() == OFSTBoolean ) + { + osSQL += poFeature->GetFieldAsInteger(i) ? "'t'" : "'f'"; + } + else + osSQL += poFeature->GetFieldAsString(i); + } + } + + for(i = 0; i < poFeatureDefn->GetGeomFieldCount(); i++) + { + if( bMustComma ) + osSQL += ", "; + else + bMustComma = TRUE; + + osSQL += OGRCARTODBEscapeIdentifier(poFeatureDefn->GetGeomFieldDefn(i)->GetNameRef()); + osSQL += " = "; + + OGRGeometry* poGeom = poFeature->GetGeomFieldRef(i); + if( poGeom == NULL ) + { + osSQL += "NULL"; + } + else + { + OGRCartoDBGeomFieldDefn* poGeomFieldDefn = + (OGRCartoDBGeomFieldDefn *)poFeatureDefn->GetGeomFieldDefn(i); + int nSRID = poGeomFieldDefn->nSRID; + if( nSRID == 0 ) + nSRID = 4326; + char* pszEWKB = OGRGeometryToHexEWKB(poGeom, nSRID, + poDS->GetPostGISMajor(), + poDS->GetPostGISMinor()); + osSQL += "'"; + osSQL += pszEWKB; + osSQL += "'"; + CPLFree(pszEWKB); + } + } + + osSQL += CPLSPrintf(" WHERE %s = " CPL_FRMT_GIB, + OGRCARTODBEscapeIdentifier(osFIDColName).c_str(), + poFeature->GetFID()); + + OGRErr eRet = OGRERR_FAILURE; + json_object* poObj = poDS->RunSQL(osSQL); + if( poObj != NULL ) + { + json_object* poTotalRows = json_object_object_get(poObj, "total_rows"); + if( poTotalRows != NULL && json_object_get_type(poTotalRows) == json_type_int ) + { + int nTotalRows = json_object_get_int(poTotalRows); + if( nTotalRows > 0 ) + { + eRet = OGRERR_NONE; + } + else + eRet = OGRERR_NON_EXISTING_FEATURE; + } + json_object_put(poObj); + } + + return eRet; +} + +/************************************************************************/ +/* DeleteFeature() */ +/************************************************************************/ + +OGRErr OGRCARTODBTableLayer::DeleteFeature( GIntBig nFID ) + +{ + + if( bDeferedCreation && RunDeferedCreationIfNecessary() != OGRERR_NONE ) + return OGRERR_FAILURE; + if( FlushDeferedInsert() != OGRERR_NONE ) + return OGRERR_FAILURE; + + GetLayerDefn(); + + if (!poDS->IsReadWrite()) + { + CPLError(CE_Failure, CPLE_AppDefined, + "Operation not available in read-only mode"); + return OGRERR_FAILURE; + } + + if( osFIDColName.size() == 0 ) + return OGRERR_FAILURE; + + CPLString osSQL; + osSQL.Printf("DELETE FROM %s WHERE %s = " CPL_FRMT_GIB, + OGRCARTODBEscapeIdentifier(osName).c_str(), + OGRCARTODBEscapeIdentifier(osFIDColName).c_str(), + nFID); + + OGRErr eRet = OGRERR_FAILURE; + json_object* poObj = poDS->RunSQL(osSQL); + if( poObj != NULL ) + { + json_object* poTotalRows = json_object_object_get(poObj, "total_rows"); + if( poTotalRows != NULL && json_object_get_type(poTotalRows) == json_type_int ) + { + int nTotalRows = json_object_get_int(poTotalRows); + if( nTotalRows > 0 ) + { + eRet = OGRERR_NONE; + } + else + eRet = OGRERR_NON_EXISTING_FEATURE; + } + json_object_put(poObj); + } + + return eRet; +} + +/************************************************************************/ +/* GetSRS_SQL() */ +/************************************************************************/ + +CPLString OGRCARTODBTableLayer::GetSRS_SQL(const char* pszGeomCol) +{ + CPLString osSQL; + + osSQL.Printf("SELECT srid, srtext FROM spatial_ref_sys WHERE srid IN " + "(SELECT Find_SRID('%s', '%s', '%s'))", + OGRCARTODBEscapeLiteral(poDS->GetCurrentSchema()).c_str(), + OGRCARTODBEscapeLiteral(osName).c_str(), + OGRCARTODBEscapeLiteral(pszGeomCol).c_str()); + + return osSQL; +} + +/************************************************************************/ +/* BuildWhere() */ +/* */ +/* Build the WHERE statement appropriate to the current set of */ +/* criteria (spatial and attribute queries). */ +/************************************************************************/ + +void OGRCARTODBTableLayer::BuildWhere() + +{ + osWHERE = ""; + + if( m_poFilterGeom != NULL && + m_iGeomFieldFilter >= 0 && + m_iGeomFieldFilter < poFeatureDefn->GetGeomFieldCount() ) + { + OGREnvelope sEnvelope; + + m_poFilterGeom->getEnvelope( &sEnvelope ); + + CPLString osGeomColumn(poFeatureDefn->GetGeomFieldDefn(m_iGeomFieldFilter)->GetNameRef()); + + char szBox3D_1[128]; + char szBox3D_2[128]; + char* pszComma; + + CPLsnprintf(szBox3D_1, sizeof(szBox3D_1), "%.18g %.18g", sEnvelope.MinX, sEnvelope.MinY); + while((pszComma = strchr(szBox3D_1, ',')) != NULL) + *pszComma = '.'; + CPLsnprintf(szBox3D_2, sizeof(szBox3D_2), "%.18g %.18g", sEnvelope.MaxX, sEnvelope.MaxY); + while((pszComma = strchr(szBox3D_2, ',')) != NULL) + *pszComma = '.'; + osWHERE.Printf("(%s && 'BOX3D(%s, %s)'::box3d)", + OGRCARTODBEscapeIdentifier(osGeomColumn).c_str(), + szBox3D_1, szBox3D_2 ); + } + + if( strlen(osQuery) > 0 ) + { + if( osWHERE.size() > 0 ) + osWHERE += " AND "; + osWHERE += osQuery; + } + + if( osFIDColName.size() == 0 ) + { + osBaseSQL = osSELECTWithoutWHERE; + if( osWHERE.size() ) + { + osBaseSQL += " WHERE "; + osBaseSQL += osWHERE; + } + } +} + +/************************************************************************/ +/* GetFeature() */ +/************************************************************************/ + +OGRFeature* OGRCARTODBTableLayer::GetFeature( GIntBig nFeatureId ) +{ + + if( bDeferedCreation && RunDeferedCreationIfNecessary() != OGRERR_NONE ) + return NULL; + if( FlushDeferedInsert() != OGRERR_NONE ) + return NULL; + + GetLayerDefn(); + + if( osFIDColName.size() == 0 ) + return OGRCARTODBLayer::GetFeature(nFeatureId); + + CPLString osSQL = osSELECTWithoutWHERE; + osSQL += " WHERE "; + osSQL += OGRCARTODBEscapeIdentifier(osFIDColName).c_str(); + osSQL += " = "; + osSQL += CPLSPrintf(CPL_FRMT_GIB, nFeatureId); + + json_object* poObj = poDS->RunSQL(osSQL); + json_object* poRowObj = OGRCARTODBGetSingleRow(poObj); + if( poRowObj == NULL ) + { + if( poObj != NULL ) + json_object_put(poObj); + return OGRCARTODBLayer::GetFeature(nFeatureId); + } + + OGRFeature* poFeature = BuildFeature(poRowObj); + json_object_put(poObj); + + return poFeature; +} + +/************************************************************************/ +/* GetFeatureCount() */ +/************************************************************************/ + +GIntBig OGRCARTODBTableLayer::GetFeatureCount(int bForce) +{ + + if( bDeferedCreation && RunDeferedCreationIfNecessary() != OGRERR_NONE ) + return 0; + if( FlushDeferedInsert() != OGRERR_NONE ) + return 0; + + GetLayerDefn(); + + CPLString osSQL(CPLSPrintf("SELECT COUNT(*) FROM %s", + OGRCARTODBEscapeIdentifier(osName).c_str())); + if( osWHERE.size() ) + { + osSQL += " WHERE "; + osSQL += osWHERE; + } + + json_object* poObj = poDS->RunSQL(osSQL); + json_object* poRowObj = OGRCARTODBGetSingleRow(poObj); + if( poRowObj == NULL ) + { + if( poObj != NULL ) + json_object_put(poObj); + return OGRCARTODBLayer::GetFeatureCount(bForce); + } + + json_object* poCount = json_object_object_get(poRowObj, "count"); + if( poCount == NULL || json_object_get_type(poCount) != json_type_int ) + { + json_object_put(poObj); + return OGRCARTODBLayer::GetFeatureCount(bForce); + } + + GIntBig nRet = (GIntBig)json_object_get_int64(poCount); + + json_object_put(poObj); + + return nRet; +} + +/************************************************************************/ +/* GetExtent() */ +/* */ +/* For PostGIS use internal Extend(geometry) function */ +/* in other cases we use standard OGRLayer::GetExtent() */ +/************************************************************************/ + +OGRErr OGRCARTODBTableLayer::GetExtent( int iGeomField, OGREnvelope *psExtent, int bForce ) +{ + CPLString osSQL; + + if( bDeferedCreation && RunDeferedCreationIfNecessary() != OGRERR_NONE ) + return OGRERR_FAILURE; + if( FlushDeferedInsert() != OGRERR_NONE ) + return OGRERR_FAILURE; + + if( iGeomField < 0 || iGeomField >= GetLayerDefn()->GetGeomFieldCount() || + GetLayerDefn()->GetGeomFieldDefn(iGeomField)->GetType() == wkbNone ) + { + if( iGeomField != 0 ) + { + CPLError(CE_Failure, CPLE_AppDefined, + "Invalid geometry field index : %d", iGeomField); + } + return OGRERR_FAILURE; + } + + OGRGeomFieldDefn* poGeomFieldDefn = + poFeatureDefn->GetGeomFieldDefn(iGeomField); + + /* Do not take the spatial filter into account */ + osSQL.Printf( "SELECT ST_Extent(%s) FROM %s", + OGRCARTODBEscapeIdentifier(poGeomFieldDefn->GetNameRef()).c_str(), + OGRCARTODBEscapeIdentifier(osName).c_str()); + + json_object* poObj = poDS->RunSQL(osSQL); + json_object* poRowObj = OGRCARTODBGetSingleRow(poObj); + if( poRowObj != NULL ) + { + json_object* poExtent = json_object_object_get(poRowObj, "st_extent"); + if( poExtent != NULL && json_object_get_type(poExtent) == json_type_string ) + { + const char* pszBox = json_object_get_string(poExtent); + const char * ptr, *ptrEndParenthesis; + char szVals[64*6+6]; + + ptr = strchr(pszBox, '('); + if (ptr) + ptr ++; + if (ptr == NULL || + (ptrEndParenthesis = strchr(ptr, ')')) == NULL || + ptrEndParenthesis - ptr > (int)(sizeof(szVals) - 1)) + { + CPLError( CE_Failure, CPLE_IllegalArg, + "Bad extent representation: '%s'", pszBox); + + json_object_put(poObj); + return OGRERR_FAILURE; + } + + strncpy(szVals,ptr,ptrEndParenthesis - ptr); + szVals[ptrEndParenthesis - ptr] = '\0'; + + char ** papszTokens = CSLTokenizeString2(szVals," ,",CSLT_HONOURSTRINGS); + int nTokenCnt = 4; + + if ( CSLCount(papszTokens) != nTokenCnt ) + { + CPLError( CE_Failure, CPLE_IllegalArg, + "Bad extent representation: '%s'", pszBox); + CSLDestroy(papszTokens); + + json_object_put(poObj); + return OGRERR_FAILURE; + } + + // Take X,Y coords + // For PostGIS ver >= 1.0.0 -> Tokens: X1 Y1 X2 Y2 (nTokenCnt = 4) + // For PostGIS ver < 1.0.0 -> Tokens: X1 Y1 Z1 X2 Y2 Z2 (nTokenCnt = 6) + // => X2 index calculated as nTokenCnt/2 + // Y2 index calculated as nTokenCnt/2+1 + + psExtent->MinX = CPLAtof( papszTokens[0] ); + psExtent->MinY = CPLAtof( papszTokens[1] ); + psExtent->MaxX = CPLAtof( papszTokens[nTokenCnt/2] ); + psExtent->MaxY = CPLAtof( papszTokens[nTokenCnt/2+1] ); + + CSLDestroy(papszTokens); + + json_object_put(poObj); + return OGRERR_NONE; + } + } + + if( poObj != NULL ) + json_object_put(poObj); + + if( iGeomField == 0 ) + return OGRLayer::GetExtent( psExtent, bForce ); + else + return OGRLayer::GetExtent( iGeomField, psExtent, bForce ); +} + +/************************************************************************/ +/* TestCapability() */ +/************************************************************************/ + +int OGRCARTODBTableLayer::TestCapability( const char * pszCap ) + +{ + if( EQUAL(pszCap, OLCFastFeatureCount) ) + return TRUE; + if( EQUAL(pszCap, OLCFastGetExtent) ) + return TRUE; + if( EQUAL(pszCap, OLCRandomRead) ) + { + GetLayerDefn(); + return osFIDColName.size() != 0; + } + + if( EQUAL(pszCap,OLCSequentialWrite) + || EQUAL(pszCap,OLCRandomWrite) + || EQUAL(pszCap,OLCDeleteFeature) + || EQUAL(pszCap,OLCCreateField) + || EQUAL(pszCap,OLCDeleteField) ) + { + return poDS->IsReadWrite(); + } + + return OGRCARTODBLayer::TestCapability(pszCap); +} + +/************************************************************************/ +/* SetDeferedCreation() */ +/************************************************************************/ + +void OGRCARTODBTableLayer::SetDeferedCreation (OGRwkbGeometryType eGType, + OGRSpatialReference* poSRSIn, + int bGeomNullable, + int bCartoDBifyIn) +{ + bDeferedCreation = TRUE; + nNextFID = 1; + CPLAssert(poFeatureDefn == NULL); + this->bCartoDBify = bCartoDBifyIn; + poFeatureDefn = new OGRFeatureDefn(osName); + poFeatureDefn->Reference(); + poFeatureDefn->SetGeomType(wkbNone); + if( eGType == wkbPolygon ) + eGType = wkbMultiPolygon; + else if( eGType == wkbPolygon25D ) + eGType = wkbMultiPolygon25D; + if( eGType != wkbNone ) + { + OGRCartoDBGeomFieldDefn *poFieldDefn = + new OGRCartoDBGeomFieldDefn("the_geom", eGType); + poFieldDefn->SetNullable(bGeomNullable); + poFeatureDefn->AddGeomFieldDefn(poFieldDefn, FALSE); + if( poSRSIn != NULL ) + { + poFieldDefn->nSRID = poDS->FetchSRSId( poSRSIn ); + poFeatureDefn->GetGeomFieldDefn( + poFeatureDefn->GetGeomFieldCount() - 1)->SetSpatialRef(poSRSIn); + } + } + osFIDColName = "cartodb_id"; + osBaseSQL.Printf("SELECT * FROM %s", + OGRCARTODBEscapeIdentifier(osName).c_str()); + osSELECTWithoutWHERE = osBaseSQL; +} + +/************************************************************************/ +/* RunDeferedCreationIfNecessary() */ +/************************************************************************/ + +OGRErr OGRCARTODBTableLayer::RunDeferedCreationIfNecessary() +{ + if( !bDeferedCreation ) + return OGRERR_NONE; + bDeferedCreation = FALSE; + + CPLString osSQL; + osSQL.Printf("CREATE TABLE %s ( %s SERIAL,", + OGRCARTODBEscapeIdentifier(osName).c_str(), + osFIDColName.c_str()); + + int nSRID = 0; + OGRwkbGeometryType eGType = GetGeomType(); + if( eGType != wkbNone ) + { + CPLString osGeomType = OGRToOGCGeomType(eGType); + if( wkbHasZ(eGType) ) + osGeomType += "Z"; + + OGRCartoDBGeomFieldDefn *poFieldDefn = + (OGRCartoDBGeomFieldDefn *)poFeatureDefn->GetGeomFieldDefn(0); + nSRID = poFieldDefn->nSRID; + + osSQL += CPLSPrintf("%s GEOMETRY(%s, %d)%s, %s GEOMETRY(%s, %d),", + "the_geom", + osGeomType.c_str(), + nSRID, + (!poFieldDefn->IsNullable()) ? " NOT NULL" : "", + "the_geom_webmercator", + osGeomType.c_str(), + 3857); + } + + for( int i = 0; i < poFeatureDefn->GetFieldCount(); i++ ) + { + OGRFieldDefn* poFieldDefn = poFeatureDefn->GetFieldDefn(i); + if( strcmp(poFieldDefn->GetNameRef(), osFIDColName) != 0 ) + { + osSQL += OGRCARTODBEscapeIdentifier(poFieldDefn->GetNameRef()); + osSQL += " "; + osSQL += OGRPGCommonLayerGetType(*poFieldDefn, FALSE, TRUE); + if( !poFieldDefn->IsNullable() ) + osSQL += " NOT NULL"; + if( poFieldDefn->GetDefault() != NULL && !poFieldDefn->IsDefaultDriverSpecific() ) + { + osSQL += " DEFAULT "; + osSQL += poFieldDefn->GetDefault(); + } + osSQL += ","; + } + } + + osSQL += CPLSPrintf("PRIMARY KEY (%s) )", osFIDColName.c_str()); + + CPLString osSeqName(OGRCARTODBEscapeIdentifier(CPLSPrintf("%s_%s_seq", + osName.c_str(), osFIDColName.c_str()))); + + osSQL += ";"; + osSQL += CPLSPrintf("DROP SEQUENCE IF EXISTS %s CASCADE", osSeqName.c_str()); + osSQL += ";"; + osSQL += CPLSPrintf("CREATE SEQUENCE %s START 1", osSeqName.c_str()); + osSQL += ";"; + osSQL += CPLSPrintf("ALTER TABLE %s ALTER COLUMN %s SET DEFAULT nextval('%s')", + OGRCARTODBEscapeIdentifier(osName).c_str(), + osFIDColName.c_str(), osSeqName.c_str()); + + json_object* poObj = poDS->RunSQL(osSQL); + if( poObj == NULL ) + return OGRERR_FAILURE; + json_object_put(poObj); + + return OGRERR_NONE; +} diff --git a/BuildTools/CommonDistFiles/cartodb/ogrcartodbtablelayer.obj b/BuildTools/CommonDistFiles/cartodb/ogrcartodbtablelayer.obj new file mode 100644 index 000000000..71ac49a7f Binary files /dev/null and b/BuildTools/CommonDistFiles/cartodb/ogrcartodbtablelayer.obj differ diff --git a/BuildTools/CommonDistFiles/menu.mm b/BuildTools/CommonDistFiles/menu.mm new file mode 100644 index 000000000..d73820a71 --- /dev/null +++ b/BuildTools/CommonDistFiles/menu.mm @@ -0,0 +1,299 @@ +///////////////////////////////////////////////////////////////////////////// +// Name: src/osx/cocoa/menu.mm +// Purpose: wxMenu, wxMenuBar, wxMenuItem +// Author: Stefan Csomor +// Modified by: +// Created: 1998-01-01 +// Copyright: (c) Stefan Csomor +// Licence: wxWindows licence +///////////////////////////////////////////////////////////////////////////// + +// ============================================================================ +// headers & declarations +// ============================================================================ + +// wxWidgets headers +// ----------------- + +#include "wx/wxprec.h" + +#ifndef WX_PRECOMP +#include "wx/log.h" +#include "wx/app.h" +#include "wx/utils.h" +#include "wx/frame.h" +#include "wx/menuitem.h" +#endif + +#include "wx/menu.h" + +#include "wx/osx/private.h" + +// other standard headers +// ---------------------- +#include + +@implementation wxNSMenu + +- (id) initWithTitle:(NSString*) title +{ + self = [super initWithTitle:title]; + impl = NULL; + return self; +} + +- (void)setImplementation: (wxMenuImpl *) theImplementation +{ + impl = theImplementation; +} + +- (wxMenuImpl*) implementation +{ + return impl; +} + +@end + +// this is more compatible, as it is also called for command-key shortcuts +// and under 10.4, we are not getting a 'close' event however... +#define wxOSX_USE_NEEDSUPDATE_HOOK 1 + +@interface wxNSMenuController : NSObject +{ +} + +#if wxOSX_USE_NEEDSUPDATE_HOOK +- (void)menuNeedsUpdate:(NSMenu*)smenu; +#else +- (void)menuWillOpen:(NSMenu *)menu; +#endif +- (void)menuDidClose:(NSMenu *)menu; +- (void)menu:(NSMenu *)menu willHighlightItem:(NSMenuItem *)item; + +@end + +@implementation wxNSMenuController + +- (id) init +{ + self = [super init]; + return self; +} + +#if wxOSX_USE_NEEDSUPDATE_HOOK +- (void)menuNeedsUpdate:(NSMenu*)smenu +{ + wxNSMenu* menu = (wxNSMenu*) smenu; + wxMenuImpl* menuimpl = [menu implementation]; + if ( menuimpl ) + { + wxMenu* wxpeer = (wxMenu*) menuimpl->GetWXPeer(); + if ( wxpeer ) + wxpeer->HandleMenuOpened(); + } +} +#else +- (void)menuWillOpen:(NSMenu *)smenu +{ + wxNSMenu* menu = (wxNSMenu*) smenu; + wxMenuImpl* menuimpl = [menu implementation]; + if ( menuimpl ) + { + wxMenu* wxpeer = (wxMenu*) menuimpl->GetWXPeer(); + if ( wxpeer ) + wxpeer->HandleMenuOpened(); + } +} +#endif + +- (void)menuDidClose:(NSMenu *)smenu +{ + wxNSMenu* menu = (wxNSMenu*) smenu; + wxMenuImpl* menuimpl = [menu implementation]; + if ( menuimpl ) + { + wxMenu* wxpeer = (wxMenu*) menuimpl->GetWXPeer(); + if ( wxpeer ) + wxpeer->HandleMenuClosed(); + } +} + +- (void)menu:(NSMenu *)smenu willHighlightItem:(NSMenuItem *)item +{ + wxNSMenu* menu = (wxNSMenu*) smenu; + wxMenuImpl* menuimpl = [menu implementation]; + if ( menuimpl ) + { + wxMenu* wxpeer = (wxMenu*) menuimpl->GetWXPeer(); + if ( [ item isKindOfClass:[wxNSMenuItem class] ] ) + { + wxMenuItemImpl* menuitemimpl = (wxMenuItemImpl*) [ (wxNSMenuItem*) item implementation ]; + if ( wxpeer && menuitemimpl ) + { + wxpeer->HandleMenuItemHighlighted( menuitemimpl->GetWXPeer() ); + } + } + } +} + +@end + +@interface NSApplication(MissingAppleMenuCall) +- (void)setAppleMenu:(NSMenu *)menu; +@end + +class wxMenuCocoaImpl : public wxMenuImpl +{ +public : + wxMenuCocoaImpl( wxMenu* peer , wxNSMenu* menu) : wxMenuImpl(peer), m_osxMenu(menu) + { + static wxNSMenuController* controller = NULL; + if ( controller == NULL ) + { + controller = [[wxNSMenuController alloc] init]; + } + [menu setDelegate:controller]; + [m_osxMenu setImplementation:this]; + // gc aware + if ( m_osxMenu ) + CFRetain(m_osxMenu); + [m_osxMenu release]; + } + + virtual ~wxMenuCocoaImpl(); + + virtual void InsertOrAppend(wxMenuItem *pItem, size_t pos) wxOVERRIDE + { + NSMenuItem* nsmenuitem = (NSMenuItem*) pItem->GetPeer()->GetHMenuItem(); + // make sure a call of SetSubMenu is also reflected (occurring after Create) + // update the native menu item accordingly + + if ( pItem->IsSubMenu() ) + { + wxMenu* wxsubmenu = pItem->GetSubMenu(); + WXHMENU nssubmenu = wxsubmenu->GetHMenu(); + if ( [nsmenuitem submenu] != nssubmenu ) + { + wxsubmenu->GetPeer()->SetTitle( pItem->GetItemLabelText() ); + [nsmenuitem setSubmenu:nssubmenu]; + } + } + + if ( pos == (size_t) -1 ) + [m_osxMenu addItem:nsmenuitem ]; + else + [m_osxMenu insertItem:nsmenuitem atIndex:pos]; + } + + virtual void Remove( wxMenuItem *pItem ) wxOVERRIDE + { + [m_osxMenu removeItem:(NSMenuItem*) pItem->GetPeer()->GetHMenuItem()]; + } + + virtual void MakeRoot() wxOVERRIDE + { + wxMenu* peer = GetWXPeer(); + + [NSApp setMainMenu:m_osxMenu]; + [NSApp setAppleMenu:[[m_osxMenu itemAtIndex:0] submenu]]; + + wxMenuItem *services = peer->FindItem(wxID_OSX_SERVICES); + if ( services ) + [NSApp setServicesMenu:services->GetSubMenu()->GetHMenu()]; +#if 0 + // should we reset this just to be sure we don't leave a dangling ref ? + else + [NSApp setServicesMenu:nil]; +#endif + + NSMenu* helpMenu = nil; + int helpid = peer->FindItem(wxApp::s_macHelpMenuTitleName); + if ( helpid == wxNOT_FOUND ) + helpid = peer->FindItem(_("&Help")); + + if ( helpid != wxNOT_FOUND ) + { + wxMenuItem* helpMenuItem = peer->FindItem(helpid); + + if ( helpMenuItem->IsSubMenu() ) + helpMenu = helpMenuItem->GetSubMenu()->GetHMenu(); + } + if ( [NSApp respondsToSelector:@selector(setHelpMenu:)]) + [NSApp setHelpMenu:helpMenu]; + + } + + virtual void Enable( bool WXUNUSED(enable) ) + { + } + + virtual void SetTitle( const wxString& text ) wxOVERRIDE + { + wxCFStringRef cfText(text); + [m_osxMenu setTitle:cfText.AsNSString()]; + } + + virtual void PopUp( wxWindow *win, int x, int y ) wxOVERRIDE + { + NSView *view = win->GetPeer()->GetWXWidget(); + + wxPoint screenPoint(x,y); + NSPoint pointInView = wxToNSPoint(view, win->ScreenToClient( screenPoint )); + + // action and validation methods are not called from macos for modal dialogs + // when using popUpMenuPositioningItem therefore we fall back to the older method + // we don't want plug-ins interfering + m_osxMenu.allowsContextMenuPlugIns = NO; + + wxTopLevelWindow* tlw = static_cast(wxGetTopLevelParent(win)); + NSWindow* nsWindow = tlw->GetWXWindow(); + NSRect nsrect = NSZeroRect; + nsrect.origin = wxToNSPoint( NULL, screenPoint ); + nsrect = [nsWindow convertRectFromScreen:nsrect]; + + NSEvent* rightClick = [NSEvent mouseEventWithType:NSRightMouseDown + location:nsrect.origin + modifierFlags:0 + timestamp:0 + windowNumber:[nsWindow windowNumber] + context:nil + eventNumber:0 + clickCount:1 + pressure:0]; + + [NSMenu popUpContextMenu:m_osxMenu withEvent:rightClick forView:view]; + } + + virtual void GetMenuBarDimensions(int &x, int &y, int &width, int &height) const wxOVERRIDE + { + NSRect r = [(NSScreen*)[[NSScreen screens] objectAtIndex:0] frame]; + height = [m_osxMenu menuBarHeight]; + x = r.origin.x; + y = r.origin.y; + width = r.size.width; + } + + WXHMENU GetHMenu() wxOVERRIDE { return m_osxMenu; } + + static wxMenuImpl* Create( wxMenu* peer, const wxString& title ); + static wxMenuImpl* CreateRootMenu( wxMenu* peer ); +protected : + wxNSMenu* m_osxMenu; +} ; + +wxMenuCocoaImpl::~wxMenuCocoaImpl() +{ + [m_osxMenu setDelegate:nil]; + [m_osxMenu setImplementation:nil]; + // gc aware + if ( m_osxMenu ) + CFRelease(m_osxMenu); +} + +wxMenuImpl* wxMenuImpl::Create( wxMenu* peer, const wxString& title ) +{ + wxCFStringRef cfText( title ); + wxNSMenu* menu = [[wxNSMenu alloc] initWithTitle:cfText.AsNSString()]; + wxMenuImpl* c = new wxMenuCocoaImpl( peer, menu ); + return c; +} diff --git a/BuildTools/CommonDistFiles/web_plugins/d3/LICENSE b/BuildTools/CommonDistFiles/web_plugins/d3/LICENSE deleted file mode 100644 index 83013469b..000000000 --- a/BuildTools/CommonDistFiles/web_plugins/d3/LICENSE +++ /dev/null @@ -1,26 +0,0 @@ -Copyright (c) 2010-2014, Michael Bostock -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -* Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. - -* Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -* The name Michael Bostock may not be used to endorse or promote products - derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL MICHAEL BOSTOCK BE LIABLE FOR ANY DIRECT, -INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, -BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY -OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, -EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/BuildTools/CommonDistFiles/web_plugins/d3/d3.hexbin.v0.js b/BuildTools/CommonDistFiles/web_plugins/d3/d3.hexbin.v0.js deleted file mode 100644 index 8076834af..000000000 --- a/BuildTools/CommonDistFiles/web_plugins/d3/d3.hexbin.v0.js +++ /dev/null @@ -1,110 +0,0 @@ -(function() { - -d3.hexbin = function() { - var width = 1, - height = 1, - r, - x = d3_hexbinX, - y = d3_hexbinY, - dx, - dy; - - function hexbin(points) { - var binsById = {}; - - points.forEach(function(point, i) { - var py = y.call(hexbin, point, i) / dy, pj = Math.round(py), - px = x.call(hexbin, point, i) / dx - (pj & 1 ? .5 : 0), pi = Math.round(px), - py1 = py - pj; - - if (Math.abs(py1) * 3 > 1) { - var px1 = px - pi, - pi2 = pi + (px < pi ? -1 : 1) / 2, - pj2 = pj + (py < pj ? -1 : 1), - px2 = px - pi2, - py2 = py - pj2; - if (px1 * px1 + py1 * py1 > px2 * px2 + py2 * py2) pi = pi2 + (pj & 1 ? 1 : -1) / 2, pj = pj2; - } - - var id = pi + "-" + pj, bin = binsById[id]; - if (bin) bin.push(point); else { - bin = binsById[id] = [point]; - bin.i = pi; - bin.j = pj; - bin.x = (pi + (pj & 1 ? 1 / 2 : 0)) * dx; - bin.y = pj * dy; - } - }); - - return d3.values(binsById); - } - - function hexagon(radius) { - var x0 = 0, y0 = 0; - return d3_hexbinAngles.map(function(angle) { - var x1 = Math.sin(angle) * radius, - y1 = -Math.cos(angle) * radius, - dx = x1 - x0, - dy = y1 - y0; - x0 = x1, y0 = y1; - return [dx, dy]; - }); - } - - hexbin.x = function(_) { - if (!arguments.length) return x; - x = _; - return hexbin; - }; - - hexbin.y = function(_) { - if (!arguments.length) return y; - y = _; - return hexbin; - }; - - hexbin.hexagon = function(radius) { - if (arguments.length < 1) radius = r; - return "m" + hexagon(radius).join("l") + "z"; - }; - - hexbin.centers = function() { - var centers = []; - for (var y = 0, odd = false, j = 0; y < height + r; y += dy, odd = !odd, ++j) { - for (var x = odd ? dx / 2 : 0, i = 0; x < width + dx / 2; x += dx, ++i) { - var center = [x, y]; - center.i = i; - center.j = j; - centers.push(center); - } - } - return centers; - }; - - hexbin.mesh = function() { - var fragment = hexagon(r).slice(0, 4).join("l"); - return hexbin.centers().map(function(p) { return "M" + p + "m" + fragment; }).join(""); - }; - - hexbin.size = function(_) { - if (!arguments.length) return [width, height]; - width = +_[0], height = +_[1]; - return hexbin; - }; - - hexbin.radius = function(_) { - if (!arguments.length) return r; - r = +_; - dx = r * 2 * Math.sin(Math.PI / 3); - dy = r * 1.5; - return hexbin; - }; - - return hexbin.radius(1); -}; - -var d3_hexbinAngles = d3.range(0, 2 * Math.PI, Math.PI / 3), - d3_hexbinX = function(d) { return d[0]; }, - d3_hexbinY = function(d) { return d[1]; }; - -})(); diff --git a/BuildTools/CommonDistFiles/web_plugins/d3/d3.hexbin.v0.min.js b/BuildTools/CommonDistFiles/web_plugins/d3/d3.hexbin.v0.min.js deleted file mode 100644 index 97e0ca647..000000000 --- a/BuildTools/CommonDistFiles/web_plugins/d3/d3.hexbin.v0.min.js +++ /dev/null @@ -1 +0,0 @@ -!function(){d3.hexbin=function(){function u(n){var r={};return n.forEach(function(n,t){var a=s.call(u,n,t)/o,e=Math.round(a),c=h.call(u,n,t)/i-(1&e?.5:0),f=Math.round(c),l=a-e;if(3*Math.abs(l)>1){var v=c-f,g=f+(f>c?-1:1)/2,m=e+(e>a?-1:1),M=c-g,d=a-m;v*v+l*l>M*M+d*d&&(f=g+(1&e?1:-1)/2,e=m)}var j=f+"-"+e,p=r[j];p?p.push(n):(p=r[j]=[n],p.i=f,p.j=e,p.x=(f+(1&e?.5:0))*i,p.y=e*o)}),d3.values(r)}function a(r){var t=0,u=0;return n.map(function(n){var a=Math.sin(n)*r,e=-Math.cos(n)*r,i=a-t,o=e-u;return t=a,u=e,[i,o]})}var e,i,o,c=1,f=1,h=r,s=t;return u.x=function(n){return arguments.length?(h=n,u):h},u.y=function(n){return arguments.length?(s=n,u):s},u.hexagon=function(n){return arguments.length<1&&(n=e),"m"+a(n).join("l")+"z"},u.centers=function(){for(var n=[],r=0,t=!1,u=0;f+e>r;r+=o,t=!t,++u)for(var a=t?i/2:0,h=0;c+i/2>a;a+=i,++h){var s=[a,r];s.i=h,s.j=u,n.push(s)}return n},u.mesh=function(){var n=a(e).slice(0,4).join("l");return u.centers().map(function(r){return"M"+r+"m"+n}).join("")},u.size=function(n){return arguments.length?(c=+n[0],f=+n[1],u):[c,f]},u.radius=function(n){return arguments.length?(e=+n,i=2*e*Math.sin(Math.PI/3),o=1.5*e,u):e},u.radius(1)};var n=d3.range(0,2*Math.PI,Math.PI/3),r=function(n){return n[0]},t=function(n){return n[1]}}(); \ No newline at end of file diff --git a/BuildTools/CommonDistFiles/web_plugins/d3/d3.js b/BuildTools/CommonDistFiles/web_plugins/d3/d3.js deleted file mode 100644 index b96992772..000000000 --- a/BuildTools/CommonDistFiles/web_plugins/d3/d3.js +++ /dev/null @@ -1,9238 +0,0 @@ -!function() { - var d3 = { - version: "3.4.12" - }; - if (!Date.now) Date.now = function() { - return +new Date(); - }; - var d3_arraySlice = [].slice, d3_array = function(list) { - return d3_arraySlice.call(list); - }; - var d3_document = document, d3_documentElement = d3_document.documentElement, d3_window = window; - try { - d3_array(d3_documentElement.childNodes)[0].nodeType; - } catch (e) { - d3_array = function(list) { - var i = list.length, array = new Array(i); - while (i--) array[i] = list[i]; - return array; - }; - } - try { - d3_document.createElement("div").style.setProperty("opacity", 0, ""); - } catch (error) { - var d3_element_prototype = d3_window.Element.prototype, d3_element_setAttribute = d3_element_prototype.setAttribute, d3_element_setAttributeNS = d3_element_prototype.setAttributeNS, d3_style_prototype = d3_window.CSSStyleDeclaration.prototype, d3_style_setProperty = d3_style_prototype.setProperty; - d3_element_prototype.setAttribute = function(name, value) { - d3_element_setAttribute.call(this, name, value + ""); - }; - d3_element_prototype.setAttributeNS = function(space, local, value) { - d3_element_setAttributeNS.call(this, space, local, value + ""); - }; - d3_style_prototype.setProperty = function(name, value, priority) { - d3_style_setProperty.call(this, name, value + "", priority); - }; - } - d3.ascending = d3_ascending; - function d3_ascending(a, b) { - return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN; - } - d3.descending = function(a, b) { - return b < a ? -1 : b > a ? 1 : b >= a ? 0 : NaN; - }; - d3.min = function(array, f) { - var i = -1, n = array.length, a, b; - if (arguments.length === 1) { - while (++i < n && !((a = array[i]) != null && a <= a)) a = undefined; - while (++i < n) if ((b = array[i]) != null && a > b) a = b; - } else { - while (++i < n && !((a = f.call(array, array[i], i)) != null && a <= a)) a = undefined; - while (++i < n) if ((b = f.call(array, array[i], i)) != null && a > b) a = b; - } - return a; - }; - d3.max = function(array, f) { - var i = -1, n = array.length, a, b; - if (arguments.length === 1) { - while (++i < n && !((a = array[i]) != null && a <= a)) a = undefined; - while (++i < n) if ((b = array[i]) != null && b > a) a = b; - } else { - while (++i < n && !((a = f.call(array, array[i], i)) != null && a <= a)) a = undefined; - while (++i < n) if ((b = f.call(array, array[i], i)) != null && b > a) a = b; - } - return a; - }; - d3.extent = function(array, f) { - var i = -1, n = array.length, a, b, c; - if (arguments.length === 1) { - while (++i < n && !((a = c = array[i]) != null && a <= a)) a = c = undefined; - while (++i < n) if ((b = array[i]) != null) { - if (a > b) a = b; - if (c < b) c = b; - } - } else { - while (++i < n && !((a = c = f.call(array, array[i], i)) != null && a <= a)) a = undefined; - while (++i < n) if ((b = f.call(array, array[i], i)) != null) { - if (a > b) a = b; - if (c < b) c = b; - } - } - return [ a, c ]; - }; - d3.sum = function(array, f) { - var s = 0, n = array.length, a, i = -1; - if (arguments.length === 1) { - while (++i < n) if (!isNaN(a = +array[i])) s += a; - } else { - while (++i < n) if (!isNaN(a = +f.call(array, array[i], i))) s += a; - } - return s; - }; - function d3_number(x) { - return x != null && !isNaN(x); - } - d3.mean = function(array, f) { - var s = 0, n = array.length, a, i = -1, j = n; - if (arguments.length === 1) { - while (++i < n) if (d3_number(a = array[i])) s += a; else --j; - } else { - while (++i < n) if (d3_number(a = f.call(array, array[i], i))) s += a; else --j; - } - return j ? s / j : undefined; - }; - d3.quantile = function(values, p) { - var H = (values.length - 1) * p + 1, h = Math.floor(H), v = +values[h - 1], e = H - h; - return e ? v + e * (values[h] - v) : v; - }; - d3.median = function(array, f) { - if (arguments.length > 1) array = array.map(f); - array = array.filter(d3_number); - return array.length ? d3.quantile(array.sort(d3_ascending), .5) : undefined; - }; - function d3_bisector(compare) { - return { - left: function(a, x, lo, hi) { - if (arguments.length < 3) lo = 0; - if (arguments.length < 4) hi = a.length; - while (lo < hi) { - var mid = lo + hi >>> 1; - if (compare(a[mid], x) < 0) lo = mid + 1; else hi = mid; - } - return lo; - }, - right: function(a, x, lo, hi) { - if (arguments.length < 3) lo = 0; - if (arguments.length < 4) hi = a.length; - while (lo < hi) { - var mid = lo + hi >>> 1; - if (compare(a[mid], x) > 0) hi = mid; else lo = mid + 1; - } - return lo; - } - }; - } - var d3_bisect = d3_bisector(d3_ascending); - d3.bisectLeft = d3_bisect.left; - d3.bisect = d3.bisectRight = d3_bisect.right; - d3.bisector = function(f) { - return d3_bisector(f.length === 1 ? function(d, x) { - return d3_ascending(f(d), x); - } : f); - }; - d3.shuffle = function(array) { - var m = array.length, t, i; - while (m) { - i = Math.random() * m-- | 0; - t = array[m], array[m] = array[i], array[i] = t; - } - return array; - }; - d3.permute = function(array, indexes) { - var i = indexes.length, permutes = new Array(i); - while (i--) permutes[i] = array[indexes[i]]; - return permutes; - }; - d3.pairs = function(array) { - var i = 0, n = array.length - 1, p0, p1 = array[0], pairs = new Array(n < 0 ? 0 : n); - while (i < n) pairs[i] = [ p0 = p1, p1 = array[++i] ]; - return pairs; - }; - d3.zip = function() { - if (!(n = arguments.length)) return []; - for (var i = -1, m = d3.min(arguments, d3_zipLength), zips = new Array(m); ++i < m; ) { - for (var j = -1, n, zip = zips[i] = new Array(n); ++j < n; ) { - zip[j] = arguments[j][i]; - } - } - return zips; - }; - function d3_zipLength(d) { - return d.length; - } - d3.transpose = function(matrix) { - return d3.zip.apply(d3, matrix); - }; - d3.keys = function(map) { - var keys = []; - for (var key in map) keys.push(key); - return keys; - }; - d3.values = function(map) { - var values = []; - for (var key in map) values.push(map[key]); - return values; - }; - d3.entries = function(map) { - var entries = []; - for (var key in map) entries.push({ - key: key, - value: map[key] - }); - return entries; - }; - d3.merge = function(arrays) { - var n = arrays.length, m, i = -1, j = 0, merged, array; - while (++i < n) j += arrays[i].length; - merged = new Array(j); - while (--n >= 0) { - array = arrays[n]; - m = array.length; - while (--m >= 0) { - merged[--j] = array[m]; - } - } - return merged; - }; - var abs = Math.abs; - d3.range = function(start, stop, step) { - if (arguments.length < 3) { - step = 1; - if (arguments.length < 2) { - stop = start; - start = 0; - } - } - if ((stop - start) / step === Infinity) throw new Error("infinite range"); - var range = [], k = d3_range_integerScale(abs(step)), i = -1, j; - start *= k, stop *= k, step *= k; - if (step < 0) while ((j = start + step * ++i) > stop) range.push(j / k); else while ((j = start + step * ++i) < stop) range.push(j / k); - return range; - }; - function d3_range_integerScale(x) { - var k = 1; - while (x * k % 1) k *= 10; - return k; - } - function d3_class(ctor, properties) { - try { - for (var key in properties) { - Object.defineProperty(ctor.prototype, key, { - value: properties[key], - enumerable: false - }); - } - } catch (e) { - ctor.prototype = properties; - } - } - d3.map = function(object) { - var map = new d3_Map(); - if (object instanceof d3_Map) object.forEach(function(key, value) { - map.set(key, value); - }); else for (var key in object) map.set(key, object[key]); - return map; - }; - function d3_Map() {} - d3_class(d3_Map, { - has: d3_map_has, - get: function(key) { - return this[d3_map_prefix + key]; - }, - set: function(key, value) { - return this[d3_map_prefix + key] = value; - }, - remove: d3_map_remove, - keys: d3_map_keys, - values: function() { - var values = []; - this.forEach(function(key, value) { - values.push(value); - }); - return values; - }, - entries: function() { - var entries = []; - this.forEach(function(key, value) { - entries.push({ - key: key, - value: value - }); - }); - return entries; - }, - size: d3_map_size, - empty: d3_map_empty, - forEach: function(f) { - for (var key in this) if (key.charCodeAt(0) === d3_map_prefixCode) f.call(this, key.slice(1), this[key]); - } - }); - var d3_map_prefix = "\x00", d3_map_prefixCode = d3_map_prefix.charCodeAt(0); - function d3_map_has(key) { - return d3_map_prefix + key in this; - } - function d3_map_remove(key) { - key = d3_map_prefix + key; - return key in this && delete this[key]; - } - function d3_map_keys() { - var keys = []; - this.forEach(function(key) { - keys.push(key); - }); - return keys; - } - function d3_map_size() { - var size = 0; - for (var key in this) if (key.charCodeAt(0) === d3_map_prefixCode) ++size; - return size; - } - function d3_map_empty() { - for (var key in this) if (key.charCodeAt(0) === d3_map_prefixCode) return false; - return true; - } - d3.nest = function() { - var nest = {}, keys = [], sortKeys = [], sortValues, rollup; - function map(mapType, array, depth) { - if (depth >= keys.length) return rollup ? rollup.call(nest, array) : sortValues ? array.sort(sortValues) : array; - var i = -1, n = array.length, key = keys[depth++], keyValue, object, setter, valuesByKey = new d3_Map(), values; - while (++i < n) { - if (values = valuesByKey.get(keyValue = key(object = array[i]))) { - values.push(object); - } else { - valuesByKey.set(keyValue, [ object ]); - } - } - if (mapType) { - object = mapType(); - setter = function(keyValue, values) { - object.set(keyValue, map(mapType, values, depth)); - }; - } else { - object = {}; - setter = function(keyValue, values) { - object[keyValue] = map(mapType, values, depth); - }; - } - valuesByKey.forEach(setter); - return object; - } - function entries(map, depth) { - if (depth >= keys.length) return map; - var array = [], sortKey = sortKeys[depth++]; - map.forEach(function(key, keyMap) { - array.push({ - key: key, - values: entries(keyMap, depth) - }); - }); - return sortKey ? array.sort(function(a, b) { - return sortKey(a.key, b.key); - }) : array; - } - nest.map = function(array, mapType) { - return map(mapType, array, 0); - }; - nest.entries = function(array) { - return entries(map(d3.map, array, 0), 0); - }; - nest.key = function(d) { - keys.push(d); - return nest; - }; - nest.sortKeys = function(order) { - sortKeys[keys.length - 1] = order; - return nest; - }; - nest.sortValues = function(order) { - sortValues = order; - return nest; - }; - nest.rollup = function(f) { - rollup = f; - return nest; - }; - return nest; - }; - d3.set = function(array) { - var set = new d3_Set(); - if (array) for (var i = 0, n = array.length; i < n; ++i) set.add(array[i]); - return set; - }; - function d3_Set() {} - d3_class(d3_Set, { - has: d3_map_has, - add: function(value) { - this[d3_map_prefix + value] = true; - return value; - }, - remove: function(value) { - value = d3_map_prefix + value; - return value in this && delete this[value]; - }, - values: d3_map_keys, - size: d3_map_size, - empty: d3_map_empty, - forEach: function(f) { - for (var value in this) if (value.charCodeAt(0) === d3_map_prefixCode) f.call(this, value.slice(1)); - } - }); - d3.behavior = {}; - d3.rebind = function(target, source) { - var i = 1, n = arguments.length, method; - while (++i < n) target[method = arguments[i]] = d3_rebind(target, source, source[method]); - return target; - }; - function d3_rebind(target, source, method) { - return function() { - var value = method.apply(source, arguments); - return value === source ? target : value; - }; - } - function d3_vendorSymbol(object, name) { - if (name in object) return name; - name = name.charAt(0).toUpperCase() + name.slice(1); - for (var i = 0, n = d3_vendorPrefixes.length; i < n; ++i) { - var prefixName = d3_vendorPrefixes[i] + name; - if (prefixName in object) return prefixName; - } - } - var d3_vendorPrefixes = [ "webkit", "ms", "moz", "Moz", "o", "O" ]; - function d3_noop() {} - d3.dispatch = function() { - var dispatch = new d3_dispatch(), i = -1, n = arguments.length; - while (++i < n) dispatch[arguments[i]] = d3_dispatch_event(dispatch); - return dispatch; - }; - function d3_dispatch() {} - d3_dispatch.prototype.on = function(type, listener) { - var i = type.indexOf("."), name = ""; - if (i >= 0) { - name = type.slice(i + 1); - type = type.slice(0, i); - } - if (type) return arguments.length < 2 ? this[type].on(name) : this[type].on(name, listener); - if (arguments.length === 2) { - if (listener == null) for (type in this) { - if (this.hasOwnProperty(type)) this[type].on(name, null); - } - return this; - } - }; - function d3_dispatch_event(dispatch) { - var listeners = [], listenerByName = new d3_Map(); - function event() { - var z = listeners, i = -1, n = z.length, l; - while (++i < n) if (l = z[i].on) l.apply(this, arguments); - return dispatch; - } - event.on = function(name, listener) { - var l = listenerByName.get(name), i; - if (arguments.length < 2) return l && l.on; - if (l) { - l.on = null; - listeners = listeners.slice(0, i = listeners.indexOf(l)).concat(listeners.slice(i + 1)); - listenerByName.remove(name); - } - if (listener) listeners.push(listenerByName.set(name, { - on: listener - })); - return dispatch; - }; - return event; - } - d3.event = null; - function d3_eventPreventDefault() { - d3.event.preventDefault(); - } - function d3_eventSource() { - var e = d3.event, s; - while (s = e.sourceEvent) e = s; - return e; - } - function d3_eventDispatch(target) { - var dispatch = new d3_dispatch(), i = 0, n = arguments.length; - while (++i < n) dispatch[arguments[i]] = d3_dispatch_event(dispatch); - dispatch.of = function(thiz, argumentz) { - return function(e1) { - try { - var e0 = e1.sourceEvent = d3.event; - e1.target = target; - d3.event = e1; - dispatch[e1.type].apply(thiz, argumentz); - } finally { - d3.event = e0; - } - }; - }; - return dispatch; - } - d3.requote = function(s) { - return s.replace(d3_requote_re, "\\$&"); - }; - var d3_requote_re = /[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g; - var d3_subclass = {}.__proto__ ? function(object, prototype) { - object.__proto__ = prototype; - } : function(object, prototype) { - for (var property in prototype) object[property] = prototype[property]; - }; - function d3_selection(groups) { - d3_subclass(groups, d3_selectionPrototype); - return groups; - } - var d3_select = function(s, n) { - return n.querySelector(s); - }, d3_selectAll = function(s, n) { - return n.querySelectorAll(s); - }, d3_selectMatcher = d3_documentElement.matches || d3_documentElement[d3_vendorSymbol(d3_documentElement, "matchesSelector")], d3_selectMatches = function(n, s) { - return d3_selectMatcher.call(n, s); - }; - if (typeof Sizzle === "function") { - d3_select = function(s, n) { - return Sizzle(s, n)[0] || null; - }; - d3_selectAll = Sizzle; - d3_selectMatches = Sizzle.matchesSelector; - } - d3.selection = function() { - return d3_selectionRoot; - }; - var d3_selectionPrototype = d3.selection.prototype = []; - d3_selectionPrototype.select = function(selector) { - var subgroups = [], subgroup, subnode, group, node; - selector = d3_selection_selector(selector); - for (var j = -1, m = this.length; ++j < m; ) { - subgroups.push(subgroup = []); - subgroup.parentNode = (group = this[j]).parentNode; - for (var i = -1, n = group.length; ++i < n; ) { - if (node = group[i]) { - subgroup.push(subnode = selector.call(node, node.__data__, i, j)); - if (subnode && "__data__" in node) subnode.__data__ = node.__data__; - } else { - subgroup.push(null); - } - } - } - return d3_selection(subgroups); - }; - function d3_selection_selector(selector) { - return typeof selector === "function" ? selector : function() { - return d3_select(selector, this); - }; - } - d3_selectionPrototype.selectAll = function(selector) { - var subgroups = [], subgroup, node; - selector = d3_selection_selectorAll(selector); - for (var j = -1, m = this.length; ++j < m; ) { - for (var group = this[j], i = -1, n = group.length; ++i < n; ) { - if (node = group[i]) { - subgroups.push(subgroup = d3_array(selector.call(node, node.__data__, i, j))); - subgroup.parentNode = node; - } - } - } - return d3_selection(subgroups); - }; - function d3_selection_selectorAll(selector) { - return typeof selector === "function" ? selector : function() { - return d3_selectAll(selector, this); - }; - } - var d3_nsPrefix = { - svg: "http://www.w3.org/2000/svg", - xhtml: "http://www.w3.org/1999/xhtml", - xlink: "http://www.w3.org/1999/xlink", - xml: "http://www.w3.org/XML/1998/namespace", - xmlns: "http://www.w3.org/2000/xmlns/" - }; - d3.ns = { - prefix: d3_nsPrefix, - qualify: function(name) { - var i = name.indexOf(":"), prefix = name; - if (i >= 0) { - prefix = name.slice(0, i); - name = name.slice(i + 1); - } - return d3_nsPrefix.hasOwnProperty(prefix) ? { - space: d3_nsPrefix[prefix], - local: name - } : name; - } - }; - d3_selectionPrototype.attr = function(name, value) { - if (arguments.length < 2) { - if (typeof name === "string") { - var node = this.node(); - name = d3.ns.qualify(name); - return name.local ? node.getAttributeNS(name.space, name.local) : node.getAttribute(name); - } - for (value in name) this.each(d3_selection_attr(value, name[value])); - return this; - } - return this.each(d3_selection_attr(name, value)); - }; - function d3_selection_attr(name, value) { - name = d3.ns.qualify(name); - function attrNull() { - this.removeAttribute(name); - } - function attrNullNS() { - this.removeAttributeNS(name.space, name.local); - } - function attrConstant() { - this.setAttribute(name, value); - } - function attrConstantNS() { - this.setAttributeNS(name.space, name.local, value); - } - function attrFunction() { - var x = value.apply(this, arguments); - if (x == null) this.removeAttribute(name); else this.setAttribute(name, x); - } - function attrFunctionNS() { - var x = value.apply(this, arguments); - if (x == null) this.removeAttributeNS(name.space, name.local); else this.setAttributeNS(name.space, name.local, x); - } - return value == null ? name.local ? attrNullNS : attrNull : typeof value === "function" ? name.local ? attrFunctionNS : attrFunction : name.local ? attrConstantNS : attrConstant; - } - function d3_collapse(s) { - return s.trim().replace(/\s+/g, " "); - } - d3_selectionPrototype.classed = function(name, value) { - if (arguments.length < 2) { - if (typeof name === "string") { - var node = this.node(), n = (name = d3_selection_classes(name)).length, i = -1; - if (value = node.classList) { - while (++i < n) if (!value.contains(name[i])) return false; - } else { - value = node.getAttribute("class"); - while (++i < n) if (!d3_selection_classedRe(name[i]).test(value)) return false; - } - return true; - } - for (value in name) this.each(d3_selection_classed(value, name[value])); - return this; - } - return this.each(d3_selection_classed(name, value)); - }; - function d3_selection_classedRe(name) { - return new RegExp("(?:^|\\s+)" + d3.requote(name) + "(?:\\s+|$)", "g"); - } - function d3_selection_classes(name) { - return (name + "").trim().split(/^|\s+/); - } - function d3_selection_classed(name, value) { - name = d3_selection_classes(name).map(d3_selection_classedName); - var n = name.length; - function classedConstant() { - var i = -1; - while (++i < n) name[i](this, value); - } - function classedFunction() { - var i = -1, x = value.apply(this, arguments); - while (++i < n) name[i](this, x); - } - return typeof value === "function" ? classedFunction : classedConstant; - } - function d3_selection_classedName(name) { - var re = d3_selection_classedRe(name); - return function(node, value) { - if (c = node.classList) return value ? c.add(name) : c.remove(name); - var c = node.getAttribute("class") || ""; - if (value) { - re.lastIndex = 0; - if (!re.test(c)) node.setAttribute("class", d3_collapse(c + " " + name)); - } else { - node.setAttribute("class", d3_collapse(c.replace(re, " "))); - } - }; - } - d3_selectionPrototype.style = function(name, value, priority) { - var n = arguments.length; - if (n < 3) { - if (typeof name !== "string") { - if (n < 2) value = ""; - for (priority in name) this.each(d3_selection_style(priority, name[priority], value)); - return this; - } - if (n < 2) return d3_window.getComputedStyle(this.node(), null).getPropertyValue(name); - priority = ""; - } - return this.each(d3_selection_style(name, value, priority)); - }; - function d3_selection_style(name, value, priority) { - function styleNull() { - this.style.removeProperty(name); - } - function styleConstant() { - this.style.setProperty(name, value, priority); - } - function styleFunction() { - var x = value.apply(this, arguments); - if (x == null) this.style.removeProperty(name); else this.style.setProperty(name, x, priority); - } - return value == null ? styleNull : typeof value === "function" ? styleFunction : styleConstant; - } - d3_selectionPrototype.property = function(name, value) { - if (arguments.length < 2) { - if (typeof name === "string") return this.node()[name]; - for (value in name) this.each(d3_selection_property(value, name[value])); - return this; - } - return this.each(d3_selection_property(name, value)); - }; - function d3_selection_property(name, value) { - function propertyNull() { - delete this[name]; - } - function propertyConstant() { - this[name] = value; - } - function propertyFunction() { - var x = value.apply(this, arguments); - if (x == null) delete this[name]; else this[name] = x; - } - return value == null ? propertyNull : typeof value === "function" ? propertyFunction : propertyConstant; - } - d3_selectionPrototype.text = function(value) { - return arguments.length ? this.each(typeof value === "function" ? function() { - var v = value.apply(this, arguments); - this.textContent = v == null ? "" : v; - } : value == null ? function() { - this.textContent = ""; - } : function() { - this.textContent = value; - }) : this.node().textContent; - }; - d3_selectionPrototype.html = function(value) { - return arguments.length ? this.each(typeof value === "function" ? function() { - var v = value.apply(this, arguments); - this.innerHTML = v == null ? "" : v; - } : value == null ? function() { - this.innerHTML = ""; - } : function() { - this.innerHTML = value; - }) : this.node().innerHTML; - }; - d3_selectionPrototype.append = function(name) { - name = d3_selection_creator(name); - return this.select(function() { - return this.appendChild(name.apply(this, arguments)); - }); - }; - function d3_selection_creator(name) { - return typeof name === "function" ? name : (name = d3.ns.qualify(name)).local ? function() { - return this.ownerDocument.createElementNS(name.space, name.local); - } : function() { - return this.ownerDocument.createElementNS(this.namespaceURI, name); - }; - } - d3_selectionPrototype.insert = function(name, before) { - name = d3_selection_creator(name); - before = d3_selection_selector(before); - return this.select(function() { - return this.insertBefore(name.apply(this, arguments), before.apply(this, arguments) || null); - }); - }; - d3_selectionPrototype.remove = function() { - return this.each(function() { - var parent = this.parentNode; - if (parent) parent.removeChild(this); - }); - }; - d3_selectionPrototype.data = function(value, key) { - var i = -1, n = this.length, group, node; - if (!arguments.length) { - value = new Array(n = (group = this[0]).length); - while (++i < n) { - if (node = group[i]) { - value[i] = node.__data__; - } - } - return value; - } - function bind(group, groupData) { - var i, n = group.length, m = groupData.length, n0 = Math.min(n, m), updateNodes = new Array(m), enterNodes = new Array(m), exitNodes = new Array(n), node, nodeData; - if (key) { - var nodeByKeyValue = new d3_Map(), dataByKeyValue = new d3_Map(), keyValues = [], keyValue; - for (i = -1; ++i < n; ) { - keyValue = key.call(node = group[i], node.__data__, i); - if (nodeByKeyValue.has(keyValue)) { - exitNodes[i] = node; - } else { - nodeByKeyValue.set(keyValue, node); - } - keyValues.push(keyValue); - } - for (i = -1; ++i < m; ) { - keyValue = key.call(groupData, nodeData = groupData[i], i); - if (node = nodeByKeyValue.get(keyValue)) { - updateNodes[i] = node; - node.__data__ = nodeData; - } else if (!dataByKeyValue.has(keyValue)) { - enterNodes[i] = d3_selection_dataNode(nodeData); - } - dataByKeyValue.set(keyValue, nodeData); - nodeByKeyValue.remove(keyValue); - } - for (i = -1; ++i < n; ) { - if (nodeByKeyValue.has(keyValues[i])) { - exitNodes[i] = group[i]; - } - } - } else { - for (i = -1; ++i < n0; ) { - node = group[i]; - nodeData = groupData[i]; - if (node) { - node.__data__ = nodeData; - updateNodes[i] = node; - } else { - enterNodes[i] = d3_selection_dataNode(nodeData); - } - } - for (;i < m; ++i) { - enterNodes[i] = d3_selection_dataNode(groupData[i]); - } - for (;i < n; ++i) { - exitNodes[i] = group[i]; - } - } - enterNodes.update = updateNodes; - enterNodes.parentNode = updateNodes.parentNode = exitNodes.parentNode = group.parentNode; - enter.push(enterNodes); - update.push(updateNodes); - exit.push(exitNodes); - } - var enter = d3_selection_enter([]), update = d3_selection([]), exit = d3_selection([]); - if (typeof value === "function") { - while (++i < n) { - bind(group = this[i], value.call(group, group.parentNode.__data__, i)); - } - } else { - while (++i < n) { - bind(group = this[i], value); - } - } - update.enter = function() { - return enter; - }; - update.exit = function() { - return exit; - }; - return update; - }; - function d3_selection_dataNode(data) { - return { - __data__: data - }; - } - d3_selectionPrototype.datum = function(value) { - return arguments.length ? this.property("__data__", value) : this.property("__data__"); - }; - d3_selectionPrototype.filter = function(filter) { - var subgroups = [], subgroup, group, node; - if (typeof filter !== "function") filter = d3_selection_filter(filter); - for (var j = 0, m = this.length; j < m; j++) { - subgroups.push(subgroup = []); - subgroup.parentNode = (group = this[j]).parentNode; - for (var i = 0, n = group.length; i < n; i++) { - if ((node = group[i]) && filter.call(node, node.__data__, i, j)) { - subgroup.push(node); - } - } - } - return d3_selection(subgroups); - }; - function d3_selection_filter(selector) { - return function() { - return d3_selectMatches(this, selector); - }; - } - d3_selectionPrototype.order = function() { - for (var j = -1, m = this.length; ++j < m; ) { - for (var group = this[j], i = group.length - 1, next = group[i], node; --i >= 0; ) { - if (node = group[i]) { - if (next && next !== node.nextSibling) next.parentNode.insertBefore(node, next); - next = node; - } - } - } - return this; - }; - d3_selectionPrototype.sort = function(comparator) { - comparator = d3_selection_sortComparator.apply(this, arguments); - for (var j = -1, m = this.length; ++j < m; ) this[j].sort(comparator); - return this.order(); - }; - function d3_selection_sortComparator(comparator) { - if (!arguments.length) comparator = d3_ascending; - return function(a, b) { - return a && b ? comparator(a.__data__, b.__data__) : !a - !b; - }; - } - d3_selectionPrototype.each = function(callback) { - return d3_selection_each(this, function(node, i, j) { - callback.call(node, node.__data__, i, j); - }); - }; - function d3_selection_each(groups, callback) { - for (var j = 0, m = groups.length; j < m; j++) { - for (var group = groups[j], i = 0, n = group.length, node; i < n; i++) { - if (node = group[i]) callback(node, i, j); - } - } - return groups; - } - d3_selectionPrototype.call = function(callback) { - var args = d3_array(arguments); - callback.apply(args[0] = this, args); - return this; - }; - d3_selectionPrototype.empty = function() { - return !this.node(); - }; - d3_selectionPrototype.node = function() { - for (var j = 0, m = this.length; j < m; j++) { - for (var group = this[j], i = 0, n = group.length; i < n; i++) { - var node = group[i]; - if (node) return node; - } - } - return null; - }; - d3_selectionPrototype.size = function() { - var n = 0; - d3_selection_each(this, function() { - ++n; - }); - return n; - }; - function d3_selection_enter(selection) { - d3_subclass(selection, d3_selection_enterPrototype); - return selection; - } - var d3_selection_enterPrototype = []; - d3.selection.enter = d3_selection_enter; - d3.selection.enter.prototype = d3_selection_enterPrototype; - d3_selection_enterPrototype.append = d3_selectionPrototype.append; - d3_selection_enterPrototype.empty = d3_selectionPrototype.empty; - d3_selection_enterPrototype.node = d3_selectionPrototype.node; - d3_selection_enterPrototype.call = d3_selectionPrototype.call; - d3_selection_enterPrototype.size = d3_selectionPrototype.size; - d3_selection_enterPrototype.select = function(selector) { - var subgroups = [], subgroup, subnode, upgroup, group, node; - for (var j = -1, m = this.length; ++j < m; ) { - upgroup = (group = this[j]).update; - subgroups.push(subgroup = []); - subgroup.parentNode = group.parentNode; - for (var i = -1, n = group.length; ++i < n; ) { - if (node = group[i]) { - subgroup.push(upgroup[i] = subnode = selector.call(group.parentNode, node.__data__, i, j)); - subnode.__data__ = node.__data__; - } else { - subgroup.push(null); - } - } - } - return d3_selection(subgroups); - }; - d3_selection_enterPrototype.insert = function(name, before) { - if (arguments.length < 2) before = d3_selection_enterInsertBefore(this); - return d3_selectionPrototype.insert.call(this, name, before); - }; - function d3_selection_enterInsertBefore(enter) { - var i0, j0; - return function(d, i, j) { - var group = enter[j].update, n = group.length, node; - if (j != j0) j0 = j, i0 = 0; - if (i >= i0) i0 = i + 1; - while (!(node = group[i0]) && ++i0 < n) ; - return node; - }; - } - d3_selectionPrototype.transition = function() { - var id = d3_transitionInheritId || ++d3_transitionId, subgroups = [], subgroup, node, transition = d3_transitionInherit || { - time: Date.now(), - ease: d3_ease_cubicInOut, - delay: 0, - duration: 250 - }; - for (var j = -1, m = this.length; ++j < m; ) { - subgroups.push(subgroup = []); - for (var group = this[j], i = -1, n = group.length; ++i < n; ) { - if (node = group[i]) d3_transitionNode(node, i, id, transition); - subgroup.push(node); - } - } - return d3_transition(subgroups, id); - }; - d3_selectionPrototype.interrupt = function() { - return this.each(d3_selection_interrupt); - }; - function d3_selection_interrupt() { - var lock = this.__transition__; - if (lock) ++lock.active; - } - d3.select = function(node) { - var group = [ typeof node === "string" ? d3_select(node, d3_document) : node ]; - group.parentNode = d3_documentElement; - return d3_selection([ group ]); - }; - d3.selectAll = function(nodes) { - var group = d3_array(typeof nodes === "string" ? d3_selectAll(nodes, d3_document) : nodes); - group.parentNode = d3_documentElement; - return d3_selection([ group ]); - }; - var d3_selectionRoot = d3.select(d3_documentElement); - d3_selectionPrototype.on = function(type, listener, capture) { - var n = arguments.length; - if (n < 3) { - if (typeof type !== "string") { - if (n < 2) listener = false; - for (capture in type) this.each(d3_selection_on(capture, type[capture], listener)); - return this; - } - if (n < 2) return (n = this.node()["__on" + type]) && n._; - capture = false; - } - return this.each(d3_selection_on(type, listener, capture)); - }; - function d3_selection_on(type, listener, capture) { - var name = "__on" + type, i = type.indexOf("."), wrap = d3_selection_onListener; - if (i > 0) type = type.slice(0, i); - var filter = d3_selection_onFilters.get(type); - if (filter) type = filter, wrap = d3_selection_onFilter; - function onRemove() { - var l = this[name]; - if (l) { - this.removeEventListener(type, l, l.$); - delete this[name]; - } - } - function onAdd() { - var l = wrap(listener, d3_array(arguments)); - onRemove.call(this); - this.addEventListener(type, this[name] = l, l.$ = capture); - l._ = listener; - } - function removeAll() { - var re = new RegExp("^__on([^.]+)" + d3.requote(type) + "$"), match; - for (var name in this) { - if (match = name.match(re)) { - var l = this[name]; - this.removeEventListener(match[1], l, l.$); - delete this[name]; - } - } - } - return i ? listener ? onAdd : onRemove : listener ? d3_noop : removeAll; - } - var d3_selection_onFilters = d3.map({ - mouseenter: "mouseover", - mouseleave: "mouseout" - }); - d3_selection_onFilters.forEach(function(k) { - if ("on" + k in d3_document) d3_selection_onFilters.remove(k); - }); - function d3_selection_onListener(listener, argumentz) { - return function(e) { - var o = d3.event; - d3.event = e; - argumentz[0] = this.__data__; - try { - listener.apply(this, argumentz); - } finally { - d3.event = o; - } - }; - } - function d3_selection_onFilter(listener, argumentz) { - var l = d3_selection_onListener(listener, argumentz); - return function(e) { - var target = this, related = e.relatedTarget; - if (!related || related !== target && !(related.compareDocumentPosition(target) & 8)) { - l.call(target, e); - } - }; - } - var d3_event_dragSelect = "onselectstart" in d3_document ? null : d3_vendorSymbol(d3_documentElement.style, "userSelect"), d3_event_dragId = 0; - function d3_event_dragSuppress() { - var name = ".dragsuppress-" + ++d3_event_dragId, click = "click" + name, w = d3.select(d3_window).on("touchmove" + name, d3_eventPreventDefault).on("dragstart" + name, d3_eventPreventDefault).on("selectstart" + name, d3_eventPreventDefault); - if (d3_event_dragSelect) { - var style = d3_documentElement.style, select = style[d3_event_dragSelect]; - style[d3_event_dragSelect] = "none"; - } - return function(suppressClick) { - w.on(name, null); - if (d3_event_dragSelect) style[d3_event_dragSelect] = select; - if (suppressClick) { - function off() { - w.on(click, null); - } - w.on(click, function() { - d3_eventPreventDefault(); - off(); - }, true); - setTimeout(off, 0); - } - }; - } - d3.mouse = function(container) { - return d3_mousePoint(container, d3_eventSource()); - }; - var d3_mouse_bug44083 = /WebKit/.test(d3_window.navigator.userAgent) ? -1 : 0; - function d3_mousePoint(container, e) { - if (e.changedTouches) e = e.changedTouches[0]; - var svg = container.ownerSVGElement || container; - if (svg.createSVGPoint) { - var point = svg.createSVGPoint(); - if (d3_mouse_bug44083 < 0 && (d3_window.scrollX || d3_window.scrollY)) { - svg = d3.select("body").append("svg").style({ - position: "absolute", - top: 0, - left: 0, - margin: 0, - padding: 0, - border: "none" - }, "important"); - var ctm = svg[0][0].getScreenCTM(); - d3_mouse_bug44083 = !(ctm.f || ctm.e); - svg.remove(); - } - if (d3_mouse_bug44083) point.x = e.pageX, point.y = e.pageY; else point.x = e.clientX, - point.y = e.clientY; - point = point.matrixTransform(container.getScreenCTM().inverse()); - return [ point.x, point.y ]; - } - var rect = container.getBoundingClientRect(); - return [ e.clientX - rect.left - container.clientLeft, e.clientY - rect.top - container.clientTop ]; - } - d3.touch = function(container, touches, identifier) { - if (arguments.length < 3) identifier = touches, touches = d3_eventSource().changedTouches; - if (touches) for (var i = 0, n = touches.length, touch; i < n; ++i) { - if ((touch = touches[i]).identifier === identifier) { - return d3_mousePoint(container, touch); - } - } - }; - d3.behavior.drag = function() { - var event = d3_eventDispatch(drag, "drag", "dragstart", "dragend"), origin = null, mousedown = dragstart(d3_noop, d3.mouse, d3_behavior_dragMouseSubject, "mousemove", "mouseup"), touchstart = dragstart(d3_behavior_dragTouchId, d3.touch, d3_behavior_dragTouchSubject, "touchmove", "touchend"); - function drag() { - this.on("mousedown.drag", mousedown).on("touchstart.drag", touchstart); - } - function dragstart(id, position, subject, move, end) { - return function() { - var that = this, target = d3.event.target, parent = that.parentNode, dispatch = event.of(that, arguments), dragged = 0, dragId = id(), dragName = ".drag" + (dragId == null ? "" : "-" + dragId), dragOffset, dragSubject = d3.select(subject()).on(move + dragName, moved).on(end + dragName, ended), dragRestore = d3_event_dragSuppress(), position0 = position(parent, dragId); - if (origin) { - dragOffset = origin.apply(that, arguments); - dragOffset = [ dragOffset.x - position0[0], dragOffset.y - position0[1] ]; - } else { - dragOffset = [ 0, 0 ]; - } - dispatch({ - type: "dragstart" - }); - function moved() { - var position1 = position(parent, dragId), dx, dy; - if (!position1) return; - dx = position1[0] - position0[0]; - dy = position1[1] - position0[1]; - dragged |= dx | dy; - position0 = position1; - dispatch({ - type: "drag", - x: position1[0] + dragOffset[0], - y: position1[1] + dragOffset[1], - dx: dx, - dy: dy - }); - } - function ended() { - if (!position(parent, dragId)) return; - dragSubject.on(move + dragName, null).on(end + dragName, null); - dragRestore(dragged && d3.event.target === target); - dispatch({ - type: "dragend" - }); - } - }; - } - drag.origin = function(x) { - if (!arguments.length) return origin; - origin = x; - return drag; - }; - return d3.rebind(drag, event, "on"); - }; - function d3_behavior_dragTouchId() { - return d3.event.changedTouches[0].identifier; - } - function d3_behavior_dragTouchSubject() { - return d3.event.target; - } - function d3_behavior_dragMouseSubject() { - return d3_window; - } - d3.touches = function(container, touches) { - if (arguments.length < 2) touches = d3_eventSource().touches; - return touches ? d3_array(touches).map(function(touch) { - var point = d3_mousePoint(container, touch); - point.identifier = touch.identifier; - return point; - }) : []; - }; - var π = Math.PI, τ = 2 * π, halfπ = π / 2, ε = 1e-6, ε2 = ε * ε, d3_radians = π / 180, d3_degrees = 180 / π; - function d3_sgn(x) { - return x > 0 ? 1 : x < 0 ? -1 : 0; - } - function d3_cross2d(a, b, c) { - return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]); - } - function d3_acos(x) { - return x > 1 ? 0 : x < -1 ? π : Math.acos(x); - } - function d3_asin(x) { - return x > 1 ? halfπ : x < -1 ? -halfπ : Math.asin(x); - } - function d3_sinh(x) { - return ((x = Math.exp(x)) - 1 / x) / 2; - } - function d3_cosh(x) { - return ((x = Math.exp(x)) + 1 / x) / 2; - } - function d3_tanh(x) { - return ((x = Math.exp(2 * x)) - 1) / (x + 1); - } - function d3_haversin(x) { - return (x = Math.sin(x / 2)) * x; - } - var ρ = Math.SQRT2, ρ2 = 2, ρ4 = 4; - d3.interpolateZoom = function(p0, p1) { - var ux0 = p0[0], uy0 = p0[1], w0 = p0[2], ux1 = p1[0], uy1 = p1[1], w1 = p1[2]; - var dx = ux1 - ux0, dy = uy1 - uy0, d2 = dx * dx + dy * dy, d1 = Math.sqrt(d2), b0 = (w1 * w1 - w0 * w0 + ρ4 * d2) / (2 * w0 * ρ2 * d1), b1 = (w1 * w1 - w0 * w0 - ρ4 * d2) / (2 * w1 * ρ2 * d1), r0 = Math.log(Math.sqrt(b0 * b0 + 1) - b0), r1 = Math.log(Math.sqrt(b1 * b1 + 1) - b1), dr = r1 - r0, S = (dr || Math.log(w1 / w0)) / ρ; - function interpolate(t) { - var s = t * S; - if (dr) { - var coshr0 = d3_cosh(r0), u = w0 / (ρ2 * d1) * (coshr0 * d3_tanh(ρ * s + r0) - d3_sinh(r0)); - return [ ux0 + u * dx, uy0 + u * dy, w0 * coshr0 / d3_cosh(ρ * s + r0) ]; - } - return [ ux0 + t * dx, uy0 + t * dy, w0 * Math.exp(ρ * s) ]; - } - interpolate.duration = S * 1e3; - return interpolate; - }; - d3.behavior.zoom = function() { - var view = { - x: 0, - y: 0, - k: 1 - }, translate0, center0, center, size = [ 960, 500 ], scaleExtent = d3_behavior_zoomInfinity, mousedown = "mousedown.zoom", mousemove = "mousemove.zoom", mouseup = "mouseup.zoom", mousewheelTimer, touchstart = "touchstart.zoom", touchtime, event = d3_eventDispatch(zoom, "zoomstart", "zoom", "zoomend"), x0, x1, y0, y1; - function zoom(g) { - g.on(mousedown, mousedowned).on(d3_behavior_zoomWheel + ".zoom", mousewheeled).on("dblclick.zoom", dblclicked).on(touchstart, touchstarted); - } - zoom.event = function(g) { - g.each(function() { - var dispatch = event.of(this, arguments), view1 = view; - if (d3_transitionInheritId) { - d3.select(this).transition().each("start.zoom", function() { - view = this.__chart__ || { - x: 0, - y: 0, - k: 1 - }; - zoomstarted(dispatch); - }).tween("zoom:zoom", function() { - var dx = size[0], dy = size[1], cx = dx / 2, cy = dy / 2, i = d3.interpolateZoom([ (cx - view.x) / view.k, (cy - view.y) / view.k, dx / view.k ], [ (cx - view1.x) / view1.k, (cy - view1.y) / view1.k, dx / view1.k ]); - return function(t) { - var l = i(t), k = dx / l[2]; - this.__chart__ = view = { - x: cx - l[0] * k, - y: cy - l[1] * k, - k: k - }; - zoomed(dispatch); - }; - }).each("end.zoom", function() { - zoomended(dispatch); - }); - } else { - this.__chart__ = view; - zoomstarted(dispatch); - zoomed(dispatch); - zoomended(dispatch); - } - }); - }; - zoom.translate = function(_) { - if (!arguments.length) return [ view.x, view.y ]; - view = { - x: +_[0], - y: +_[1], - k: view.k - }; - rescale(); - return zoom; - }; - zoom.scale = function(_) { - if (!arguments.length) return view.k; - view = { - x: view.x, - y: view.y, - k: +_ - }; - rescale(); - return zoom; - }; - zoom.scaleExtent = function(_) { - if (!arguments.length) return scaleExtent; - scaleExtent = _ == null ? d3_behavior_zoomInfinity : [ +_[0], +_[1] ]; - return zoom; - }; - zoom.center = function(_) { - if (!arguments.length) return center; - center = _ && [ +_[0], +_[1] ]; - return zoom; - }; - zoom.size = function(_) { - if (!arguments.length) return size; - size = _ && [ +_[0], +_[1] ]; - return zoom; - }; - zoom.x = function(z) { - if (!arguments.length) return x1; - x1 = z; - x0 = z.copy(); - view = { - x: 0, - y: 0, - k: 1 - }; - return zoom; - }; - zoom.y = function(z) { - if (!arguments.length) return y1; - y1 = z; - y0 = z.copy(); - view = { - x: 0, - y: 0, - k: 1 - }; - return zoom; - }; - function location(p) { - return [ (p[0] - view.x) / view.k, (p[1] - view.y) / view.k ]; - } - function point(l) { - return [ l[0] * view.k + view.x, l[1] * view.k + view.y ]; - } - function scaleTo(s) { - view.k = Math.max(scaleExtent[0], Math.min(scaleExtent[1], s)); - } - function translateTo(p, l) { - l = point(l); - view.x += p[0] - l[0]; - view.y += p[1] - l[1]; - } - function rescale() { - if (x1) x1.domain(x0.range().map(function(x) { - return (x - view.x) / view.k; - }).map(x0.invert)); - if (y1) y1.domain(y0.range().map(function(y) { - return (y - view.y) / view.k; - }).map(y0.invert)); - } - function zoomstarted(dispatch) { - dispatch({ - type: "zoomstart" - }); - } - function zoomed(dispatch) { - rescale(); - dispatch({ - type: "zoom", - scale: view.k, - translate: [ view.x, view.y ] - }); - } - function zoomended(dispatch) { - dispatch({ - type: "zoomend" - }); - } - function mousedowned() { - var that = this, target = d3.event.target, dispatch = event.of(that, arguments), dragged = 0, subject = d3.select(d3_window).on(mousemove, moved).on(mouseup, ended), location0 = location(d3.mouse(that)), dragRestore = d3_event_dragSuppress(); - d3_selection_interrupt.call(that); - zoomstarted(dispatch); - function moved() { - dragged = 1; - translateTo(d3.mouse(that), location0); - zoomed(dispatch); - } - function ended() { - subject.on(mousemove, null).on(mouseup, null); - dragRestore(dragged && d3.event.target === target); - zoomended(dispatch); - } - } - function touchstarted() { - var that = this, dispatch = event.of(that, arguments), locations0 = {}, distance0 = 0, scale0, zoomName = ".zoom-" + d3.event.changedTouches[0].identifier, touchmove = "touchmove" + zoomName, touchend = "touchend" + zoomName, targets = [], subject = d3.select(that), dragRestore = d3_event_dragSuppress(); - d3_selection_interrupt.call(that); - started(); - zoomstarted(dispatch); - subject.on(mousedown, null).on(touchstart, started); - function relocate() { - var touches = d3.touches(that); - scale0 = view.k; - touches.forEach(function(t) { - if (t.identifier in locations0) locations0[t.identifier] = location(t); - }); - return touches; - } - function started() { - var target = d3.event.target; - d3.select(target).on(touchmove, moved).on(touchend, ended); - targets.push(target); - var changed = d3.event.changedTouches; - for (var i = 0, n = changed.length; i < n; ++i) { - locations0[changed[i].identifier] = null; - } - var touches = relocate(), now = Date.now(); - if (touches.length === 1) { - if (now - touchtime < 500) { - var p = touches[0], l = locations0[p.identifier]; - scaleTo(view.k * 2); - translateTo(p, l); - d3_eventPreventDefault(); - zoomed(dispatch); - } - touchtime = now; - } else if (touches.length > 1) { - var p = touches[0], q = touches[1], dx = p[0] - q[0], dy = p[1] - q[1]; - distance0 = dx * dx + dy * dy; - } - } - function moved() { - var touches = d3.touches(that), p0, l0, p1, l1; - for (var i = 0, n = touches.length; i < n; ++i, l1 = null) { - p1 = touches[i]; - if (l1 = locations0[p1.identifier]) { - if (l0) break; - p0 = p1, l0 = l1; - } - } - if (l1) { - var distance1 = (distance1 = p1[0] - p0[0]) * distance1 + (distance1 = p1[1] - p0[1]) * distance1, scale1 = distance0 && Math.sqrt(distance1 / distance0); - p0 = [ (p0[0] + p1[0]) / 2, (p0[1] + p1[1]) / 2 ]; - l0 = [ (l0[0] + l1[0]) / 2, (l0[1] + l1[1]) / 2 ]; - scaleTo(scale1 * scale0); - } - touchtime = null; - translateTo(p0, l0); - zoomed(dispatch); - } - function ended() { - if (d3.event.touches.length) { - var changed = d3.event.changedTouches; - for (var i = 0, n = changed.length; i < n; ++i) { - delete locations0[changed[i].identifier]; - } - for (var identifier in locations0) { - return void relocate(); - } - } - d3.selectAll(targets).on(zoomName, null); - subject.on(mousedown, mousedowned).on(touchstart, touchstarted); - dragRestore(); - zoomended(dispatch); - } - } - function mousewheeled() { - var dispatch = event.of(this, arguments); - if (mousewheelTimer) clearTimeout(mousewheelTimer); else translate0 = location(center0 = center || d3.mouse(this)), - d3_selection_interrupt.call(this), zoomstarted(dispatch); - mousewheelTimer = setTimeout(function() { - mousewheelTimer = null; - zoomended(dispatch); - }, 50); - d3_eventPreventDefault(); - scaleTo(Math.pow(2, d3_behavior_zoomDelta() * .002) * view.k); - translateTo(center0, translate0); - zoomed(dispatch); - } - function dblclicked() { - var dispatch = event.of(this, arguments), p = d3.mouse(this), l = location(p), k = Math.log(view.k) / Math.LN2; - zoomstarted(dispatch); - scaleTo(Math.pow(2, d3.event.shiftKey ? Math.ceil(k) - 1 : Math.floor(k) + 1)); - translateTo(p, l); - zoomed(dispatch); - zoomended(dispatch); - } - return d3.rebind(zoom, event, "on"); - }; - var d3_behavior_zoomInfinity = [ 0, Infinity ]; - var d3_behavior_zoomDelta, d3_behavior_zoomWheel = "onwheel" in d3_document ? (d3_behavior_zoomDelta = function() { - return -d3.event.deltaY * (d3.event.deltaMode ? 120 : 1); - }, "wheel") : "onmousewheel" in d3_document ? (d3_behavior_zoomDelta = function() { - return d3.event.wheelDelta; - }, "mousewheel") : (d3_behavior_zoomDelta = function() { - return -d3.event.detail; - }, "MozMousePixelScroll"); - d3.color = d3_color; - function d3_color() {} - d3_color.prototype.toString = function() { - return this.rgb() + ""; - }; - d3.hsl = d3_hsl; - function d3_hsl(h, s, l) { - return this instanceof d3_hsl ? void (this.h = +h, this.s = +s, this.l = +l) : arguments.length < 2 ? h instanceof d3_hsl ? new d3_hsl(h.h, h.s, h.l) : d3_rgb_parse("" + h, d3_rgb_hsl, d3_hsl) : new d3_hsl(h, s, l); - } - var d3_hslPrototype = d3_hsl.prototype = new d3_color(); - d3_hslPrototype.brighter = function(k) { - k = Math.pow(.7, arguments.length ? k : 1); - return new d3_hsl(this.h, this.s, this.l / k); - }; - d3_hslPrototype.darker = function(k) { - k = Math.pow(.7, arguments.length ? k : 1); - return new d3_hsl(this.h, this.s, k * this.l); - }; - d3_hslPrototype.rgb = function() { - return d3_hsl_rgb(this.h, this.s, this.l); - }; - function d3_hsl_rgb(h, s, l) { - var m1, m2; - h = isNaN(h) ? 0 : (h %= 360) < 0 ? h + 360 : h; - s = isNaN(s) ? 0 : s < 0 ? 0 : s > 1 ? 1 : s; - l = l < 0 ? 0 : l > 1 ? 1 : l; - m2 = l <= .5 ? l * (1 + s) : l + s - l * s; - m1 = 2 * l - m2; - function v(h) { - if (h > 360) h -= 360; else if (h < 0) h += 360; - if (h < 60) return m1 + (m2 - m1) * h / 60; - if (h < 180) return m2; - if (h < 240) return m1 + (m2 - m1) * (240 - h) / 60; - return m1; - } - function vv(h) { - return Math.round(v(h) * 255); - } - return new d3_rgb(vv(h + 120), vv(h), vv(h - 120)); - } - d3.hcl = d3_hcl; - function d3_hcl(h, c, l) { - return this instanceof d3_hcl ? void (this.h = +h, this.c = +c, this.l = +l) : arguments.length < 2 ? h instanceof d3_hcl ? new d3_hcl(h.h, h.c, h.l) : h instanceof d3_lab ? d3_lab_hcl(h.l, h.a, h.b) : d3_lab_hcl((h = d3_rgb_lab((h = d3.rgb(h)).r, h.g, h.b)).l, h.a, h.b) : new d3_hcl(h, c, l); - } - var d3_hclPrototype = d3_hcl.prototype = new d3_color(); - d3_hclPrototype.brighter = function(k) { - return new d3_hcl(this.h, this.c, Math.min(100, this.l + d3_lab_K * (arguments.length ? k : 1))); - }; - d3_hclPrototype.darker = function(k) { - return new d3_hcl(this.h, this.c, Math.max(0, this.l - d3_lab_K * (arguments.length ? k : 1))); - }; - d3_hclPrototype.rgb = function() { - return d3_hcl_lab(this.h, this.c, this.l).rgb(); - }; - function d3_hcl_lab(h, c, l) { - if (isNaN(h)) h = 0; - if (isNaN(c)) c = 0; - return new d3_lab(l, Math.cos(h *= d3_radians) * c, Math.sin(h) * c); - } - d3.lab = d3_lab; - function d3_lab(l, a, b) { - return this instanceof d3_lab ? void (this.l = +l, this.a = +a, this.b = +b) : arguments.length < 2 ? l instanceof d3_lab ? new d3_lab(l.l, l.a, l.b) : l instanceof d3_hcl ? d3_hcl_lab(l.l, l.c, l.h) : d3_rgb_lab((l = d3_rgb(l)).r, l.g, l.b) : new d3_lab(l, a, b); - } - var d3_lab_K = 18; - var d3_lab_X = .95047, d3_lab_Y = 1, d3_lab_Z = 1.08883; - var d3_labPrototype = d3_lab.prototype = new d3_color(); - d3_labPrototype.brighter = function(k) { - return new d3_lab(Math.min(100, this.l + d3_lab_K * (arguments.length ? k : 1)), this.a, this.b); - }; - d3_labPrototype.darker = function(k) { - return new d3_lab(Math.max(0, this.l - d3_lab_K * (arguments.length ? k : 1)), this.a, this.b); - }; - d3_labPrototype.rgb = function() { - return d3_lab_rgb(this.l, this.a, this.b); - }; - function d3_lab_rgb(l, a, b) { - var y = (l + 16) / 116, x = y + a / 500, z = y - b / 200; - x = d3_lab_xyz(x) * d3_lab_X; - y = d3_lab_xyz(y) * d3_lab_Y; - z = d3_lab_xyz(z) * d3_lab_Z; - return new d3_rgb(d3_xyz_rgb(3.2404542 * x - 1.5371385 * y - .4985314 * z), d3_xyz_rgb(-.969266 * x + 1.8760108 * y + .041556 * z), d3_xyz_rgb(.0556434 * x - .2040259 * y + 1.0572252 * z)); - } - function d3_lab_hcl(l, a, b) { - return l > 0 ? new d3_hcl(Math.atan2(b, a) * d3_degrees, Math.sqrt(a * a + b * b), l) : new d3_hcl(NaN, NaN, l); - } - function d3_lab_xyz(x) { - return x > .206893034 ? x * x * x : (x - 4 / 29) / 7.787037; - } - function d3_xyz_lab(x) { - return x > .008856 ? Math.pow(x, 1 / 3) : 7.787037 * x + 4 / 29; - } - function d3_xyz_rgb(r) { - return Math.round(255 * (r <= .00304 ? 12.92 * r : 1.055 * Math.pow(r, 1 / 2.4) - .055)); - } - d3.rgb = d3_rgb; - function d3_rgb(r, g, b) { - return this instanceof d3_rgb ? void (this.r = ~~r, this.g = ~~g, this.b = ~~b) : arguments.length < 2 ? r instanceof d3_rgb ? new d3_rgb(r.r, r.g, r.b) : d3_rgb_parse("" + r, d3_rgb, d3_hsl_rgb) : new d3_rgb(r, g, b); - } - function d3_rgbNumber(value) { - return new d3_rgb(value >> 16, value >> 8 & 255, value & 255); - } - function d3_rgbString(value) { - return d3_rgbNumber(value) + ""; - } - var d3_rgbPrototype = d3_rgb.prototype = new d3_color(); - d3_rgbPrototype.brighter = function(k) { - k = Math.pow(.7, arguments.length ? k : 1); - var r = this.r, g = this.g, b = this.b, i = 30; - if (!r && !g && !b) return new d3_rgb(i, i, i); - if (r && r < i) r = i; - if (g && g < i) g = i; - if (b && b < i) b = i; - return new d3_rgb(Math.min(255, r / k), Math.min(255, g / k), Math.min(255, b / k)); - }; - d3_rgbPrototype.darker = function(k) { - k = Math.pow(.7, arguments.length ? k : 1); - return new d3_rgb(k * this.r, k * this.g, k * this.b); - }; - d3_rgbPrototype.hsl = function() { - return d3_rgb_hsl(this.r, this.g, this.b); - }; - d3_rgbPrototype.toString = function() { - return "#" + d3_rgb_hex(this.r) + d3_rgb_hex(this.g) + d3_rgb_hex(this.b); - }; - function d3_rgb_hex(v) { - return v < 16 ? "0" + Math.max(0, v).toString(16) : Math.min(255, v).toString(16); - } - function d3_rgb_parse(format, rgb, hsl) { - var r = 0, g = 0, b = 0, m1, m2, color; - m1 = /([a-z]+)\((.*)\)/i.exec(format); - if (m1) { - m2 = m1[2].split(","); - switch (m1[1]) { - case "hsl": - { - return hsl(parseFloat(m2[0]), parseFloat(m2[1]) / 100, parseFloat(m2[2]) / 100); - } - - case "rgb": - { - return rgb(d3_rgb_parseNumber(m2[0]), d3_rgb_parseNumber(m2[1]), d3_rgb_parseNumber(m2[2])); - } - } - } - if (color = d3_rgb_names.get(format)) return rgb(color.r, color.g, color.b); - if (format != null && format.charAt(0) === "#" && !isNaN(color = parseInt(format.slice(1), 16))) { - if (format.length === 4) { - r = (color & 3840) >> 4; - r = r >> 4 | r; - g = color & 240; - g = g >> 4 | g; - b = color & 15; - b = b << 4 | b; - } else if (format.length === 7) { - r = (color & 16711680) >> 16; - g = (color & 65280) >> 8; - b = color & 255; - } - } - return rgb(r, g, b); - } - function d3_rgb_hsl(r, g, b) { - var min = Math.min(r /= 255, g /= 255, b /= 255), max = Math.max(r, g, b), d = max - min, h, s, l = (max + min) / 2; - if (d) { - s = l < .5 ? d / (max + min) : d / (2 - max - min); - if (r == max) h = (g - b) / d + (g < b ? 6 : 0); else if (g == max) h = (b - r) / d + 2; else h = (r - g) / d + 4; - h *= 60; - } else { - h = NaN; - s = l > 0 && l < 1 ? 0 : h; - } - return new d3_hsl(h, s, l); - } - function d3_rgb_lab(r, g, b) { - r = d3_rgb_xyz(r); - g = d3_rgb_xyz(g); - b = d3_rgb_xyz(b); - var x = d3_xyz_lab((.4124564 * r + .3575761 * g + .1804375 * b) / d3_lab_X), y = d3_xyz_lab((.2126729 * r + .7151522 * g + .072175 * b) / d3_lab_Y), z = d3_xyz_lab((.0193339 * r + .119192 * g + .9503041 * b) / d3_lab_Z); - return d3_lab(116 * y - 16, 500 * (x - y), 200 * (y - z)); - } - function d3_rgb_xyz(r) { - return (r /= 255) <= .04045 ? r / 12.92 : Math.pow((r + .055) / 1.055, 2.4); - } - function d3_rgb_parseNumber(c) { - var f = parseFloat(c); - return c.charAt(c.length - 1) === "%" ? Math.round(f * 2.55) : f; - } - var d3_rgb_names = d3.map({ - aliceblue: 15792383, - antiquewhite: 16444375, - aqua: 65535, - aquamarine: 8388564, - azure: 15794175, - beige: 16119260, - bisque: 16770244, - black: 0, - blanchedalmond: 16772045, - blue: 255, - blueviolet: 9055202, - brown: 10824234, - burlywood: 14596231, - cadetblue: 6266528, - chartreuse: 8388352, - chocolate: 13789470, - coral: 16744272, - cornflowerblue: 6591981, - cornsilk: 16775388, - crimson: 14423100, - cyan: 65535, - darkblue: 139, - darkcyan: 35723, - darkgoldenrod: 12092939, - darkgray: 11119017, - darkgreen: 25600, - darkgrey: 11119017, - darkkhaki: 12433259, - darkmagenta: 9109643, - darkolivegreen: 5597999, - darkorange: 16747520, - darkorchid: 10040012, - darkred: 9109504, - darksalmon: 15308410, - darkseagreen: 9419919, - darkslateblue: 4734347, - darkslategray: 3100495, - darkslategrey: 3100495, - darkturquoise: 52945, - darkviolet: 9699539, - deeppink: 16716947, - deepskyblue: 49151, - dimgray: 6908265, - dimgrey: 6908265, - dodgerblue: 2003199, - firebrick: 11674146, - floralwhite: 16775920, - forestgreen: 2263842, - fuchsia: 16711935, - gainsboro: 14474460, - ghostwhite: 16316671, - gold: 16766720, - goldenrod: 14329120, - gray: 8421504, - green: 32768, - greenyellow: 11403055, - grey: 8421504, - honeydew: 15794160, - hotpink: 16738740, - indianred: 13458524, - indigo: 4915330, - ivory: 16777200, - khaki: 15787660, - lavender: 15132410, - lavenderblush: 16773365, - lawngreen: 8190976, - lemonchiffon: 16775885, - lightblue: 11393254, - lightcoral: 15761536, - lightcyan: 14745599, - lightgoldenrodyellow: 16448210, - lightgray: 13882323, - lightgreen: 9498256, - lightgrey: 13882323, - lightpink: 16758465, - lightsalmon: 16752762, - lightseagreen: 2142890, - lightskyblue: 8900346, - lightslategray: 7833753, - lightslategrey: 7833753, - lightsteelblue: 11584734, - lightyellow: 16777184, - lime: 65280, - limegreen: 3329330, - linen: 16445670, - magenta: 16711935, - maroon: 8388608, - mediumaquamarine: 6737322, - mediumblue: 205, - mediumorchid: 12211667, - mediumpurple: 9662683, - mediumseagreen: 3978097, - mediumslateblue: 8087790, - mediumspringgreen: 64154, - mediumturquoise: 4772300, - mediumvioletred: 13047173, - midnightblue: 1644912, - mintcream: 16121850, - mistyrose: 16770273, - moccasin: 16770229, - navajowhite: 16768685, - navy: 128, - oldlace: 16643558, - olive: 8421376, - olivedrab: 7048739, - orange: 16753920, - orangered: 16729344, - orchid: 14315734, - palegoldenrod: 15657130, - palegreen: 10025880, - paleturquoise: 11529966, - palevioletred: 14381203, - papayawhip: 16773077, - peachpuff: 16767673, - peru: 13468991, - pink: 16761035, - plum: 14524637, - powderblue: 11591910, - purple: 8388736, - red: 16711680, - rosybrown: 12357519, - royalblue: 4286945, - saddlebrown: 9127187, - salmon: 16416882, - sandybrown: 16032864, - seagreen: 3050327, - seashell: 16774638, - sienna: 10506797, - silver: 12632256, - skyblue: 8900331, - slateblue: 6970061, - slategray: 7372944, - slategrey: 7372944, - snow: 16775930, - springgreen: 65407, - steelblue: 4620980, - tan: 13808780, - teal: 32896, - thistle: 14204888, - tomato: 16737095, - turquoise: 4251856, - violet: 15631086, - wheat: 16113331, - white: 16777215, - whitesmoke: 16119285, - yellow: 16776960, - yellowgreen: 10145074 - }); - d3_rgb_names.forEach(function(key, value) { - d3_rgb_names.set(key, d3_rgbNumber(value)); - }); - function d3_functor(v) { - return typeof v === "function" ? v : function() { - return v; - }; - } - d3.functor = d3_functor; - function d3_identity(d) { - return d; - } - d3.xhr = d3_xhrType(d3_identity); - function d3_xhrType(response) { - return function(url, mimeType, callback) { - if (arguments.length === 2 && typeof mimeType === "function") callback = mimeType, - mimeType = null; - return d3_xhr(url, mimeType, response, callback); - }; - } - function d3_xhr(url, mimeType, response, callback) { - var xhr = {}, dispatch = d3.dispatch("beforesend", "progress", "load", "error"), headers = {}, request = new XMLHttpRequest(), responseType = null; - if (d3_window.XDomainRequest && !("withCredentials" in request) && /^(http(s)?:)?\/\//.test(url)) request = new XDomainRequest(); - "onload" in request ? request.onload = request.onerror = respond : request.onreadystatechange = function() { - request.readyState > 3 && respond(); - }; - function respond() { - var status = request.status, result; - if (!status && d3_xhrHasResponse(request) || status >= 200 && status < 300 || status === 304) { - try { - result = response.call(xhr, request); - } catch (e) { - dispatch.error.call(xhr, e); - return; - } - dispatch.load.call(xhr, result); - } else { - dispatch.error.call(xhr, request); - } - } - request.onprogress = function(event) { - var o = d3.event; - d3.event = event; - try { - dispatch.progress.call(xhr, request); - } finally { - d3.event = o; - } - }; - xhr.header = function(name, value) { - name = (name + "").toLowerCase(); - if (arguments.length < 2) return headers[name]; - if (value == null) delete headers[name]; else headers[name] = value + ""; - return xhr; - }; - xhr.mimeType = function(value) { - if (!arguments.length) return mimeType; - mimeType = value == null ? null : value + ""; - return xhr; - }; - xhr.responseType = function(value) { - if (!arguments.length) return responseType; - responseType = value; - return xhr; - }; - xhr.response = function(value) { - response = value; - return xhr; - }; - [ "get", "post" ].forEach(function(method) { - xhr[method] = function() { - return xhr.send.apply(xhr, [ method ].concat(d3_array(arguments))); - }; - }); - xhr.send = function(method, data, callback) { - if (arguments.length === 2 && typeof data === "function") callback = data, data = null; - request.open(method, url, true); - if (mimeType != null && !("accept" in headers)) headers["accept"] = mimeType + ",*/*"; - if (request.setRequestHeader) for (var name in headers) request.setRequestHeader(name, headers[name]); - if (mimeType != null && request.overrideMimeType) request.overrideMimeType(mimeType); - if (responseType != null) request.responseType = responseType; - if (callback != null) xhr.on("error", callback).on("load", function(request) { - callback(null, request); - }); - dispatch.beforesend.call(xhr, request); - request.send(data == null ? null : data); - return xhr; - }; - xhr.abort = function() { - request.abort(); - return xhr; - }; - d3.rebind(xhr, dispatch, "on"); - return callback == null ? xhr : xhr.get(d3_xhr_fixCallback(callback)); - } - function d3_xhr_fixCallback(callback) { - return callback.length === 1 ? function(error, request) { - callback(error == null ? request : null); - } : callback; - } - function d3_xhrHasResponse(request) { - var type = request.responseType; - return type && type !== "text" ? request.response : request.responseText; - } - d3.dsv = function(delimiter, mimeType) { - var reFormat = new RegExp('["' + delimiter + "\n]"), delimiterCode = delimiter.charCodeAt(0); - function dsv(url, row, callback) { - if (arguments.length < 3) callback = row, row = null; - var xhr = d3_xhr(url, mimeType, row == null ? response : typedResponse(row), callback); - xhr.row = function(_) { - return arguments.length ? xhr.response((row = _) == null ? response : typedResponse(_)) : row; - }; - return xhr; - } - function response(request) { - return dsv.parse(request.responseText); - } - function typedResponse(f) { - return function(request) { - return dsv.parse(request.responseText, f); - }; - } - dsv.parse = function(text, f) { - var o; - return dsv.parseRows(text, function(row, i) { - if (o) return o(row, i - 1); - var a = new Function("d", "return {" + row.map(function(name, i) { - return JSON.stringify(name) + ": d[" + i + "]"; - }).join(",") + "}"); - o = f ? function(row, i) { - return f(a(row), i); - } : a; - }); - }; - dsv.parseRows = function(text, f) { - var EOL = {}, EOF = {}, rows = [], N = text.length, I = 0, n = 0, t, eol; - function token() { - if (I >= N) return EOF; - if (eol) return eol = false, EOL; - var j = I; - if (text.charCodeAt(j) === 34) { - var i = j; - while (i++ < N) { - if (text.charCodeAt(i) === 34) { - if (text.charCodeAt(i + 1) !== 34) break; - ++i; - } - } - I = i + 2; - var c = text.charCodeAt(i + 1); - if (c === 13) { - eol = true; - if (text.charCodeAt(i + 2) === 10) ++I; - } else if (c === 10) { - eol = true; - } - return text.slice(j + 1, i).replace(/""/g, '"'); - } - while (I < N) { - var c = text.charCodeAt(I++), k = 1; - if (c === 10) eol = true; else if (c === 13) { - eol = true; - if (text.charCodeAt(I) === 10) ++I, ++k; - } else if (c !== delimiterCode) continue; - return text.slice(j, I - k); - } - return text.slice(j); - } - while ((t = token()) !== EOF) { - var a = []; - while (t !== EOL && t !== EOF) { - a.push(t); - t = token(); - } - if (f && !(a = f(a, n++))) continue; - rows.push(a); - } - return rows; - }; - dsv.format = function(rows) { - if (Array.isArray(rows[0])) return dsv.formatRows(rows); - var fieldSet = new d3_Set(), fields = []; - rows.forEach(function(row) { - for (var field in row) { - if (!fieldSet.has(field)) { - fields.push(fieldSet.add(field)); - } - } - }); - return [ fields.map(formatValue).join(delimiter) ].concat(rows.map(function(row) { - return fields.map(function(field) { - return formatValue(row[field]); - }).join(delimiter); - })).join("\n"); - }; - dsv.formatRows = function(rows) { - return rows.map(formatRow).join("\n"); - }; - function formatRow(row) { - return row.map(formatValue).join(delimiter); - } - function formatValue(text) { - return reFormat.test(text) ? '"' + text.replace(/\"/g, '""') + '"' : text; - } - return dsv; - }; - d3.csv = d3.dsv(",", "text/csv"); - d3.tsv = d3.dsv(" ", "text/tab-separated-values"); - var d3_timer_queueHead, d3_timer_queueTail, d3_timer_interval, d3_timer_timeout, d3_timer_active, d3_timer_frame = d3_window[d3_vendorSymbol(d3_window, "requestAnimationFrame")] || function(callback) { - setTimeout(callback, 17); - }; - d3.timer = function(callback, delay, then) { - var n = arguments.length; - if (n < 2) delay = 0; - if (n < 3) then = Date.now(); - var time = then + delay, timer = { - c: callback, - t: time, - f: false, - n: null - }; - if (d3_timer_queueTail) d3_timer_queueTail.n = timer; else d3_timer_queueHead = timer; - d3_timer_queueTail = timer; - if (!d3_timer_interval) { - d3_timer_timeout = clearTimeout(d3_timer_timeout); - d3_timer_interval = 1; - d3_timer_frame(d3_timer_step); - } - }; - function d3_timer_step() { - var now = d3_timer_mark(), delay = d3_timer_sweep() - now; - if (delay > 24) { - if (isFinite(delay)) { - clearTimeout(d3_timer_timeout); - d3_timer_timeout = setTimeout(d3_timer_step, delay); - } - d3_timer_interval = 0; - } else { - d3_timer_interval = 1; - d3_timer_frame(d3_timer_step); - } - } - d3.timer.flush = function() { - d3_timer_mark(); - d3_timer_sweep(); - }; - function d3_timer_mark() { - var now = Date.now(); - d3_timer_active = d3_timer_queueHead; - while (d3_timer_active) { - if (now >= d3_timer_active.t) d3_timer_active.f = d3_timer_active.c(now - d3_timer_active.t); - d3_timer_active = d3_timer_active.n; - } - return now; - } - function d3_timer_sweep() { - var t0, t1 = d3_timer_queueHead, time = Infinity; - while (t1) { - if (t1.f) { - t1 = t0 ? t0.n = t1.n : d3_timer_queueHead = t1.n; - } else { - if (t1.t < time) time = t1.t; - t1 = (t0 = t1).n; - } - } - d3_timer_queueTail = t0; - return time; - } - function d3_format_precision(x, p) { - return p - (x ? Math.ceil(Math.log(x) / Math.LN10) : 1); - } - d3.round = function(x, n) { - return n ? Math.round(x * (n = Math.pow(10, n))) / n : Math.round(x); - }; - var d3_formatPrefixes = [ "y", "z", "a", "f", "p", "n", "µ", "m", "", "k", "M", "G", "T", "P", "E", "Z", "Y" ].map(d3_formatPrefix); - d3.formatPrefix = function(value, precision) { - var i = 0; - if (value) { - if (value < 0) value *= -1; - if (precision) value = d3.round(value, d3_format_precision(value, precision)); - i = 1 + Math.floor(1e-12 + Math.log(value) / Math.LN10); - i = Math.max(-24, Math.min(24, Math.floor((i - 1) / 3) * 3)); - } - return d3_formatPrefixes[8 + i / 3]; - }; - function d3_formatPrefix(d, i) { - var k = Math.pow(10, abs(8 - i) * 3); - return { - scale: i > 8 ? function(d) { - return d / k; - } : function(d) { - return d * k; - }, - symbol: d - }; - } - function d3_locale_numberFormat(locale) { - var locale_decimal = locale.decimal, locale_thousands = locale.thousands, locale_grouping = locale.grouping, locale_currency = locale.currency, formatGroup = locale_grouping ? function(value) { - var i = value.length, t = [], j = 0, g = locale_grouping[0]; - while (g > 0 && i > 0) { - t.push(value.substring(i -= g, i + g)); - g = locale_grouping[j = (j + 1) % locale_grouping.length]; - } - return t.reverse().join(locale_thousands); - } : d3_identity; - return function(specifier) { - var match = d3_format_re.exec(specifier), fill = match[1] || " ", align = match[2] || ">", sign = match[3] || "", symbol = match[4] || "", zfill = match[5], width = +match[6], comma = match[7], precision = match[8], type = match[9], scale = 1, prefix = "", suffix = "", integer = false; - if (precision) precision = +precision.substring(1); - if (zfill || fill === "0" && align === "=") { - zfill = fill = "0"; - align = "="; - if (comma) width -= Math.floor((width - 1) / 4); - } - switch (type) { - case "n": - comma = true; - type = "g"; - break; - - case "%": - scale = 100; - suffix = "%"; - type = "f"; - break; - - case "p": - scale = 100; - suffix = "%"; - type = "r"; - break; - - case "b": - case "o": - case "x": - case "X": - if (symbol === "#") prefix = "0" + type.toLowerCase(); - - case "c": - case "d": - integer = true; - precision = 0; - break; - - case "s": - scale = -1; - type = "r"; - break; - } - if (symbol === "$") prefix = locale_currency[0], suffix = locale_currency[1]; - if (type == "r" && !precision) type = "g"; - if (precision != null) { - if (type == "g") precision = Math.max(1, Math.min(21, precision)); else if (type == "e" || type == "f") precision = Math.max(0, Math.min(20, precision)); - } - type = d3_format_types.get(type) || d3_format_typeDefault; - var zcomma = zfill && comma; - return function(value) { - var fullSuffix = suffix; - if (integer && value % 1) return ""; - var negative = value < 0 || value === 0 && 1 / value < 0 ? (value = -value, "-") : sign; - if (scale < 0) { - var unit = d3.formatPrefix(value, precision); - value = unit.scale(value); - fullSuffix = unit.symbol + suffix; - } else { - value *= scale; - } - value = type(value, precision); - var i = value.lastIndexOf("."), before = i < 0 ? value : value.substring(0, i), after = i < 0 ? "" : locale_decimal + value.substring(i + 1); - if (!zfill && comma) before = formatGroup(before); - var length = prefix.length + before.length + after.length + (zcomma ? 0 : negative.length), padding = length < width ? new Array(length = width - length + 1).join(fill) : ""; - if (zcomma) before = formatGroup(padding + before); - negative += prefix; - value = before + after; - return (align === "<" ? negative + value + padding : align === ">" ? padding + negative + value : align === "^" ? padding.substring(0, length >>= 1) + negative + value + padding.substring(length) : negative + (zcomma ? value : padding + value)) + fullSuffix; - }; - }; - } - var d3_format_re = /(?:([^{])?([<>=^]))?([+\- ])?([$#])?(0)?(\d+)?(,)?(\.-?\d+)?([a-z%])?/i; - var d3_format_types = d3.map({ - b: function(x) { - return x.toString(2); - }, - c: function(x) { - return String.fromCharCode(x); - }, - o: function(x) { - return x.toString(8); - }, - x: function(x) { - return x.toString(16); - }, - X: function(x) { - return x.toString(16).toUpperCase(); - }, - g: function(x, p) { - return x.toPrecision(p); - }, - e: function(x, p) { - return x.toExponential(p); - }, - f: function(x, p) { - return x.toFixed(p); - }, - r: function(x, p) { - return (x = d3.round(x, d3_format_precision(x, p))).toFixed(Math.max(0, Math.min(20, d3_format_precision(x * (1 + 1e-15), p)))); - } - }); - function d3_format_typeDefault(x) { - return x + ""; - } - var d3_time = d3.time = {}, d3_date = Date; - function d3_date_utc() { - this._ = new Date(arguments.length > 1 ? Date.UTC.apply(this, arguments) : arguments[0]); - } - d3_date_utc.prototype = { - getDate: function() { - return this._.getUTCDate(); - }, - getDay: function() { - return this._.getUTCDay(); - }, - getFullYear: function() { - return this._.getUTCFullYear(); - }, - getHours: function() { - return this._.getUTCHours(); - }, - getMilliseconds: function() { - return this._.getUTCMilliseconds(); - }, - getMinutes: function() { - return this._.getUTCMinutes(); - }, - getMonth: function() { - return this._.getUTCMonth(); - }, - getSeconds: function() { - return this._.getUTCSeconds(); - }, - getTime: function() { - return this._.getTime(); - }, - getTimezoneOffset: function() { - return 0; - }, - valueOf: function() { - return this._.valueOf(); - }, - setDate: function() { - d3_time_prototype.setUTCDate.apply(this._, arguments); - }, - setDay: function() { - d3_time_prototype.setUTCDay.apply(this._, arguments); - }, - setFullYear: function() { - d3_time_prototype.setUTCFullYear.apply(this._, arguments); - }, - setHours: function() { - d3_time_prototype.setUTCHours.apply(this._, arguments); - }, - setMilliseconds: function() { - d3_time_prototype.setUTCMilliseconds.apply(this._, arguments); - }, - setMinutes: function() { - d3_time_prototype.setUTCMinutes.apply(this._, arguments); - }, - setMonth: function() { - d3_time_prototype.setUTCMonth.apply(this._, arguments); - }, - setSeconds: function() { - d3_time_prototype.setUTCSeconds.apply(this._, arguments); - }, - setTime: function() { - d3_time_prototype.setTime.apply(this._, arguments); - } - }; - var d3_time_prototype = Date.prototype; - function d3_time_interval(local, step, number) { - function round(date) { - var d0 = local(date), d1 = offset(d0, 1); - return date - d0 < d1 - date ? d0 : d1; - } - function ceil(date) { - step(date = local(new d3_date(date - 1)), 1); - return date; - } - function offset(date, k) { - step(date = new d3_date(+date), k); - return date; - } - function range(t0, t1, dt) { - var time = ceil(t0), times = []; - if (dt > 1) { - while (time < t1) { - if (!(number(time) % dt)) times.push(new Date(+time)); - step(time, 1); - } - } else { - while (time < t1) times.push(new Date(+time)), step(time, 1); - } - return times; - } - function range_utc(t0, t1, dt) { - try { - d3_date = d3_date_utc; - var utc = new d3_date_utc(); - utc._ = t0; - return range(utc, t1, dt); - } finally { - d3_date = Date; - } - } - local.floor = local; - local.round = round; - local.ceil = ceil; - local.offset = offset; - local.range = range; - var utc = local.utc = d3_time_interval_utc(local); - utc.floor = utc; - utc.round = d3_time_interval_utc(round); - utc.ceil = d3_time_interval_utc(ceil); - utc.offset = d3_time_interval_utc(offset); - utc.range = range_utc; - return local; - } - function d3_time_interval_utc(method) { - return function(date, k) { - try { - d3_date = d3_date_utc; - var utc = new d3_date_utc(); - utc._ = date; - return method(utc, k)._; - } finally { - d3_date = Date; - } - }; - } - d3_time.year = d3_time_interval(function(date) { - date = d3_time.day(date); - date.setMonth(0, 1); - return date; - }, function(date, offset) { - date.setFullYear(date.getFullYear() + offset); - }, function(date) { - return date.getFullYear(); - }); - d3_time.years = d3_time.year.range; - d3_time.years.utc = d3_time.year.utc.range; - d3_time.day = d3_time_interval(function(date) { - var day = new d3_date(2e3, 0); - day.setFullYear(date.getFullYear(), date.getMonth(), date.getDate()); - return day; - }, function(date, offset) { - date.setDate(date.getDate() + offset); - }, function(date) { - return date.getDate() - 1; - }); - d3_time.days = d3_time.day.range; - d3_time.days.utc = d3_time.day.utc.range; - d3_time.dayOfYear = function(date) { - var year = d3_time.year(date); - return Math.floor((date - year - (date.getTimezoneOffset() - year.getTimezoneOffset()) * 6e4) / 864e5); - }; - [ "sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday" ].forEach(function(day, i) { - i = 7 - i; - var interval = d3_time[day] = d3_time_interval(function(date) { - (date = d3_time.day(date)).setDate(date.getDate() - (date.getDay() + i) % 7); - return date; - }, function(date, offset) { - date.setDate(date.getDate() + Math.floor(offset) * 7); - }, function(date) { - var day = d3_time.year(date).getDay(); - return Math.floor((d3_time.dayOfYear(date) + (day + i) % 7) / 7) - (day !== i); - }); - d3_time[day + "s"] = interval.range; - d3_time[day + "s"].utc = interval.utc.range; - d3_time[day + "OfYear"] = function(date) { - var day = d3_time.year(date).getDay(); - return Math.floor((d3_time.dayOfYear(date) + (day + i) % 7) / 7); - }; - }); - d3_time.week = d3_time.sunday; - d3_time.weeks = d3_time.sunday.range; - d3_time.weeks.utc = d3_time.sunday.utc.range; - d3_time.weekOfYear = d3_time.sundayOfYear; - function d3_locale_timeFormat(locale) { - var locale_dateTime = locale.dateTime, locale_date = locale.date, locale_time = locale.time, locale_periods = locale.periods, locale_days = locale.days, locale_shortDays = locale.shortDays, locale_months = locale.months, locale_shortMonths = locale.shortMonths; - function d3_time_format(template) { - var n = template.length; - function format(date) { - var string = [], i = -1, j = 0, c, p, f; - while (++i < n) { - if (template.charCodeAt(i) === 37) { - string.push(template.slice(j, i)); - if ((p = d3_time_formatPads[c = template.charAt(++i)]) != null) c = template.charAt(++i); - if (f = d3_time_formats[c]) c = f(date, p == null ? c === "e" ? " " : "0" : p); - string.push(c); - j = i + 1; - } - } - string.push(template.slice(j, i)); - return string.join(""); - } - format.parse = function(string) { - var d = { - y: 1900, - m: 0, - d: 1, - H: 0, - M: 0, - S: 0, - L: 0, - Z: null - }, i = d3_time_parse(d, template, string, 0); - if (i != string.length) return null; - if ("p" in d) d.H = d.H % 12 + d.p * 12; - var localZ = d.Z != null && d3_date !== d3_date_utc, date = new (localZ ? d3_date_utc : d3_date)(); - if ("j" in d) date.setFullYear(d.y, 0, d.j); else if ("w" in d && ("W" in d || "U" in d)) { - date.setFullYear(d.y, 0, 1); - date.setFullYear(d.y, 0, "W" in d ? (d.w + 6) % 7 + d.W * 7 - (date.getDay() + 5) % 7 : d.w + d.U * 7 - (date.getDay() + 6) % 7); - } else date.setFullYear(d.y, d.m, d.d); - date.setHours(d.H + (d.Z / 100 | 0), d.M + d.Z % 100, d.S, d.L); - return localZ ? date._ : date; - }; - format.toString = function() { - return template; - }; - return format; - } - function d3_time_parse(date, template, string, j) { - var c, p, t, i = 0, n = template.length, m = string.length; - while (i < n) { - if (j >= m) return -1; - c = template.charCodeAt(i++); - if (c === 37) { - t = template.charAt(i++); - p = d3_time_parsers[t in d3_time_formatPads ? template.charAt(i++) : t]; - if (!p || (j = p(date, string, j)) < 0) return -1; - } else if (c != string.charCodeAt(j++)) { - return -1; - } - } - return j; - } - d3_time_format.utc = function(template) { - var local = d3_time_format(template); - function format(date) { - try { - d3_date = d3_date_utc; - var utc = new d3_date(); - utc._ = date; - return local(utc); - } finally { - d3_date = Date; - } - } - format.parse = function(string) { - try { - d3_date = d3_date_utc; - var date = local.parse(string); - return date && date._; - } finally { - d3_date = Date; - } - }; - format.toString = local.toString; - return format; - }; - d3_time_format.multi = d3_time_format.utc.multi = d3_time_formatMulti; - var d3_time_periodLookup = d3.map(), d3_time_dayRe = d3_time_formatRe(locale_days), d3_time_dayLookup = d3_time_formatLookup(locale_days), d3_time_dayAbbrevRe = d3_time_formatRe(locale_shortDays), d3_time_dayAbbrevLookup = d3_time_formatLookup(locale_shortDays), d3_time_monthRe = d3_time_formatRe(locale_months), d3_time_monthLookup = d3_time_formatLookup(locale_months), d3_time_monthAbbrevRe = d3_time_formatRe(locale_shortMonths), d3_time_monthAbbrevLookup = d3_time_formatLookup(locale_shortMonths); - locale_periods.forEach(function(p, i) { - d3_time_periodLookup.set(p.toLowerCase(), i); - }); - var d3_time_formats = { - a: function(d) { - return locale_shortDays[d.getDay()]; - }, - A: function(d) { - return locale_days[d.getDay()]; - }, - b: function(d) { - return locale_shortMonths[d.getMonth()]; - }, - B: function(d) { - return locale_months[d.getMonth()]; - }, - c: d3_time_format(locale_dateTime), - d: function(d, p) { - return d3_time_formatPad(d.getDate(), p, 2); - }, - e: function(d, p) { - return d3_time_formatPad(d.getDate(), p, 2); - }, - H: function(d, p) { - return d3_time_formatPad(d.getHours(), p, 2); - }, - I: function(d, p) { - return d3_time_formatPad(d.getHours() % 12 || 12, p, 2); - }, - j: function(d, p) { - return d3_time_formatPad(1 + d3_time.dayOfYear(d), p, 3); - }, - L: function(d, p) { - return d3_time_formatPad(d.getMilliseconds(), p, 3); - }, - m: function(d, p) { - return d3_time_formatPad(d.getMonth() + 1, p, 2); - }, - M: function(d, p) { - return d3_time_formatPad(d.getMinutes(), p, 2); - }, - p: function(d) { - return locale_periods[+(d.getHours() >= 12)]; - }, - S: function(d, p) { - return d3_time_formatPad(d.getSeconds(), p, 2); - }, - U: function(d, p) { - return d3_time_formatPad(d3_time.sundayOfYear(d), p, 2); - }, - w: function(d) { - return d.getDay(); - }, - W: function(d, p) { - return d3_time_formatPad(d3_time.mondayOfYear(d), p, 2); - }, - x: d3_time_format(locale_date), - X: d3_time_format(locale_time), - y: function(d, p) { - return d3_time_formatPad(d.getFullYear() % 100, p, 2); - }, - Y: function(d, p) { - return d3_time_formatPad(d.getFullYear() % 1e4, p, 4); - }, - Z: d3_time_zone, - "%": function() { - return "%"; - } - }; - var d3_time_parsers = { - a: d3_time_parseWeekdayAbbrev, - A: d3_time_parseWeekday, - b: d3_time_parseMonthAbbrev, - B: d3_time_parseMonth, - c: d3_time_parseLocaleFull, - d: d3_time_parseDay, - e: d3_time_parseDay, - H: d3_time_parseHour24, - I: d3_time_parseHour24, - j: d3_time_parseDayOfYear, - L: d3_time_parseMilliseconds, - m: d3_time_parseMonthNumber, - M: d3_time_parseMinutes, - p: d3_time_parseAmPm, - S: d3_time_parseSeconds, - U: d3_time_parseWeekNumberSunday, - w: d3_time_parseWeekdayNumber, - W: d3_time_parseWeekNumberMonday, - x: d3_time_parseLocaleDate, - X: d3_time_parseLocaleTime, - y: d3_time_parseYear, - Y: d3_time_parseFullYear, - Z: d3_time_parseZone, - "%": d3_time_parseLiteralPercent - }; - function d3_time_parseWeekdayAbbrev(date, string, i) { - d3_time_dayAbbrevRe.lastIndex = 0; - var n = d3_time_dayAbbrevRe.exec(string.slice(i)); - return n ? (date.w = d3_time_dayAbbrevLookup.get(n[0].toLowerCase()), i + n[0].length) : -1; - } - function d3_time_parseWeekday(date, string, i) { - d3_time_dayRe.lastIndex = 0; - var n = d3_time_dayRe.exec(string.slice(i)); - return n ? (date.w = d3_time_dayLookup.get(n[0].toLowerCase()), i + n[0].length) : -1; - } - function d3_time_parseMonthAbbrev(date, string, i) { - d3_time_monthAbbrevRe.lastIndex = 0; - var n = d3_time_monthAbbrevRe.exec(string.slice(i)); - return n ? (date.m = d3_time_monthAbbrevLookup.get(n[0].toLowerCase()), i + n[0].length) : -1; - } - function d3_time_parseMonth(date, string, i) { - d3_time_monthRe.lastIndex = 0; - var n = d3_time_monthRe.exec(string.slice(i)); - return n ? (date.m = d3_time_monthLookup.get(n[0].toLowerCase()), i + n[0].length) : -1; - } - function d3_time_parseLocaleFull(date, string, i) { - return d3_time_parse(date, d3_time_formats.c.toString(), string, i); - } - function d3_time_parseLocaleDate(date, string, i) { - return d3_time_parse(date, d3_time_formats.x.toString(), string, i); - } - function d3_time_parseLocaleTime(date, string, i) { - return d3_time_parse(date, d3_time_formats.X.toString(), string, i); - } - function d3_time_parseAmPm(date, string, i) { - var n = d3_time_periodLookup.get(string.slice(i, i += 2).toLowerCase()); - return n == null ? -1 : (date.p = n, i); - } - return d3_time_format; - } - var d3_time_formatPads = { - "-": "", - _: " ", - "0": "0" - }, d3_time_numberRe = /^\s*\d+/, d3_time_percentRe = /^%/; - function d3_time_formatPad(value, fill, width) { - var sign = value < 0 ? "-" : "", string = (sign ? -value : value) + "", length = string.length; - return sign + (length < width ? new Array(width - length + 1).join(fill) + string : string); - } - function d3_time_formatRe(names) { - return new RegExp("^(?:" + names.map(d3.requote).join("|") + ")", "i"); - } - function d3_time_formatLookup(names) { - var map = new d3_Map(), i = -1, n = names.length; - while (++i < n) map.set(names[i].toLowerCase(), i); - return map; - } - function d3_time_parseWeekdayNumber(date, string, i) { - d3_time_numberRe.lastIndex = 0; - var n = d3_time_numberRe.exec(string.slice(i, i + 1)); - return n ? (date.w = +n[0], i + n[0].length) : -1; - } - function d3_time_parseWeekNumberSunday(date, string, i) { - d3_time_numberRe.lastIndex = 0; - var n = d3_time_numberRe.exec(string.slice(i)); - return n ? (date.U = +n[0], i + n[0].length) : -1; - } - function d3_time_parseWeekNumberMonday(date, string, i) { - d3_time_numberRe.lastIndex = 0; - var n = d3_time_numberRe.exec(string.slice(i)); - return n ? (date.W = +n[0], i + n[0].length) : -1; - } - function d3_time_parseFullYear(date, string, i) { - d3_time_numberRe.lastIndex = 0; - var n = d3_time_numberRe.exec(string.slice(i, i + 4)); - return n ? (date.y = +n[0], i + n[0].length) : -1; - } - function d3_time_parseYear(date, string, i) { - d3_time_numberRe.lastIndex = 0; - var n = d3_time_numberRe.exec(string.slice(i, i + 2)); - return n ? (date.y = d3_time_expandYear(+n[0]), i + n[0].length) : -1; - } - function d3_time_parseZone(date, string, i) { - return /^[+-]\d{4}$/.test(string = string.slice(i, i + 5)) ? (date.Z = -string, - i + 5) : -1; - } - function d3_time_expandYear(d) { - return d + (d > 68 ? 1900 : 2e3); - } - function d3_time_parseMonthNumber(date, string, i) { - d3_time_numberRe.lastIndex = 0; - var n = d3_time_numberRe.exec(string.slice(i, i + 2)); - return n ? (date.m = n[0] - 1, i + n[0].length) : -1; - } - function d3_time_parseDay(date, string, i) { - d3_time_numberRe.lastIndex = 0; - var n = d3_time_numberRe.exec(string.slice(i, i + 2)); - return n ? (date.d = +n[0], i + n[0].length) : -1; - } - function d3_time_parseDayOfYear(date, string, i) { - d3_time_numberRe.lastIndex = 0; - var n = d3_time_numberRe.exec(string.slice(i, i + 3)); - return n ? (date.j = +n[0], i + n[0].length) : -1; - } - function d3_time_parseHour24(date, string, i) { - d3_time_numberRe.lastIndex = 0; - var n = d3_time_numberRe.exec(string.slice(i, i + 2)); - return n ? (date.H = +n[0], i + n[0].length) : -1; - } - function d3_time_parseMinutes(date, string, i) { - d3_time_numberRe.lastIndex = 0; - var n = d3_time_numberRe.exec(string.slice(i, i + 2)); - return n ? (date.M = +n[0], i + n[0].length) : -1; - } - function d3_time_parseSeconds(date, string, i) { - d3_time_numberRe.lastIndex = 0; - var n = d3_time_numberRe.exec(string.slice(i, i + 2)); - return n ? (date.S = +n[0], i + n[0].length) : -1; - } - function d3_time_parseMilliseconds(date, string, i) { - d3_time_numberRe.lastIndex = 0; - var n = d3_time_numberRe.exec(string.slice(i, i + 3)); - return n ? (date.L = +n[0], i + n[0].length) : -1; - } - function d3_time_zone(d) { - var z = d.getTimezoneOffset(), zs = z > 0 ? "-" : "+", zh = abs(z) / 60 | 0, zm = abs(z) % 60; - return zs + d3_time_formatPad(zh, "0", 2) + d3_time_formatPad(zm, "0", 2); - } - function d3_time_parseLiteralPercent(date, string, i) { - d3_time_percentRe.lastIndex = 0; - var n = d3_time_percentRe.exec(string.slice(i, i + 1)); - return n ? i + n[0].length : -1; - } - function d3_time_formatMulti(formats) { - var n = formats.length, i = -1; - while (++i < n) formats[i][0] = this(formats[i][0]); - return function(date) { - var i = 0, f = formats[i]; - while (!f[1](date)) f = formats[++i]; - return f[0](date); - }; - } - d3.locale = function(locale) { - return { - numberFormat: d3_locale_numberFormat(locale), - timeFormat: d3_locale_timeFormat(locale) - }; - }; - var d3_locale_enUS = d3.locale({ - decimal: ".", - thousands: ",", - grouping: [ 3 ], - currency: [ "$", "" ], - dateTime: "%a %b %e %X %Y", - date: "%m/%d/%Y", - time: "%H:%M:%S", - periods: [ "AM", "PM" ], - days: [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ], - shortDays: [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ], - months: [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ], - shortMonths: [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ] - }); - d3.format = d3_locale_enUS.numberFormat; - d3.geo = {}; - function d3_adder() {} - d3_adder.prototype = { - s: 0, - t: 0, - add: function(y) { - d3_adderSum(y, this.t, d3_adderTemp); - d3_adderSum(d3_adderTemp.s, this.s, this); - if (this.s) this.t += d3_adderTemp.t; else this.s = d3_adderTemp.t; - }, - reset: function() { - this.s = this.t = 0; - }, - valueOf: function() { - return this.s; - } - }; - var d3_adderTemp = new d3_adder(); - function d3_adderSum(a, b, o) { - var x = o.s = a + b, bv = x - a, av = x - bv; - o.t = a - av + (b - bv); - } - d3.geo.stream = function(object, listener) { - if (object && d3_geo_streamObjectType.hasOwnProperty(object.type)) { - d3_geo_streamObjectType[object.type](object, listener); - } else { - d3_geo_streamGeometry(object, listener); - } - }; - function d3_geo_streamGeometry(geometry, listener) { - if (geometry && d3_geo_streamGeometryType.hasOwnProperty(geometry.type)) { - d3_geo_streamGeometryType[geometry.type](geometry, listener); - } - } - var d3_geo_streamObjectType = { - Feature: function(feature, listener) { - d3_geo_streamGeometry(feature.geometry, listener); - }, - FeatureCollection: function(object, listener) { - var features = object.features, i = -1, n = features.length; - while (++i < n) d3_geo_streamGeometry(features[i].geometry, listener); - } - }; - var d3_geo_streamGeometryType = { - Sphere: function(object, listener) { - listener.sphere(); - }, - Point: function(object, listener) { - object = object.coordinates; - listener.point(object[0], object[1], object[2]); - }, - MultiPoint: function(object, listener) { - var coordinates = object.coordinates, i = -1, n = coordinates.length; - while (++i < n) object = coordinates[i], listener.point(object[0], object[1], object[2]); - }, - LineString: function(object, listener) { - d3_geo_streamLine(object.coordinates, listener, 0); - }, - MultiLineString: function(object, listener) { - var coordinates = object.coordinates, i = -1, n = coordinates.length; - while (++i < n) d3_geo_streamLine(coordinates[i], listener, 0); - }, - Polygon: function(object, listener) { - d3_geo_streamPolygon(object.coordinates, listener); - }, - MultiPolygon: function(object, listener) { - var coordinates = object.coordinates, i = -1, n = coordinates.length; - while (++i < n) d3_geo_streamPolygon(coordinates[i], listener); - }, - GeometryCollection: function(object, listener) { - var geometries = object.geometries, i = -1, n = geometries.length; - while (++i < n) d3_geo_streamGeometry(geometries[i], listener); - } - }; - function d3_geo_streamLine(coordinates, listener, closed) { - var i = -1, n = coordinates.length - closed, coordinate; - listener.lineStart(); - while (++i < n) coordinate = coordinates[i], listener.point(coordinate[0], coordinate[1], coordinate[2]); - listener.lineEnd(); - } - function d3_geo_streamPolygon(coordinates, listener) { - var i = -1, n = coordinates.length; - listener.polygonStart(); - while (++i < n) d3_geo_streamLine(coordinates[i], listener, 1); - listener.polygonEnd(); - } - d3.geo.area = function(object) { - d3_geo_areaSum = 0; - d3.geo.stream(object, d3_geo_area); - return d3_geo_areaSum; - }; - var d3_geo_areaSum, d3_geo_areaRingSum = new d3_adder(); - var d3_geo_area = { - sphere: function() { - d3_geo_areaSum += 4 * π; - }, - point: d3_noop, - lineStart: d3_noop, - lineEnd: d3_noop, - polygonStart: function() { - d3_geo_areaRingSum.reset(); - d3_geo_area.lineStart = d3_geo_areaRingStart; - }, - polygonEnd: function() { - var area = 2 * d3_geo_areaRingSum; - d3_geo_areaSum += area < 0 ? 4 * π + area : area; - d3_geo_area.lineStart = d3_geo_area.lineEnd = d3_geo_area.point = d3_noop; - } - }; - function d3_geo_areaRingStart() { - var λ00, φ00, λ0, cosφ0, sinφ0; - d3_geo_area.point = function(λ, φ) { - d3_geo_area.point = nextPoint; - λ0 = (λ00 = λ) * d3_radians, cosφ0 = Math.cos(φ = (φ00 = φ) * d3_radians / 2 + π / 4), - sinφ0 = Math.sin(φ); - }; - function nextPoint(λ, φ) { - λ *= d3_radians; - φ = φ * d3_radians / 2 + π / 4; - var dλ = λ - λ0, sdλ = dλ >= 0 ? 1 : -1, adλ = sdλ * dλ, cosφ = Math.cos(φ), sinφ = Math.sin(φ), k = sinφ0 * sinφ, u = cosφ0 * cosφ + k * Math.cos(adλ), v = k * sdλ * Math.sin(adλ); - d3_geo_areaRingSum.add(Math.atan2(v, u)); - λ0 = λ, cosφ0 = cosφ, sinφ0 = sinφ; - } - d3_geo_area.lineEnd = function() { - nextPoint(λ00, φ00); - }; - } - function d3_geo_cartesian(spherical) { - var λ = spherical[0], φ = spherical[1], cosφ = Math.cos(φ); - return [ cosφ * Math.cos(λ), cosφ * Math.sin(λ), Math.sin(φ) ]; - } - function d3_geo_cartesianDot(a, b) { - return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; - } - function d3_geo_cartesianCross(a, b) { - return [ a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0] ]; - } - function d3_geo_cartesianAdd(a, b) { - a[0] += b[0]; - a[1] += b[1]; - a[2] += b[2]; - } - function d3_geo_cartesianScale(vector, k) { - return [ vector[0] * k, vector[1] * k, vector[2] * k ]; - } - function d3_geo_cartesianNormalize(d) { - var l = Math.sqrt(d[0] * d[0] + d[1] * d[1] + d[2] * d[2]); - d[0] /= l; - d[1] /= l; - d[2] /= l; - } - function d3_geo_spherical(cartesian) { - return [ Math.atan2(cartesian[1], cartesian[0]), d3_asin(cartesian[2]) ]; - } - function d3_geo_sphericalEqual(a, b) { - return abs(a[0] - b[0]) < ε && abs(a[1] - b[1]) < ε; - } - d3.geo.bounds = function() { - var λ0, φ0, λ1, φ1, λ_, λ__, φ__, p0, dλSum, ranges, range; - var bound = { - point: point, - lineStart: lineStart, - lineEnd: lineEnd, - polygonStart: function() { - bound.point = ringPoint; - bound.lineStart = ringStart; - bound.lineEnd = ringEnd; - dλSum = 0; - d3_geo_area.polygonStart(); - }, - polygonEnd: function() { - d3_geo_area.polygonEnd(); - bound.point = point; - bound.lineStart = lineStart; - bound.lineEnd = lineEnd; - if (d3_geo_areaRingSum < 0) λ0 = -(λ1 = 180), φ0 = -(φ1 = 90); else if (dλSum > ε) φ1 = 90; else if (dλSum < -ε) φ0 = -90; - range[0] = λ0, range[1] = λ1; - } - }; - function point(λ, φ) { - ranges.push(range = [ λ0 = λ, λ1 = λ ]); - if (φ < φ0) φ0 = φ; - if (φ > φ1) φ1 = φ; - } - function linePoint(λ, φ) { - var p = d3_geo_cartesian([ λ * d3_radians, φ * d3_radians ]); - if (p0) { - var normal = d3_geo_cartesianCross(p0, p), equatorial = [ normal[1], -normal[0], 0 ], inflection = d3_geo_cartesianCross(equatorial, normal); - d3_geo_cartesianNormalize(inflection); - inflection = d3_geo_spherical(inflection); - var dλ = λ - λ_, s = dλ > 0 ? 1 : -1, λi = inflection[0] * d3_degrees * s, antimeridian = abs(dλ) > 180; - if (antimeridian ^ (s * λ_ < λi && λi < s * λ)) { - var φi = inflection[1] * d3_degrees; - if (φi > φ1) φ1 = φi; - } else if (λi = (λi + 360) % 360 - 180, antimeridian ^ (s * λ_ < λi && λi < s * λ)) { - var φi = -inflection[1] * d3_degrees; - if (φi < φ0) φ0 = φi; - } else { - if (φ < φ0) φ0 = φ; - if (φ > φ1) φ1 = φ; - } - if (antimeridian) { - if (λ < λ_) { - if (angle(λ0, λ) > angle(λ0, λ1)) λ1 = λ; - } else { - if (angle(λ, λ1) > angle(λ0, λ1)) λ0 = λ; - } - } else { - if (λ1 >= λ0) { - if (λ < λ0) λ0 = λ; - if (λ > λ1) λ1 = λ; - } else { - if (λ > λ_) { - if (angle(λ0, λ) > angle(λ0, λ1)) λ1 = λ; - } else { - if (angle(λ, λ1) > angle(λ0, λ1)) λ0 = λ; - } - } - } - } else { - point(λ, φ); - } - p0 = p, λ_ = λ; - } - function lineStart() { - bound.point = linePoint; - } - function lineEnd() { - range[0] = λ0, range[1] = λ1; - bound.point = point; - p0 = null; - } - function ringPoint(λ, φ) { - if (p0) { - var dλ = λ - λ_; - dλSum += abs(dλ) > 180 ? dλ + (dλ > 0 ? 360 : -360) : dλ; - } else λ__ = λ, φ__ = φ; - d3_geo_area.point(λ, φ); - linePoint(λ, φ); - } - function ringStart() { - d3_geo_area.lineStart(); - } - function ringEnd() { - ringPoint(λ__, φ__); - d3_geo_area.lineEnd(); - if (abs(dλSum) > ε) λ0 = -(λ1 = 180); - range[0] = λ0, range[1] = λ1; - p0 = null; - } - function angle(λ0, λ1) { - return (λ1 -= λ0) < 0 ? λ1 + 360 : λ1; - } - function compareRanges(a, b) { - return a[0] - b[0]; - } - function withinRange(x, range) { - return range[0] <= range[1] ? range[0] <= x && x <= range[1] : x < range[0] || range[1] < x; - } - return function(feature) { - φ1 = λ1 = -(λ0 = φ0 = Infinity); - ranges = []; - d3.geo.stream(feature, bound); - var n = ranges.length; - if (n) { - ranges.sort(compareRanges); - for (var i = 1, a = ranges[0], b, merged = [ a ]; i < n; ++i) { - b = ranges[i]; - if (withinRange(b[0], a) || withinRange(b[1], a)) { - if (angle(a[0], b[1]) > angle(a[0], a[1])) a[1] = b[1]; - if (angle(b[0], a[1]) > angle(a[0], a[1])) a[0] = b[0]; - } else { - merged.push(a = b); - } - } - var best = -Infinity, dλ; - for (var n = merged.length - 1, i = 0, a = merged[n], b; i <= n; a = b, ++i) { - b = merged[i]; - if ((dλ = angle(a[1], b[0])) > best) best = dλ, λ0 = b[0], λ1 = a[1]; - } - } - ranges = range = null; - return λ0 === Infinity || φ0 === Infinity ? [ [ NaN, NaN ], [ NaN, NaN ] ] : [ [ λ0, φ0 ], [ λ1, φ1 ] ]; - }; - }(); - d3.geo.centroid = function(object) { - d3_geo_centroidW0 = d3_geo_centroidW1 = d3_geo_centroidX0 = d3_geo_centroidY0 = d3_geo_centroidZ0 = d3_geo_centroidX1 = d3_geo_centroidY1 = d3_geo_centroidZ1 = d3_geo_centroidX2 = d3_geo_centroidY2 = d3_geo_centroidZ2 = 0; - d3.geo.stream(object, d3_geo_centroid); - var x = d3_geo_centroidX2, y = d3_geo_centroidY2, z = d3_geo_centroidZ2, m = x * x + y * y + z * z; - if (m < ε2) { - x = d3_geo_centroidX1, y = d3_geo_centroidY1, z = d3_geo_centroidZ1; - if (d3_geo_centroidW1 < ε) x = d3_geo_centroidX0, y = d3_geo_centroidY0, z = d3_geo_centroidZ0; - m = x * x + y * y + z * z; - if (m < ε2) return [ NaN, NaN ]; - } - return [ Math.atan2(y, x) * d3_degrees, d3_asin(z / Math.sqrt(m)) * d3_degrees ]; - }; - var d3_geo_centroidW0, d3_geo_centroidW1, d3_geo_centroidX0, d3_geo_centroidY0, d3_geo_centroidZ0, d3_geo_centroidX1, d3_geo_centroidY1, d3_geo_centroidZ1, d3_geo_centroidX2, d3_geo_centroidY2, d3_geo_centroidZ2; - var d3_geo_centroid = { - sphere: d3_noop, - point: d3_geo_centroidPoint, - lineStart: d3_geo_centroidLineStart, - lineEnd: d3_geo_centroidLineEnd, - polygonStart: function() { - d3_geo_centroid.lineStart = d3_geo_centroidRingStart; - }, - polygonEnd: function() { - d3_geo_centroid.lineStart = d3_geo_centroidLineStart; - } - }; - function d3_geo_centroidPoint(λ, φ) { - λ *= d3_radians; - var cosφ = Math.cos(φ *= d3_radians); - d3_geo_centroidPointXYZ(cosφ * Math.cos(λ), cosφ * Math.sin(λ), Math.sin(φ)); - } - function d3_geo_centroidPointXYZ(x, y, z) { - ++d3_geo_centroidW0; - d3_geo_centroidX0 += (x - d3_geo_centroidX0) / d3_geo_centroidW0; - d3_geo_centroidY0 += (y - d3_geo_centroidY0) / d3_geo_centroidW0; - d3_geo_centroidZ0 += (z - d3_geo_centroidZ0) / d3_geo_centroidW0; - } - function d3_geo_centroidLineStart() { - var x0, y0, z0; - d3_geo_centroid.point = function(λ, φ) { - λ *= d3_radians; - var cosφ = Math.cos(φ *= d3_radians); - x0 = cosφ * Math.cos(λ); - y0 = cosφ * Math.sin(λ); - z0 = Math.sin(φ); - d3_geo_centroid.point = nextPoint; - d3_geo_centroidPointXYZ(x0, y0, z0); - }; - function nextPoint(λ, φ) { - λ *= d3_radians; - var cosφ = Math.cos(φ *= d3_radians), x = cosφ * Math.cos(λ), y = cosφ * Math.sin(λ), z = Math.sin(φ), w = Math.atan2(Math.sqrt((w = y0 * z - z0 * y) * w + (w = z0 * x - x0 * z) * w + (w = x0 * y - y0 * x) * w), x0 * x + y0 * y + z0 * z); - d3_geo_centroidW1 += w; - d3_geo_centroidX1 += w * (x0 + (x0 = x)); - d3_geo_centroidY1 += w * (y0 + (y0 = y)); - d3_geo_centroidZ1 += w * (z0 + (z0 = z)); - d3_geo_centroidPointXYZ(x0, y0, z0); - } - } - function d3_geo_centroidLineEnd() { - d3_geo_centroid.point = d3_geo_centroidPoint; - } - function d3_geo_centroidRingStart() { - var λ00, φ00, x0, y0, z0; - d3_geo_centroid.point = function(λ, φ) { - λ00 = λ, φ00 = φ; - d3_geo_centroid.point = nextPoint; - λ *= d3_radians; - var cosφ = Math.cos(φ *= d3_radians); - x0 = cosφ * Math.cos(λ); - y0 = cosφ * Math.sin(λ); - z0 = Math.sin(φ); - d3_geo_centroidPointXYZ(x0, y0, z0); - }; - d3_geo_centroid.lineEnd = function() { - nextPoint(λ00, φ00); - d3_geo_centroid.lineEnd = d3_geo_centroidLineEnd; - d3_geo_centroid.point = d3_geo_centroidPoint; - }; - function nextPoint(λ, φ) { - λ *= d3_radians; - var cosφ = Math.cos(φ *= d3_radians), x = cosφ * Math.cos(λ), y = cosφ * Math.sin(λ), z = Math.sin(φ), cx = y0 * z - z0 * y, cy = z0 * x - x0 * z, cz = x0 * y - y0 * x, m = Math.sqrt(cx * cx + cy * cy + cz * cz), u = x0 * x + y0 * y + z0 * z, v = m && -d3_acos(u) / m, w = Math.atan2(m, u); - d3_geo_centroidX2 += v * cx; - d3_geo_centroidY2 += v * cy; - d3_geo_centroidZ2 += v * cz; - d3_geo_centroidW1 += w; - d3_geo_centroidX1 += w * (x0 + (x0 = x)); - d3_geo_centroidY1 += w * (y0 + (y0 = y)); - d3_geo_centroidZ1 += w * (z0 + (z0 = z)); - d3_geo_centroidPointXYZ(x0, y0, z0); - } - } - function d3_true() { - return true; - } - function d3_geo_clipPolygon(segments, compare, clipStartInside, interpolate, listener) { - var subject = [], clip = []; - segments.forEach(function(segment) { - if ((n = segment.length - 1) <= 0) return; - var n, p0 = segment[0], p1 = segment[n]; - if (d3_geo_sphericalEqual(p0, p1)) { - listener.lineStart(); - for (var i = 0; i < n; ++i) listener.point((p0 = segment[i])[0], p0[1]); - listener.lineEnd(); - return; - } - var a = new d3_geo_clipPolygonIntersection(p0, segment, null, true), b = new d3_geo_clipPolygonIntersection(p0, null, a, false); - a.o = b; - subject.push(a); - clip.push(b); - a = new d3_geo_clipPolygonIntersection(p1, segment, null, false); - b = new d3_geo_clipPolygonIntersection(p1, null, a, true); - a.o = b; - subject.push(a); - clip.push(b); - }); - clip.sort(compare); - d3_geo_clipPolygonLinkCircular(subject); - d3_geo_clipPolygonLinkCircular(clip); - if (!subject.length) return; - for (var i = 0, entry = clipStartInside, n = clip.length; i < n; ++i) { - clip[i].e = entry = !entry; - } - var start = subject[0], points, point; - while (1) { - var current = start, isSubject = true; - while (current.v) if ((current = current.n) === start) return; - points = current.z; - listener.lineStart(); - do { - current.v = current.o.v = true; - if (current.e) { - if (isSubject) { - for (var i = 0, n = points.length; i < n; ++i) listener.point((point = points[i])[0], point[1]); - } else { - interpolate(current.x, current.n.x, 1, listener); - } - current = current.n; - } else { - if (isSubject) { - points = current.p.z; - for (var i = points.length - 1; i >= 0; --i) listener.point((point = points[i])[0], point[1]); - } else { - interpolate(current.x, current.p.x, -1, listener); - } - current = current.p; - } - current = current.o; - points = current.z; - isSubject = !isSubject; - } while (!current.v); - listener.lineEnd(); - } - } - function d3_geo_clipPolygonLinkCircular(array) { - if (!(n = array.length)) return; - var n, i = 0, a = array[0], b; - while (++i < n) { - a.n = b = array[i]; - b.p = a; - a = b; - } - a.n = b = array[0]; - b.p = a; - } - function d3_geo_clipPolygonIntersection(point, points, other, entry) { - this.x = point; - this.z = points; - this.o = other; - this.e = entry; - this.v = false; - this.n = this.p = null; - } - function d3_geo_clip(pointVisible, clipLine, interpolate, clipStart) { - return function(rotate, listener) { - var line = clipLine(listener), rotatedClipStart = rotate.invert(clipStart[0], clipStart[1]); - var clip = { - point: point, - lineStart: lineStart, - lineEnd: lineEnd, - polygonStart: function() { - clip.point = pointRing; - clip.lineStart = ringStart; - clip.lineEnd = ringEnd; - segments = []; - polygon = []; - }, - polygonEnd: function() { - clip.point = point; - clip.lineStart = lineStart; - clip.lineEnd = lineEnd; - segments = d3.merge(segments); - var clipStartInside = d3_geo_pointInPolygon(rotatedClipStart, polygon); - if (segments.length) { - if (!polygonStarted) listener.polygonStart(), polygonStarted = true; - d3_geo_clipPolygon(segments, d3_geo_clipSort, clipStartInside, interpolate, listener); - } else if (clipStartInside) { - if (!polygonStarted) listener.polygonStart(), polygonStarted = true; - listener.lineStart(); - interpolate(null, null, 1, listener); - listener.lineEnd(); - } - if (polygonStarted) listener.polygonEnd(), polygonStarted = false; - segments = polygon = null; - }, - sphere: function() { - listener.polygonStart(); - listener.lineStart(); - interpolate(null, null, 1, listener); - listener.lineEnd(); - listener.polygonEnd(); - } - }; - function point(λ, φ) { - var point = rotate(λ, φ); - if (pointVisible(λ = point[0], φ = point[1])) listener.point(λ, φ); - } - function pointLine(λ, φ) { - var point = rotate(λ, φ); - line.point(point[0], point[1]); - } - function lineStart() { - clip.point = pointLine; - line.lineStart(); - } - function lineEnd() { - clip.point = point; - line.lineEnd(); - } - var segments; - var buffer = d3_geo_clipBufferListener(), ringListener = clipLine(buffer), polygonStarted = false, polygon, ring; - function pointRing(λ, φ) { - ring.push([ λ, φ ]); - var point = rotate(λ, φ); - ringListener.point(point[0], point[1]); - } - function ringStart() { - ringListener.lineStart(); - ring = []; - } - function ringEnd() { - pointRing(ring[0][0], ring[0][1]); - ringListener.lineEnd(); - var clean = ringListener.clean(), ringSegments = buffer.buffer(), segment, n = ringSegments.length; - ring.pop(); - polygon.push(ring); - ring = null; - if (!n) return; - if (clean & 1) { - segment = ringSegments[0]; - var n = segment.length - 1, i = -1, point; - if (n > 0) { - if (!polygonStarted) listener.polygonStart(), polygonStarted = true; - listener.lineStart(); - while (++i < n) listener.point((point = segment[i])[0], point[1]); - listener.lineEnd(); - } - return; - } - if (n > 1 && clean & 2) ringSegments.push(ringSegments.pop().concat(ringSegments.shift())); - segments.push(ringSegments.filter(d3_geo_clipSegmentLength1)); - } - return clip; - }; - } - function d3_geo_clipSegmentLength1(segment) { - return segment.length > 1; - } - function d3_geo_clipBufferListener() { - var lines = [], line; - return { - lineStart: function() { - lines.push(line = []); - }, - point: function(λ, φ) { - line.push([ λ, φ ]); - }, - lineEnd: d3_noop, - buffer: function() { - var buffer = lines; - lines = []; - line = null; - return buffer; - }, - rejoin: function() { - if (lines.length > 1) lines.push(lines.pop().concat(lines.shift())); - } - }; - } - function d3_geo_clipSort(a, b) { - return ((a = a.x)[0] < 0 ? a[1] - halfπ - ε : halfπ - a[1]) - ((b = b.x)[0] < 0 ? b[1] - halfπ - ε : halfπ - b[1]); - } - var d3_geo_clipAntimeridian = d3_geo_clip(d3_true, d3_geo_clipAntimeridianLine, d3_geo_clipAntimeridianInterpolate, [ -π, -π / 2 ]); - function d3_geo_clipAntimeridianLine(listener) { - var λ0 = NaN, φ0 = NaN, sλ0 = NaN, clean; - return { - lineStart: function() { - listener.lineStart(); - clean = 1; - }, - point: function(λ1, φ1) { - var sλ1 = λ1 > 0 ? π : -π, dλ = abs(λ1 - λ0); - if (abs(dλ - π) < ε) { - listener.point(λ0, φ0 = (φ0 + φ1) / 2 > 0 ? halfπ : -halfπ); - listener.point(sλ0, φ0); - listener.lineEnd(); - listener.lineStart(); - listener.point(sλ1, φ0); - listener.point(λ1, φ0); - clean = 0; - } else if (sλ0 !== sλ1 && dλ >= π) { - if (abs(λ0 - sλ0) < ε) λ0 -= sλ0 * ε; - if (abs(λ1 - sλ1) < ε) λ1 -= sλ1 * ε; - φ0 = d3_geo_clipAntimeridianIntersect(λ0, φ0, λ1, φ1); - listener.point(sλ0, φ0); - listener.lineEnd(); - listener.lineStart(); - listener.point(sλ1, φ0); - clean = 0; - } - listener.point(λ0 = λ1, φ0 = φ1); - sλ0 = sλ1; - }, - lineEnd: function() { - listener.lineEnd(); - λ0 = φ0 = NaN; - }, - clean: function() { - return 2 - clean; - } - }; - } - function d3_geo_clipAntimeridianIntersect(λ0, φ0, λ1, φ1) { - var cosφ0, cosφ1, sinλ0_λ1 = Math.sin(λ0 - λ1); - return abs(sinλ0_λ1) > ε ? Math.atan((Math.sin(φ0) * (cosφ1 = Math.cos(φ1)) * Math.sin(λ1) - Math.sin(φ1) * (cosφ0 = Math.cos(φ0)) * Math.sin(λ0)) / (cosφ0 * cosφ1 * sinλ0_λ1)) : (φ0 + φ1) / 2; - } - function d3_geo_clipAntimeridianInterpolate(from, to, direction, listener) { - var φ; - if (from == null) { - φ = direction * halfπ; - listener.point(-π, φ); - listener.point(0, φ); - listener.point(π, φ); - listener.point(π, 0); - listener.point(π, -φ); - listener.point(0, -φ); - listener.point(-π, -φ); - listener.point(-π, 0); - listener.point(-π, φ); - } else if (abs(from[0] - to[0]) > ε) { - var s = from[0] < to[0] ? π : -π; - φ = direction * s / 2; - listener.point(-s, φ); - listener.point(0, φ); - listener.point(s, φ); - } else { - listener.point(to[0], to[1]); - } - } - function d3_geo_pointInPolygon(point, polygon) { - var meridian = point[0], parallel = point[1], meridianNormal = [ Math.sin(meridian), -Math.cos(meridian), 0 ], polarAngle = 0, winding = 0; - d3_geo_areaRingSum.reset(); - for (var i = 0, n = polygon.length; i < n; ++i) { - var ring = polygon[i], m = ring.length; - if (!m) continue; - var point0 = ring[0], λ0 = point0[0], φ0 = point0[1] / 2 + π / 4, sinφ0 = Math.sin(φ0), cosφ0 = Math.cos(φ0), j = 1; - while (true) { - if (j === m) j = 0; - point = ring[j]; - var λ = point[0], φ = point[1] / 2 + π / 4, sinφ = Math.sin(φ), cosφ = Math.cos(φ), dλ = λ - λ0, sdλ = dλ >= 0 ? 1 : -1, adλ = sdλ * dλ, antimeridian = adλ > π, k = sinφ0 * sinφ; - d3_geo_areaRingSum.add(Math.atan2(k * sdλ * Math.sin(adλ), cosφ0 * cosφ + k * Math.cos(adλ))); - polarAngle += antimeridian ? dλ + sdλ * τ : dλ; - if (antimeridian ^ λ0 >= meridian ^ λ >= meridian) { - var arc = d3_geo_cartesianCross(d3_geo_cartesian(point0), d3_geo_cartesian(point)); - d3_geo_cartesianNormalize(arc); - var intersection = d3_geo_cartesianCross(meridianNormal, arc); - d3_geo_cartesianNormalize(intersection); - var φarc = (antimeridian ^ dλ >= 0 ? -1 : 1) * d3_asin(intersection[2]); - if (parallel > φarc || parallel === φarc && (arc[0] || arc[1])) { - winding += antimeridian ^ dλ >= 0 ? 1 : -1; - } - } - if (!j++) break; - λ0 = λ, sinφ0 = sinφ, cosφ0 = cosφ, point0 = point; - } - } - return (polarAngle < -ε || polarAngle < ε && d3_geo_areaRingSum < 0) ^ winding & 1; - } - function d3_geo_clipCircle(radius) { - var cr = Math.cos(radius), smallRadius = cr > 0, notHemisphere = abs(cr) > ε, interpolate = d3_geo_circleInterpolate(radius, 6 * d3_radians); - return d3_geo_clip(visible, clipLine, interpolate, smallRadius ? [ 0, -radius ] : [ -π, radius - π ]); - function visible(λ, φ) { - return Math.cos(λ) * Math.cos(φ) > cr; - } - function clipLine(listener) { - var point0, c0, v0, v00, clean; - return { - lineStart: function() { - v00 = v0 = false; - clean = 1; - }, - point: function(λ, φ) { - var point1 = [ λ, φ ], point2, v = visible(λ, φ), c = smallRadius ? v ? 0 : code(λ, φ) : v ? code(λ + (λ < 0 ? π : -π), φ) : 0; - if (!point0 && (v00 = v0 = v)) listener.lineStart(); - if (v !== v0) { - point2 = intersect(point0, point1); - if (d3_geo_sphericalEqual(point0, point2) || d3_geo_sphericalEqual(point1, point2)) { - point1[0] += ε; - point1[1] += ε; - v = visible(point1[0], point1[1]); - } - } - if (v !== v0) { - clean = 0; - if (v) { - listener.lineStart(); - point2 = intersect(point1, point0); - listener.point(point2[0], point2[1]); - } else { - point2 = intersect(point0, point1); - listener.point(point2[0], point2[1]); - listener.lineEnd(); - } - point0 = point2; - } else if (notHemisphere && point0 && smallRadius ^ v) { - var t; - if (!(c & c0) && (t = intersect(point1, point0, true))) { - clean = 0; - if (smallRadius) { - listener.lineStart(); - listener.point(t[0][0], t[0][1]); - listener.point(t[1][0], t[1][1]); - listener.lineEnd(); - } else { - listener.point(t[1][0], t[1][1]); - listener.lineEnd(); - listener.lineStart(); - listener.point(t[0][0], t[0][1]); - } - } - } - if (v && (!point0 || !d3_geo_sphericalEqual(point0, point1))) { - listener.point(point1[0], point1[1]); - } - point0 = point1, v0 = v, c0 = c; - }, - lineEnd: function() { - if (v0) listener.lineEnd(); - point0 = null; - }, - clean: function() { - return clean | (v00 && v0) << 1; - } - }; - } - function intersect(a, b, two) { - var pa = d3_geo_cartesian(a), pb = d3_geo_cartesian(b); - var n1 = [ 1, 0, 0 ], n2 = d3_geo_cartesianCross(pa, pb), n2n2 = d3_geo_cartesianDot(n2, n2), n1n2 = n2[0], determinant = n2n2 - n1n2 * n1n2; - if (!determinant) return !two && a; - var c1 = cr * n2n2 / determinant, c2 = -cr * n1n2 / determinant, n1xn2 = d3_geo_cartesianCross(n1, n2), A = d3_geo_cartesianScale(n1, c1), B = d3_geo_cartesianScale(n2, c2); - d3_geo_cartesianAdd(A, B); - var u = n1xn2, w = d3_geo_cartesianDot(A, u), uu = d3_geo_cartesianDot(u, u), t2 = w * w - uu * (d3_geo_cartesianDot(A, A) - 1); - if (t2 < 0) return; - var t = Math.sqrt(t2), q = d3_geo_cartesianScale(u, (-w - t) / uu); - d3_geo_cartesianAdd(q, A); - q = d3_geo_spherical(q); - if (!two) return q; - var λ0 = a[0], λ1 = b[0], φ0 = a[1], φ1 = b[1], z; - if (λ1 < λ0) z = λ0, λ0 = λ1, λ1 = z; - var δλ = λ1 - λ0, polar = abs(δλ - π) < ε, meridian = polar || δλ < ε; - if (!polar && φ1 < φ0) z = φ0, φ0 = φ1, φ1 = z; - if (meridian ? polar ? φ0 + φ1 > 0 ^ q[1] < (abs(q[0] - λ0) < ε ? φ0 : φ1) : φ0 <= q[1] && q[1] <= φ1 : δλ > π ^ (λ0 <= q[0] && q[0] <= λ1)) { - var q1 = d3_geo_cartesianScale(u, (-w + t) / uu); - d3_geo_cartesianAdd(q1, A); - return [ q, d3_geo_spherical(q1) ]; - } - } - function code(λ, φ) { - var r = smallRadius ? radius : π - radius, code = 0; - if (λ < -r) code |= 1; else if (λ > r) code |= 2; - if (φ < -r) code |= 4; else if (φ > r) code |= 8; - return code; - } - } - function d3_geom_clipLine(x0, y0, x1, y1) { - return function(line) { - var a = line.a, b = line.b, ax = a.x, ay = a.y, bx = b.x, by = b.y, t0 = 0, t1 = 1, dx = bx - ax, dy = by - ay, r; - r = x0 - ax; - if (!dx && r > 0) return; - r /= dx; - if (dx < 0) { - if (r < t0) return; - if (r < t1) t1 = r; - } else if (dx > 0) { - if (r > t1) return; - if (r > t0) t0 = r; - } - r = x1 - ax; - if (!dx && r < 0) return; - r /= dx; - if (dx < 0) { - if (r > t1) return; - if (r > t0) t0 = r; - } else if (dx > 0) { - if (r < t0) return; - if (r < t1) t1 = r; - } - r = y0 - ay; - if (!dy && r > 0) return; - r /= dy; - if (dy < 0) { - if (r < t0) return; - if (r < t1) t1 = r; - } else if (dy > 0) { - if (r > t1) return; - if (r > t0) t0 = r; - } - r = y1 - ay; - if (!dy && r < 0) return; - r /= dy; - if (dy < 0) { - if (r > t1) return; - if (r > t0) t0 = r; - } else if (dy > 0) { - if (r < t0) return; - if (r < t1) t1 = r; - } - if (t0 > 0) line.a = { - x: ax + t0 * dx, - y: ay + t0 * dy - }; - if (t1 < 1) line.b = { - x: ax + t1 * dx, - y: ay + t1 * dy - }; - return line; - }; - } - var d3_geo_clipExtentMAX = 1e9; - d3.geo.clipExtent = function() { - var x0, y0, x1, y1, stream, clip, clipExtent = { - stream: function(output) { - if (stream) stream.valid = false; - stream = clip(output); - stream.valid = true; - return stream; - }, - extent: function(_) { - if (!arguments.length) return [ [ x0, y0 ], [ x1, y1 ] ]; - clip = d3_geo_clipExtent(x0 = +_[0][0], y0 = +_[0][1], x1 = +_[1][0], y1 = +_[1][1]); - if (stream) stream.valid = false, stream = null; - return clipExtent; - } - }; - return clipExtent.extent([ [ 0, 0 ], [ 960, 500 ] ]); - }; - function d3_geo_clipExtent(x0, y0, x1, y1) { - return function(listener) { - var listener_ = listener, bufferListener = d3_geo_clipBufferListener(), clipLine = d3_geom_clipLine(x0, y0, x1, y1), segments, polygon, ring; - var clip = { - point: point, - lineStart: lineStart, - lineEnd: lineEnd, - polygonStart: function() { - listener = bufferListener; - segments = []; - polygon = []; - clean = true; - }, - polygonEnd: function() { - listener = listener_; - segments = d3.merge(segments); - var clipStartInside = insidePolygon([ x0, y1 ]), inside = clean && clipStartInside, visible = segments.length; - if (inside || visible) { - listener.polygonStart(); - if (inside) { - listener.lineStart(); - interpolate(null, null, 1, listener); - listener.lineEnd(); - } - if (visible) { - d3_geo_clipPolygon(segments, compare, clipStartInside, interpolate, listener); - } - listener.polygonEnd(); - } - segments = polygon = ring = null; - } - }; - function insidePolygon(p) { - var wn = 0, n = polygon.length, y = p[1]; - for (var i = 0; i < n; ++i) { - for (var j = 1, v = polygon[i], m = v.length, a = v[0], b; j < m; ++j) { - b = v[j]; - if (a[1] <= y) { - if (b[1] > y && d3_cross2d(a, b, p) > 0) ++wn; - } else { - if (b[1] <= y && d3_cross2d(a, b, p) < 0) --wn; - } - a = b; - } - } - return wn !== 0; - } - function interpolate(from, to, direction, listener) { - var a = 0, a1 = 0; - if (from == null || (a = corner(from, direction)) !== (a1 = corner(to, direction)) || comparePoints(from, to) < 0 ^ direction > 0) { - do { - listener.point(a === 0 || a === 3 ? x0 : x1, a > 1 ? y1 : y0); - } while ((a = (a + direction + 4) % 4) !== a1); - } else { - listener.point(to[0], to[1]); - } - } - function pointVisible(x, y) { - return x0 <= x && x <= x1 && y0 <= y && y <= y1; - } - function point(x, y) { - if (pointVisible(x, y)) listener.point(x, y); - } - var x__, y__, v__, x_, y_, v_, first, clean; - function lineStart() { - clip.point = linePoint; - if (polygon) polygon.push(ring = []); - first = true; - v_ = false; - x_ = y_ = NaN; - } - function lineEnd() { - if (segments) { - linePoint(x__, y__); - if (v__ && v_) bufferListener.rejoin(); - segments.push(bufferListener.buffer()); - } - clip.point = point; - if (v_) listener.lineEnd(); - } - function linePoint(x, y) { - x = Math.max(-d3_geo_clipExtentMAX, Math.min(d3_geo_clipExtentMAX, x)); - y = Math.max(-d3_geo_clipExtentMAX, Math.min(d3_geo_clipExtentMAX, y)); - var v = pointVisible(x, y); - if (polygon) ring.push([ x, y ]); - if (first) { - x__ = x, y__ = y, v__ = v; - first = false; - if (v) { - listener.lineStart(); - listener.point(x, y); - } - } else { - if (v && v_) listener.point(x, y); else { - var l = { - a: { - x: x_, - y: y_ - }, - b: { - x: x, - y: y - } - }; - if (clipLine(l)) { - if (!v_) { - listener.lineStart(); - listener.point(l.a.x, l.a.y); - } - listener.point(l.b.x, l.b.y); - if (!v) listener.lineEnd(); - clean = false; - } else if (v) { - listener.lineStart(); - listener.point(x, y); - clean = false; - } - } - } - x_ = x, y_ = y, v_ = v; - } - return clip; - }; - function corner(p, direction) { - return abs(p[0] - x0) < ε ? direction > 0 ? 0 : 3 : abs(p[0] - x1) < ε ? direction > 0 ? 2 : 1 : abs(p[1] - y0) < ε ? direction > 0 ? 1 : 0 : direction > 0 ? 3 : 2; - } - function compare(a, b) { - return comparePoints(a.x, b.x); - } - function comparePoints(a, b) { - var ca = corner(a, 1), cb = corner(b, 1); - return ca !== cb ? ca - cb : ca === 0 ? b[1] - a[1] : ca === 1 ? a[0] - b[0] : ca === 2 ? a[1] - b[1] : b[0] - a[0]; - } - } - function d3_geo_compose(a, b) { - function compose(x, y) { - return x = a(x, y), b(x[0], x[1]); - } - if (a.invert && b.invert) compose.invert = function(x, y) { - return x = b.invert(x, y), x && a.invert(x[0], x[1]); - }; - return compose; - } - function d3_geo_conic(projectAt) { - var φ0 = 0, φ1 = π / 3, m = d3_geo_projectionMutator(projectAt), p = m(φ0, φ1); - p.parallels = function(_) { - if (!arguments.length) return [ φ0 / π * 180, φ1 / π * 180 ]; - return m(φ0 = _[0] * π / 180, φ1 = _[1] * π / 180); - }; - return p; - } - function d3_geo_conicEqualArea(φ0, φ1) { - var sinφ0 = Math.sin(φ0), n = (sinφ0 + Math.sin(φ1)) / 2, C = 1 + sinφ0 * (2 * n - sinφ0), ρ0 = Math.sqrt(C) / n; - function forward(λ, φ) { - var ρ = Math.sqrt(C - 2 * n * Math.sin(φ)) / n; - return [ ρ * Math.sin(λ *= n), ρ0 - ρ * Math.cos(λ) ]; - } - forward.invert = function(x, y) { - var ρ0_y = ρ0 - y; - return [ Math.atan2(x, ρ0_y) / n, d3_asin((C - (x * x + ρ0_y * ρ0_y) * n * n) / (2 * n)) ]; - }; - return forward; - } - (d3.geo.conicEqualArea = function() { - return d3_geo_conic(d3_geo_conicEqualArea); - }).raw = d3_geo_conicEqualArea; - d3.geo.albers = function() { - return d3.geo.conicEqualArea().rotate([ 96, 0 ]).center([ -.6, 38.7 ]).parallels([ 29.5, 45.5 ]).scale(1070); - }; - d3.geo.albersUsa = function() { - var lower48 = d3.geo.albers(); - var alaska = d3.geo.conicEqualArea().rotate([ 154, 0 ]).center([ -2, 58.5 ]).parallels([ 55, 65 ]); - var hawaii = d3.geo.conicEqualArea().rotate([ 157, 0 ]).center([ -3, 19.9 ]).parallels([ 8, 18 ]); - var point, pointStream = { - point: function(x, y) { - point = [ x, y ]; - } - }, lower48Point, alaskaPoint, hawaiiPoint; - function albersUsa(coordinates) { - var x = coordinates[0], y = coordinates[1]; - point = null; - (lower48Point(x, y), point) || (alaskaPoint(x, y), point) || hawaiiPoint(x, y); - return point; - } - albersUsa.invert = function(coordinates) { - var k = lower48.scale(), t = lower48.translate(), x = (coordinates[0] - t[0]) / k, y = (coordinates[1] - t[1]) / k; - return (y >= .12 && y < .234 && x >= -.425 && x < -.214 ? alaska : y >= .166 && y < .234 && x >= -.214 && x < -.115 ? hawaii : lower48).invert(coordinates); - }; - albersUsa.stream = function(stream) { - var lower48Stream = lower48.stream(stream), alaskaStream = alaska.stream(stream), hawaiiStream = hawaii.stream(stream); - return { - point: function(x, y) { - lower48Stream.point(x, y); - alaskaStream.point(x, y); - hawaiiStream.point(x, y); - }, - sphere: function() { - lower48Stream.sphere(); - alaskaStream.sphere(); - hawaiiStream.sphere(); - }, - lineStart: function() { - lower48Stream.lineStart(); - alaskaStream.lineStart(); - hawaiiStream.lineStart(); - }, - lineEnd: function() { - lower48Stream.lineEnd(); - alaskaStream.lineEnd(); - hawaiiStream.lineEnd(); - }, - polygonStart: function() { - lower48Stream.polygonStart(); - alaskaStream.polygonStart(); - hawaiiStream.polygonStart(); - }, - polygonEnd: function() { - lower48Stream.polygonEnd(); - alaskaStream.polygonEnd(); - hawaiiStream.polygonEnd(); - } - }; - }; - albersUsa.precision = function(_) { - if (!arguments.length) return lower48.precision(); - lower48.precision(_); - alaska.precision(_); - hawaii.precision(_); - return albersUsa; - }; - albersUsa.scale = function(_) { - if (!arguments.length) return lower48.scale(); - lower48.scale(_); - alaska.scale(_ * .35); - hawaii.scale(_); - return albersUsa.translate(lower48.translate()); - }; - albersUsa.translate = function(_) { - if (!arguments.length) return lower48.translate(); - var k = lower48.scale(), x = +_[0], y = +_[1]; - lower48Point = lower48.translate(_).clipExtent([ [ x - .455 * k, y - .238 * k ], [ x + .455 * k, y + .238 * k ] ]).stream(pointStream).point; - alaskaPoint = alaska.translate([ x - .307 * k, y + .201 * k ]).clipExtent([ [ x - .425 * k + ε, y + .12 * k + ε ], [ x - .214 * k - ε, y + .234 * k - ε ] ]).stream(pointStream).point; - hawaiiPoint = hawaii.translate([ x - .205 * k, y + .212 * k ]).clipExtent([ [ x - .214 * k + ε, y + .166 * k + ε ], [ x - .115 * k - ε, y + .234 * k - ε ] ]).stream(pointStream).point; - return albersUsa; - }; - return albersUsa.scale(1070); - }; - var d3_geo_pathAreaSum, d3_geo_pathAreaPolygon, d3_geo_pathArea = { - point: d3_noop, - lineStart: d3_noop, - lineEnd: d3_noop, - polygonStart: function() { - d3_geo_pathAreaPolygon = 0; - d3_geo_pathArea.lineStart = d3_geo_pathAreaRingStart; - }, - polygonEnd: function() { - d3_geo_pathArea.lineStart = d3_geo_pathArea.lineEnd = d3_geo_pathArea.point = d3_noop; - d3_geo_pathAreaSum += abs(d3_geo_pathAreaPolygon / 2); - } - }; - function d3_geo_pathAreaRingStart() { - var x00, y00, x0, y0; - d3_geo_pathArea.point = function(x, y) { - d3_geo_pathArea.point = nextPoint; - x00 = x0 = x, y00 = y0 = y; - }; - function nextPoint(x, y) { - d3_geo_pathAreaPolygon += y0 * x - x0 * y; - x0 = x, y0 = y; - } - d3_geo_pathArea.lineEnd = function() { - nextPoint(x00, y00); - }; - } - var d3_geo_pathBoundsX0, d3_geo_pathBoundsY0, d3_geo_pathBoundsX1, d3_geo_pathBoundsY1; - var d3_geo_pathBounds = { - point: d3_geo_pathBoundsPoint, - lineStart: d3_noop, - lineEnd: d3_noop, - polygonStart: d3_noop, - polygonEnd: d3_noop - }; - function d3_geo_pathBoundsPoint(x, y) { - if (x < d3_geo_pathBoundsX0) d3_geo_pathBoundsX0 = x; - if (x > d3_geo_pathBoundsX1) d3_geo_pathBoundsX1 = x; - if (y < d3_geo_pathBoundsY0) d3_geo_pathBoundsY0 = y; - if (y > d3_geo_pathBoundsY1) d3_geo_pathBoundsY1 = y; - } - function d3_geo_pathBuffer() { - var pointCircle = d3_geo_pathBufferCircle(4.5), buffer = []; - var stream = { - point: point, - lineStart: function() { - stream.point = pointLineStart; - }, - lineEnd: lineEnd, - polygonStart: function() { - stream.lineEnd = lineEndPolygon; - }, - polygonEnd: function() { - stream.lineEnd = lineEnd; - stream.point = point; - }, - pointRadius: function(_) { - pointCircle = d3_geo_pathBufferCircle(_); - return stream; - }, - result: function() { - if (buffer.length) { - var result = buffer.join(""); - buffer = []; - return result; - } - } - }; - function point(x, y) { - buffer.push("M", x, ",", y, pointCircle); - } - function pointLineStart(x, y) { - buffer.push("M", x, ",", y); - stream.point = pointLine; - } - function pointLine(x, y) { - buffer.push("L", x, ",", y); - } - function lineEnd() { - stream.point = point; - } - function lineEndPolygon() { - buffer.push("Z"); - } - return stream; - } - function d3_geo_pathBufferCircle(radius) { - return "m0," + radius + "a" + radius + "," + radius + " 0 1,1 0," + -2 * radius + "a" + radius + "," + radius + " 0 1,1 0," + 2 * radius + "z"; - } - var d3_geo_pathCentroid = { - point: d3_geo_pathCentroidPoint, - lineStart: d3_geo_pathCentroidLineStart, - lineEnd: d3_geo_pathCentroidLineEnd, - polygonStart: function() { - d3_geo_pathCentroid.lineStart = d3_geo_pathCentroidRingStart; - }, - polygonEnd: function() { - d3_geo_pathCentroid.point = d3_geo_pathCentroidPoint; - d3_geo_pathCentroid.lineStart = d3_geo_pathCentroidLineStart; - d3_geo_pathCentroid.lineEnd = d3_geo_pathCentroidLineEnd; - } - }; - function d3_geo_pathCentroidPoint(x, y) { - d3_geo_centroidX0 += x; - d3_geo_centroidY0 += y; - ++d3_geo_centroidZ0; - } - function d3_geo_pathCentroidLineStart() { - var x0, y0; - d3_geo_pathCentroid.point = function(x, y) { - d3_geo_pathCentroid.point = nextPoint; - d3_geo_pathCentroidPoint(x0 = x, y0 = y); - }; - function nextPoint(x, y) { - var dx = x - x0, dy = y - y0, z = Math.sqrt(dx * dx + dy * dy); - d3_geo_centroidX1 += z * (x0 + x) / 2; - d3_geo_centroidY1 += z * (y0 + y) / 2; - d3_geo_centroidZ1 += z; - d3_geo_pathCentroidPoint(x0 = x, y0 = y); - } - } - function d3_geo_pathCentroidLineEnd() { - d3_geo_pathCentroid.point = d3_geo_pathCentroidPoint; - } - function d3_geo_pathCentroidRingStart() { - var x00, y00, x0, y0; - d3_geo_pathCentroid.point = function(x, y) { - d3_geo_pathCentroid.point = nextPoint; - d3_geo_pathCentroidPoint(x00 = x0 = x, y00 = y0 = y); - }; - function nextPoint(x, y) { - var dx = x - x0, dy = y - y0, z = Math.sqrt(dx * dx + dy * dy); - d3_geo_centroidX1 += z * (x0 + x) / 2; - d3_geo_centroidY1 += z * (y0 + y) / 2; - d3_geo_centroidZ1 += z; - z = y0 * x - x0 * y; - d3_geo_centroidX2 += z * (x0 + x); - d3_geo_centroidY2 += z * (y0 + y); - d3_geo_centroidZ2 += z * 3; - d3_geo_pathCentroidPoint(x0 = x, y0 = y); - } - d3_geo_pathCentroid.lineEnd = function() { - nextPoint(x00, y00); - }; - } - function d3_geo_pathContext(context) { - var pointRadius = 4.5; - var stream = { - point: point, - lineStart: function() { - stream.point = pointLineStart; - }, - lineEnd: lineEnd, - polygonStart: function() { - stream.lineEnd = lineEndPolygon; - }, - polygonEnd: function() { - stream.lineEnd = lineEnd; - stream.point = point; - }, - pointRadius: function(_) { - pointRadius = _; - return stream; - }, - result: d3_noop - }; - function point(x, y) { - context.moveTo(x, y); - context.arc(x, y, pointRadius, 0, τ); - } - function pointLineStart(x, y) { - context.moveTo(x, y); - stream.point = pointLine; - } - function pointLine(x, y) { - context.lineTo(x, y); - } - function lineEnd() { - stream.point = point; - } - function lineEndPolygon() { - context.closePath(); - } - return stream; - } - function d3_geo_resample(project) { - var δ2 = .5, cosMinDistance = Math.cos(30 * d3_radians), maxDepth = 16; - function resample(stream) { - return (maxDepth ? resampleRecursive : resampleNone)(stream); - } - function resampleNone(stream) { - return d3_geo_transformPoint(stream, function(x, y) { - x = project(x, y); - stream.point(x[0], x[1]); - }); - } - function resampleRecursive(stream) { - var λ00, φ00, x00, y00, a00, b00, c00, λ0, x0, y0, a0, b0, c0; - var resample = { - point: point, - lineStart: lineStart, - lineEnd: lineEnd, - polygonStart: function() { - stream.polygonStart(); - resample.lineStart = ringStart; - }, - polygonEnd: function() { - stream.polygonEnd(); - resample.lineStart = lineStart; - } - }; - function point(x, y) { - x = project(x, y); - stream.point(x[0], x[1]); - } - function lineStart() { - x0 = NaN; - resample.point = linePoint; - stream.lineStart(); - } - function linePoint(λ, φ) { - var c = d3_geo_cartesian([ λ, φ ]), p = project(λ, φ); - resampleLineTo(x0, y0, λ0, a0, b0, c0, x0 = p[0], y0 = p[1], λ0 = λ, a0 = c[0], b0 = c[1], c0 = c[2], maxDepth, stream); - stream.point(x0, y0); - } - function lineEnd() { - resample.point = point; - stream.lineEnd(); - } - function ringStart() { - lineStart(); - resample.point = ringPoint; - resample.lineEnd = ringEnd; - } - function ringPoint(λ, φ) { - linePoint(λ00 = λ, φ00 = φ), x00 = x0, y00 = y0, a00 = a0, b00 = b0, c00 = c0; - resample.point = linePoint; - } - function ringEnd() { - resampleLineTo(x0, y0, λ0, a0, b0, c0, x00, y00, λ00, a00, b00, c00, maxDepth, stream); - resample.lineEnd = lineEnd; - lineEnd(); - } - return resample; - } - function resampleLineTo(x0, y0, λ0, a0, b0, c0, x1, y1, λ1, a1, b1, c1, depth, stream) { - var dx = x1 - x0, dy = y1 - y0, d2 = dx * dx + dy * dy; - if (d2 > 4 * δ2 && depth--) { - var a = a0 + a1, b = b0 + b1, c = c0 + c1, m = Math.sqrt(a * a + b * b + c * c), φ2 = Math.asin(c /= m), λ2 = abs(abs(c) - 1) < ε || abs(λ0 - λ1) < ε ? (λ0 + λ1) / 2 : Math.atan2(b, a), p = project(λ2, φ2), x2 = p[0], y2 = p[1], dx2 = x2 - x0, dy2 = y2 - y0, dz = dy * dx2 - dx * dy2; - if (dz * dz / d2 > δ2 || abs((dx * dx2 + dy * dy2) / d2 - .5) > .3 || a0 * a1 + b0 * b1 + c0 * c1 < cosMinDistance) { - resampleLineTo(x0, y0, λ0, a0, b0, c0, x2, y2, λ2, a /= m, b /= m, c, depth, stream); - stream.point(x2, y2); - resampleLineTo(x2, y2, λ2, a, b, c, x1, y1, λ1, a1, b1, c1, depth, stream); - } - } - } - resample.precision = function(_) { - if (!arguments.length) return Math.sqrt(δ2); - maxDepth = (δ2 = _ * _) > 0 && 16; - return resample; - }; - return resample; - } - d3.geo.path = function() { - var pointRadius = 4.5, projection, context, projectStream, contextStream, cacheStream; - function path(object) { - if (object) { - if (typeof pointRadius === "function") contextStream.pointRadius(+pointRadius.apply(this, arguments)); - if (!cacheStream || !cacheStream.valid) cacheStream = projectStream(contextStream); - d3.geo.stream(object, cacheStream); - } - return contextStream.result(); - } - path.area = function(object) { - d3_geo_pathAreaSum = 0; - d3.geo.stream(object, projectStream(d3_geo_pathArea)); - return d3_geo_pathAreaSum; - }; - path.centroid = function(object) { - d3_geo_centroidX0 = d3_geo_centroidY0 = d3_geo_centroidZ0 = d3_geo_centroidX1 = d3_geo_centroidY1 = d3_geo_centroidZ1 = d3_geo_centroidX2 = d3_geo_centroidY2 = d3_geo_centroidZ2 = 0; - d3.geo.stream(object, projectStream(d3_geo_pathCentroid)); - return d3_geo_centroidZ2 ? [ d3_geo_centroidX2 / d3_geo_centroidZ2, d3_geo_centroidY2 / d3_geo_centroidZ2 ] : d3_geo_centroidZ1 ? [ d3_geo_centroidX1 / d3_geo_centroidZ1, d3_geo_centroidY1 / d3_geo_centroidZ1 ] : d3_geo_centroidZ0 ? [ d3_geo_centroidX0 / d3_geo_centroidZ0, d3_geo_centroidY0 / d3_geo_centroidZ0 ] : [ NaN, NaN ]; - }; - path.bounds = function(object) { - d3_geo_pathBoundsX1 = d3_geo_pathBoundsY1 = -(d3_geo_pathBoundsX0 = d3_geo_pathBoundsY0 = Infinity); - d3.geo.stream(object, projectStream(d3_geo_pathBounds)); - return [ [ d3_geo_pathBoundsX0, d3_geo_pathBoundsY0 ], [ d3_geo_pathBoundsX1, d3_geo_pathBoundsY1 ] ]; - }; - path.projection = function(_) { - if (!arguments.length) return projection; - projectStream = (projection = _) ? _.stream || d3_geo_pathProjectStream(_) : d3_identity; - return reset(); - }; - path.context = function(_) { - if (!arguments.length) return context; - contextStream = (context = _) == null ? new d3_geo_pathBuffer() : new d3_geo_pathContext(_); - if (typeof pointRadius !== "function") contextStream.pointRadius(pointRadius); - return reset(); - }; - path.pointRadius = function(_) { - if (!arguments.length) return pointRadius; - pointRadius = typeof _ === "function" ? _ : (contextStream.pointRadius(+_), +_); - return path; - }; - function reset() { - cacheStream = null; - return path; - } - return path.projection(d3.geo.albersUsa()).context(null); - }; - function d3_geo_pathProjectStream(project) { - var resample = d3_geo_resample(function(x, y) { - return project([ x * d3_degrees, y * d3_degrees ]); - }); - return function(stream) { - return d3_geo_projectionRadians(resample(stream)); - }; - } - d3.geo.transform = function(methods) { - return { - stream: function(stream) { - var transform = new d3_geo_transform(stream); - for (var k in methods) transform[k] = methods[k]; - return transform; - } - }; - }; - function d3_geo_transform(stream) { - this.stream = stream; - } - d3_geo_transform.prototype = { - point: function(x, y) { - this.stream.point(x, y); - }, - sphere: function() { - this.stream.sphere(); - }, - lineStart: function() { - this.stream.lineStart(); - }, - lineEnd: function() { - this.stream.lineEnd(); - }, - polygonStart: function() { - this.stream.polygonStart(); - }, - polygonEnd: function() { - this.stream.polygonEnd(); - } - }; - function d3_geo_transformPoint(stream, point) { - return { - point: point, - sphere: function() { - stream.sphere(); - }, - lineStart: function() { - stream.lineStart(); - }, - lineEnd: function() { - stream.lineEnd(); - }, - polygonStart: function() { - stream.polygonStart(); - }, - polygonEnd: function() { - stream.polygonEnd(); - } - }; - } - d3.geo.projection = d3_geo_projection; - d3.geo.projectionMutator = d3_geo_projectionMutator; - function d3_geo_projection(project) { - return d3_geo_projectionMutator(function() { - return project; - })(); - } - function d3_geo_projectionMutator(projectAt) { - var project, rotate, projectRotate, projectResample = d3_geo_resample(function(x, y) { - x = project(x, y); - return [ x[0] * k + δx, δy - x[1] * k ]; - }), k = 150, x = 480, y = 250, λ = 0, φ = 0, δλ = 0, δφ = 0, δγ = 0, δx, δy, preclip = d3_geo_clipAntimeridian, postclip = d3_identity, clipAngle = null, clipExtent = null, stream; - function projection(point) { - point = projectRotate(point[0] * d3_radians, point[1] * d3_radians); - return [ point[0] * k + δx, δy - point[1] * k ]; - } - function invert(point) { - point = projectRotate.invert((point[0] - δx) / k, (δy - point[1]) / k); - return point && [ point[0] * d3_degrees, point[1] * d3_degrees ]; - } - projection.stream = function(output) { - if (stream) stream.valid = false; - stream = d3_geo_projectionRadians(preclip(rotate, projectResample(postclip(output)))); - stream.valid = true; - return stream; - }; - projection.clipAngle = function(_) { - if (!arguments.length) return clipAngle; - preclip = _ == null ? (clipAngle = _, d3_geo_clipAntimeridian) : d3_geo_clipCircle((clipAngle = +_) * d3_radians); - return invalidate(); - }; - projection.clipExtent = function(_) { - if (!arguments.length) return clipExtent; - clipExtent = _; - postclip = _ ? d3_geo_clipExtent(_[0][0], _[0][1], _[1][0], _[1][1]) : d3_identity; - return invalidate(); - }; - projection.scale = function(_) { - if (!arguments.length) return k; - k = +_; - return reset(); - }; - projection.translate = function(_) { - if (!arguments.length) return [ x, y ]; - x = +_[0]; - y = +_[1]; - return reset(); - }; - projection.center = function(_) { - if (!arguments.length) return [ λ * d3_degrees, φ * d3_degrees ]; - λ = _[0] % 360 * d3_radians; - φ = _[1] % 360 * d3_radians; - return reset(); - }; - projection.rotate = function(_) { - if (!arguments.length) return [ δλ * d3_degrees, δφ * d3_degrees, δγ * d3_degrees ]; - δλ = _[0] % 360 * d3_radians; - δφ = _[1] % 360 * d3_radians; - δγ = _.length > 2 ? _[2] % 360 * d3_radians : 0; - return reset(); - }; - d3.rebind(projection, projectResample, "precision"); - function reset() { - projectRotate = d3_geo_compose(rotate = d3_geo_rotation(δλ, δφ, δγ), project); - var center = project(λ, φ); - δx = x - center[0] * k; - δy = y + center[1] * k; - return invalidate(); - } - function invalidate() { - if (stream) stream.valid = false, stream = null; - return projection; - } - return function() { - project = projectAt.apply(this, arguments); - projection.invert = project.invert && invert; - return reset(); - }; - } - function d3_geo_projectionRadians(stream) { - return d3_geo_transformPoint(stream, function(x, y) { - stream.point(x * d3_radians, y * d3_radians); - }); - } - function d3_geo_equirectangular(λ, φ) { - return [ λ, φ ]; - } - (d3.geo.equirectangular = function() { - return d3_geo_projection(d3_geo_equirectangular); - }).raw = d3_geo_equirectangular.invert = d3_geo_equirectangular; - d3.geo.rotation = function(rotate) { - rotate = d3_geo_rotation(rotate[0] % 360 * d3_radians, rotate[1] * d3_radians, rotate.length > 2 ? rotate[2] * d3_radians : 0); - function forward(coordinates) { - coordinates = rotate(coordinates[0] * d3_radians, coordinates[1] * d3_radians); - return coordinates[0] *= d3_degrees, coordinates[1] *= d3_degrees, coordinates; - } - forward.invert = function(coordinates) { - coordinates = rotate.invert(coordinates[0] * d3_radians, coordinates[1] * d3_radians); - return coordinates[0] *= d3_degrees, coordinates[1] *= d3_degrees, coordinates; - }; - return forward; - }; - function d3_geo_identityRotation(λ, φ) { - return [ λ > π ? λ - τ : λ < -π ? λ + τ : λ, φ ]; - } - d3_geo_identityRotation.invert = d3_geo_equirectangular; - function d3_geo_rotation(δλ, δφ, δγ) { - return δλ ? δφ || δγ ? d3_geo_compose(d3_geo_rotationλ(δλ), d3_geo_rotationφγ(δφ, δγ)) : d3_geo_rotationλ(δλ) : δφ || δγ ? d3_geo_rotationφγ(δφ, δγ) : d3_geo_identityRotation; - } - function d3_geo_forwardRotationλ(δλ) { - return function(λ, φ) { - return λ += δλ, [ λ > π ? λ - τ : λ < -π ? λ + τ : λ, φ ]; - }; - } - function d3_geo_rotationλ(δλ) { - var rotation = d3_geo_forwardRotationλ(δλ); - rotation.invert = d3_geo_forwardRotationλ(-δλ); - return rotation; - } - function d3_geo_rotationφγ(δφ, δγ) { - var cosδφ = Math.cos(δφ), sinδφ = Math.sin(δφ), cosδγ = Math.cos(δγ), sinδγ = Math.sin(δγ); - function rotation(λ, φ) { - var cosφ = Math.cos(φ), x = Math.cos(λ) * cosφ, y = Math.sin(λ) * cosφ, z = Math.sin(φ), k = z * cosδφ + x * sinδφ; - return [ Math.atan2(y * cosδγ - k * sinδγ, x * cosδφ - z * sinδφ), d3_asin(k * cosδγ + y * sinδγ) ]; - } - rotation.invert = function(λ, φ) { - var cosφ = Math.cos(φ), x = Math.cos(λ) * cosφ, y = Math.sin(λ) * cosφ, z = Math.sin(φ), k = z * cosδγ - y * sinδγ; - return [ Math.atan2(y * cosδγ + z * sinδγ, x * cosδφ + k * sinδφ), d3_asin(k * cosδφ - x * sinδφ) ]; - }; - return rotation; - } - d3.geo.circle = function() { - var origin = [ 0, 0 ], angle, precision = 6, interpolate; - function circle() { - var center = typeof origin === "function" ? origin.apply(this, arguments) : origin, rotate = d3_geo_rotation(-center[0] * d3_radians, -center[1] * d3_radians, 0).invert, ring = []; - interpolate(null, null, 1, { - point: function(x, y) { - ring.push(x = rotate(x, y)); - x[0] *= d3_degrees, x[1] *= d3_degrees; - } - }); - return { - type: "Polygon", - coordinates: [ ring ] - }; - } - circle.origin = function(x) { - if (!arguments.length) return origin; - origin = x; - return circle; - }; - circle.angle = function(x) { - if (!arguments.length) return angle; - interpolate = d3_geo_circleInterpolate((angle = +x) * d3_radians, precision * d3_radians); - return circle; - }; - circle.precision = function(_) { - if (!arguments.length) return precision; - interpolate = d3_geo_circleInterpolate(angle * d3_radians, (precision = +_) * d3_radians); - return circle; - }; - return circle.angle(90); - }; - function d3_geo_circleInterpolate(radius, precision) { - var cr = Math.cos(radius), sr = Math.sin(radius); - return function(from, to, direction, listener) { - var step = direction * precision; - if (from != null) { - from = d3_geo_circleAngle(cr, from); - to = d3_geo_circleAngle(cr, to); - if (direction > 0 ? from < to : from > to) from += direction * τ; - } else { - from = radius + direction * τ; - to = radius - .5 * step; - } - for (var point, t = from; direction > 0 ? t > to : t < to; t -= step) { - listener.point((point = d3_geo_spherical([ cr, -sr * Math.cos(t), -sr * Math.sin(t) ]))[0], point[1]); - } - }; - } - function d3_geo_circleAngle(cr, point) { - var a = d3_geo_cartesian(point); - a[0] -= cr; - d3_geo_cartesianNormalize(a); - var angle = d3_acos(-a[1]); - return ((-a[2] < 0 ? -angle : angle) + 2 * Math.PI - ε) % (2 * Math.PI); - } - d3.geo.distance = function(a, b) { - var Δλ = (b[0] - a[0]) * d3_radians, φ0 = a[1] * d3_radians, φ1 = b[1] * d3_radians, sinΔλ = Math.sin(Δλ), cosΔλ = Math.cos(Δλ), sinφ0 = Math.sin(φ0), cosφ0 = Math.cos(φ0), sinφ1 = Math.sin(φ1), cosφ1 = Math.cos(φ1), t; - return Math.atan2(Math.sqrt((t = cosφ1 * sinΔλ) * t + (t = cosφ0 * sinφ1 - sinφ0 * cosφ1 * cosΔλ) * t), sinφ0 * sinφ1 + cosφ0 * cosφ1 * cosΔλ); - }; - d3.geo.graticule = function() { - var x1, x0, X1, X0, y1, y0, Y1, Y0, dx = 10, dy = dx, DX = 90, DY = 360, x, y, X, Y, precision = 2.5; - function graticule() { - return { - type: "MultiLineString", - coordinates: lines() - }; - } - function lines() { - return d3.range(Math.ceil(X0 / DX) * DX, X1, DX).map(X).concat(d3.range(Math.ceil(Y0 / DY) * DY, Y1, DY).map(Y)).concat(d3.range(Math.ceil(x0 / dx) * dx, x1, dx).filter(function(x) { - return abs(x % DX) > ε; - }).map(x)).concat(d3.range(Math.ceil(y0 / dy) * dy, y1, dy).filter(function(y) { - return abs(y % DY) > ε; - }).map(y)); - } - graticule.lines = function() { - return lines().map(function(coordinates) { - return { - type: "LineString", - coordinates: coordinates - }; - }); - }; - graticule.outline = function() { - return { - type: "Polygon", - coordinates: [ X(X0).concat(Y(Y1).slice(1), X(X1).reverse().slice(1), Y(Y0).reverse().slice(1)) ] - }; - }; - graticule.extent = function(_) { - if (!arguments.length) return graticule.minorExtent(); - return graticule.majorExtent(_).minorExtent(_); - }; - graticule.majorExtent = function(_) { - if (!arguments.length) return [ [ X0, Y0 ], [ X1, Y1 ] ]; - X0 = +_[0][0], X1 = +_[1][0]; - Y0 = +_[0][1], Y1 = +_[1][1]; - if (X0 > X1) _ = X0, X0 = X1, X1 = _; - if (Y0 > Y1) _ = Y0, Y0 = Y1, Y1 = _; - return graticule.precision(precision); - }; - graticule.minorExtent = function(_) { - if (!arguments.length) return [ [ x0, y0 ], [ x1, y1 ] ]; - x0 = +_[0][0], x1 = +_[1][0]; - y0 = +_[0][1], y1 = +_[1][1]; - if (x0 > x1) _ = x0, x0 = x1, x1 = _; - if (y0 > y1) _ = y0, y0 = y1, y1 = _; - return graticule.precision(precision); - }; - graticule.step = function(_) { - if (!arguments.length) return graticule.minorStep(); - return graticule.majorStep(_).minorStep(_); - }; - graticule.majorStep = function(_) { - if (!arguments.length) return [ DX, DY ]; - DX = +_[0], DY = +_[1]; - return graticule; - }; - graticule.minorStep = function(_) { - if (!arguments.length) return [ dx, dy ]; - dx = +_[0], dy = +_[1]; - return graticule; - }; - graticule.precision = function(_) { - if (!arguments.length) return precision; - precision = +_; - x = d3_geo_graticuleX(y0, y1, 90); - y = d3_geo_graticuleY(x0, x1, precision); - X = d3_geo_graticuleX(Y0, Y1, 90); - Y = d3_geo_graticuleY(X0, X1, precision); - return graticule; - }; - return graticule.majorExtent([ [ -180, -90 + ε ], [ 180, 90 - ε ] ]).minorExtent([ [ -180, -80 - ε ], [ 180, 80 + ε ] ]); - }; - function d3_geo_graticuleX(y0, y1, dy) { - var y = d3.range(y0, y1 - ε, dy).concat(y1); - return function(x) { - return y.map(function(y) { - return [ x, y ]; - }); - }; - } - function d3_geo_graticuleY(x0, x1, dx) { - var x = d3.range(x0, x1 - ε, dx).concat(x1); - return function(y) { - return x.map(function(x) { - return [ x, y ]; - }); - }; - } - function d3_source(d) { - return d.source; - } - function d3_target(d) { - return d.target; - } - d3.geo.greatArc = function() { - var source = d3_source, source_, target = d3_target, target_; - function greatArc() { - return { - type: "LineString", - coordinates: [ source_ || source.apply(this, arguments), target_ || target.apply(this, arguments) ] - }; - } - greatArc.distance = function() { - return d3.geo.distance(source_ || source.apply(this, arguments), target_ || target.apply(this, arguments)); - }; - greatArc.source = function(_) { - if (!arguments.length) return source; - source = _, source_ = typeof _ === "function" ? null : _; - return greatArc; - }; - greatArc.target = function(_) { - if (!arguments.length) return target; - target = _, target_ = typeof _ === "function" ? null : _; - return greatArc; - }; - greatArc.precision = function() { - return arguments.length ? greatArc : 0; - }; - return greatArc; - }; - d3.geo.interpolate = function(source, target) { - return d3_geo_interpolate(source[0] * d3_radians, source[1] * d3_radians, target[0] * d3_radians, target[1] * d3_radians); - }; - function d3_geo_interpolate(x0, y0, x1, y1) { - var cy0 = Math.cos(y0), sy0 = Math.sin(y0), cy1 = Math.cos(y1), sy1 = Math.sin(y1), kx0 = cy0 * Math.cos(x0), ky0 = cy0 * Math.sin(x0), kx1 = cy1 * Math.cos(x1), ky1 = cy1 * Math.sin(x1), d = 2 * Math.asin(Math.sqrt(d3_haversin(y1 - y0) + cy0 * cy1 * d3_haversin(x1 - x0))), k = 1 / Math.sin(d); - var interpolate = d ? function(t) { - var B = Math.sin(t *= d) * k, A = Math.sin(d - t) * k, x = A * kx0 + B * kx1, y = A * ky0 + B * ky1, z = A * sy0 + B * sy1; - return [ Math.atan2(y, x) * d3_degrees, Math.atan2(z, Math.sqrt(x * x + y * y)) * d3_degrees ]; - } : function() { - return [ x0 * d3_degrees, y0 * d3_degrees ]; - }; - interpolate.distance = d; - return interpolate; - } - d3.geo.length = function(object) { - d3_geo_lengthSum = 0; - d3.geo.stream(object, d3_geo_length); - return d3_geo_lengthSum; - }; - var d3_geo_lengthSum; - var d3_geo_length = { - sphere: d3_noop, - point: d3_noop, - lineStart: d3_geo_lengthLineStart, - lineEnd: d3_noop, - polygonStart: d3_noop, - polygonEnd: d3_noop - }; - function d3_geo_lengthLineStart() { - var λ0, sinφ0, cosφ0; - d3_geo_length.point = function(λ, φ) { - λ0 = λ * d3_radians, sinφ0 = Math.sin(φ *= d3_radians), cosφ0 = Math.cos(φ); - d3_geo_length.point = nextPoint; - }; - d3_geo_length.lineEnd = function() { - d3_geo_length.point = d3_geo_length.lineEnd = d3_noop; - }; - function nextPoint(λ, φ) { - var sinφ = Math.sin(φ *= d3_radians), cosφ = Math.cos(φ), t = abs((λ *= d3_radians) - λ0), cosΔλ = Math.cos(t); - d3_geo_lengthSum += Math.atan2(Math.sqrt((t = cosφ * Math.sin(t)) * t + (t = cosφ0 * sinφ - sinφ0 * cosφ * cosΔλ) * t), sinφ0 * sinφ + cosφ0 * cosφ * cosΔλ); - λ0 = λ, sinφ0 = sinφ, cosφ0 = cosφ; - } - } - function d3_geo_azimuthal(scale, angle) { - function azimuthal(λ, φ) { - var cosλ = Math.cos(λ), cosφ = Math.cos(φ), k = scale(cosλ * cosφ); - return [ k * cosφ * Math.sin(λ), k * Math.sin(φ) ]; - } - azimuthal.invert = function(x, y) { - var ρ = Math.sqrt(x * x + y * y), c = angle(ρ), sinc = Math.sin(c), cosc = Math.cos(c); - return [ Math.atan2(x * sinc, ρ * cosc), Math.asin(ρ && y * sinc / ρ) ]; - }; - return azimuthal; - } - var d3_geo_azimuthalEqualArea = d3_geo_azimuthal(function(cosλcosφ) { - return Math.sqrt(2 / (1 + cosλcosφ)); - }, function(ρ) { - return 2 * Math.asin(ρ / 2); - }); - (d3.geo.azimuthalEqualArea = function() { - return d3_geo_projection(d3_geo_azimuthalEqualArea); - }).raw = d3_geo_azimuthalEqualArea; - var d3_geo_azimuthalEquidistant = d3_geo_azimuthal(function(cosλcosφ) { - var c = Math.acos(cosλcosφ); - return c && c / Math.sin(c); - }, d3_identity); - (d3.geo.azimuthalEquidistant = function() { - return d3_geo_projection(d3_geo_azimuthalEquidistant); - }).raw = d3_geo_azimuthalEquidistant; - function d3_geo_conicConformal(φ0, φ1) { - var cosφ0 = Math.cos(φ0), t = function(φ) { - return Math.tan(π / 4 + φ / 2); - }, n = φ0 === φ1 ? Math.sin(φ0) : Math.log(cosφ0 / Math.cos(φ1)) / Math.log(t(φ1) / t(φ0)), F = cosφ0 * Math.pow(t(φ0), n) / n; - if (!n) return d3_geo_mercator; - function forward(λ, φ) { - if (F > 0) { - if (φ < -halfπ + ε) φ = -halfπ + ε; - } else { - if (φ > halfπ - ε) φ = halfπ - ε; - } - var ρ = F / Math.pow(t(φ), n); - return [ ρ * Math.sin(n * λ), F - ρ * Math.cos(n * λ) ]; - } - forward.invert = function(x, y) { - var ρ0_y = F - y, ρ = d3_sgn(n) * Math.sqrt(x * x + ρ0_y * ρ0_y); - return [ Math.atan2(x, ρ0_y) / n, 2 * Math.atan(Math.pow(F / ρ, 1 / n)) - halfπ ]; - }; - return forward; - } - (d3.geo.conicConformal = function() { - return d3_geo_conic(d3_geo_conicConformal); - }).raw = d3_geo_conicConformal; - function d3_geo_conicEquidistant(φ0, φ1) { - var cosφ0 = Math.cos(φ0), n = φ0 === φ1 ? Math.sin(φ0) : (cosφ0 - Math.cos(φ1)) / (φ1 - φ0), G = cosφ0 / n + φ0; - if (abs(n) < ε) return d3_geo_equirectangular; - function forward(λ, φ) { - var ρ = G - φ; - return [ ρ * Math.sin(n * λ), G - ρ * Math.cos(n * λ) ]; - } - forward.invert = function(x, y) { - var ρ0_y = G - y; - return [ Math.atan2(x, ρ0_y) / n, G - d3_sgn(n) * Math.sqrt(x * x + ρ0_y * ρ0_y) ]; - }; - return forward; - } - (d3.geo.conicEquidistant = function() { - return d3_geo_conic(d3_geo_conicEquidistant); - }).raw = d3_geo_conicEquidistant; - var d3_geo_gnomonic = d3_geo_azimuthal(function(cosλcosφ) { - return 1 / cosλcosφ; - }, Math.atan); - (d3.geo.gnomonic = function() { - return d3_geo_projection(d3_geo_gnomonic); - }).raw = d3_geo_gnomonic; - function d3_geo_mercator(λ, φ) { - return [ λ, Math.log(Math.tan(π / 4 + φ / 2)) ]; - } - d3_geo_mercator.invert = function(x, y) { - return [ x, 2 * Math.atan(Math.exp(y)) - halfπ ]; - }; - function d3_geo_mercatorProjection(project) { - var m = d3_geo_projection(project), scale = m.scale, translate = m.translate, clipExtent = m.clipExtent, clipAuto; - m.scale = function() { - var v = scale.apply(m, arguments); - return v === m ? clipAuto ? m.clipExtent(null) : m : v; - }; - m.translate = function() { - var v = translate.apply(m, arguments); - return v === m ? clipAuto ? m.clipExtent(null) : m : v; - }; - m.clipExtent = function(_) { - var v = clipExtent.apply(m, arguments); - if (v === m) { - if (clipAuto = _ == null) { - var k = π * scale(), t = translate(); - clipExtent([ [ t[0] - k, t[1] - k ], [ t[0] + k, t[1] + k ] ]); - } - } else if (clipAuto) { - v = null; - } - return v; - }; - return m.clipExtent(null); - } - (d3.geo.mercator = function() { - return d3_geo_mercatorProjection(d3_geo_mercator); - }).raw = d3_geo_mercator; - var d3_geo_orthographic = d3_geo_azimuthal(function() { - return 1; - }, Math.asin); - (d3.geo.orthographic = function() { - return d3_geo_projection(d3_geo_orthographic); - }).raw = d3_geo_orthographic; - var d3_geo_stereographic = d3_geo_azimuthal(function(cosλcosφ) { - return 1 / (1 + cosλcosφ); - }, function(ρ) { - return 2 * Math.atan(ρ); - }); - (d3.geo.stereographic = function() { - return d3_geo_projection(d3_geo_stereographic); - }).raw = d3_geo_stereographic; - function d3_geo_transverseMercator(λ, φ) { - return [ Math.log(Math.tan(π / 4 + φ / 2)), -λ ]; - } - d3_geo_transverseMercator.invert = function(x, y) { - return [ -y, 2 * Math.atan(Math.exp(x)) - halfπ ]; - }; - (d3.geo.transverseMercator = function() { - var projection = d3_geo_mercatorProjection(d3_geo_transverseMercator), center = projection.center, rotate = projection.rotate; - projection.center = function(_) { - return _ ? center([ -_[1], _[0] ]) : (_ = center(), [ _[1], -_[0] ]); - }; - projection.rotate = function(_) { - return _ ? rotate([ _[0], _[1], _.length > 2 ? _[2] + 90 : 90 ]) : (_ = rotate(), - [ _[0], _[1], _[2] - 90 ]); - }; - return rotate([ 0, 0, 90 ]); - }).raw = d3_geo_transverseMercator; - d3.geom = {}; - function d3_geom_pointX(d) { - return d[0]; - } - function d3_geom_pointY(d) { - return d[1]; - } - d3.geom.hull = function(vertices) { - var x = d3_geom_pointX, y = d3_geom_pointY; - if (arguments.length) return hull(vertices); - function hull(data) { - if (data.length < 3) return []; - var fx = d3_functor(x), fy = d3_functor(y), i, n = data.length, points = [], flippedPoints = []; - for (i = 0; i < n; i++) { - points.push([ +fx.call(this, data[i], i), +fy.call(this, data[i], i), i ]); - } - points.sort(d3_geom_hullOrder); - for (i = 0; i < n; i++) flippedPoints.push([ points[i][0], -points[i][1] ]); - var upper = d3_geom_hullUpper(points), lower = d3_geom_hullUpper(flippedPoints); - var skipLeft = lower[0] === upper[0], skipRight = lower[lower.length - 1] === upper[upper.length - 1], polygon = []; - for (i = upper.length - 1; i >= 0; --i) polygon.push(data[points[upper[i]][2]]); - for (i = +skipLeft; i < lower.length - skipRight; ++i) polygon.push(data[points[lower[i]][2]]); - return polygon; - } - hull.x = function(_) { - return arguments.length ? (x = _, hull) : x; - }; - hull.y = function(_) { - return arguments.length ? (y = _, hull) : y; - }; - return hull; - }; - function d3_geom_hullUpper(points) { - var n = points.length, hull = [ 0, 1 ], hs = 2; - for (var i = 2; i < n; i++) { - while (hs > 1 && d3_cross2d(points[hull[hs - 2]], points[hull[hs - 1]], points[i]) <= 0) --hs; - hull[hs++] = i; - } - return hull.slice(0, hs); - } - function d3_geom_hullOrder(a, b) { - return a[0] - b[0] || a[1] - b[1]; - } - d3.geom.polygon = function(coordinates) { - d3_subclass(coordinates, d3_geom_polygonPrototype); - return coordinates; - }; - var d3_geom_polygonPrototype = d3.geom.polygon.prototype = []; - d3_geom_polygonPrototype.area = function() { - var i = -1, n = this.length, a, b = this[n - 1], area = 0; - while (++i < n) { - a = b; - b = this[i]; - area += a[1] * b[0] - a[0] * b[1]; - } - return area * .5; - }; - d3_geom_polygonPrototype.centroid = function(k) { - var i = -1, n = this.length, x = 0, y = 0, a, b = this[n - 1], c; - if (!arguments.length) k = -1 / (6 * this.area()); - while (++i < n) { - a = b; - b = this[i]; - c = a[0] * b[1] - b[0] * a[1]; - x += (a[0] + b[0]) * c; - y += (a[1] + b[1]) * c; - } - return [ x * k, y * k ]; - }; - d3_geom_polygonPrototype.clip = function(subject) { - var input, closed = d3_geom_polygonClosed(subject), i = -1, n = this.length - d3_geom_polygonClosed(this), j, m, a = this[n - 1], b, c, d; - while (++i < n) { - input = subject.slice(); - subject.length = 0; - b = this[i]; - c = input[(m = input.length - closed) - 1]; - j = -1; - while (++j < m) { - d = input[j]; - if (d3_geom_polygonInside(d, a, b)) { - if (!d3_geom_polygonInside(c, a, b)) { - subject.push(d3_geom_polygonIntersect(c, d, a, b)); - } - subject.push(d); - } else if (d3_geom_polygonInside(c, a, b)) { - subject.push(d3_geom_polygonIntersect(c, d, a, b)); - } - c = d; - } - if (closed) subject.push(subject[0]); - a = b; - } - return subject; - }; - function d3_geom_polygonInside(p, a, b) { - return (b[0] - a[0]) * (p[1] - a[1]) < (b[1] - a[1]) * (p[0] - a[0]); - } - function d3_geom_polygonIntersect(c, d, a, b) { - var x1 = c[0], x3 = a[0], x21 = d[0] - x1, x43 = b[0] - x3, y1 = c[1], y3 = a[1], y21 = d[1] - y1, y43 = b[1] - y3, ua = (x43 * (y1 - y3) - y43 * (x1 - x3)) / (y43 * x21 - x43 * y21); - return [ x1 + ua * x21, y1 + ua * y21 ]; - } - function d3_geom_polygonClosed(coordinates) { - var a = coordinates[0], b = coordinates[coordinates.length - 1]; - return !(a[0] - b[0] || a[1] - b[1]); - } - var d3_geom_voronoiEdges, d3_geom_voronoiCells, d3_geom_voronoiBeaches, d3_geom_voronoiBeachPool = [], d3_geom_voronoiFirstCircle, d3_geom_voronoiCircles, d3_geom_voronoiCirclePool = []; - function d3_geom_voronoiBeach() { - d3_geom_voronoiRedBlackNode(this); - this.edge = this.site = this.circle = null; - } - function d3_geom_voronoiCreateBeach(site) { - var beach = d3_geom_voronoiBeachPool.pop() || new d3_geom_voronoiBeach(); - beach.site = site; - return beach; - } - function d3_geom_voronoiDetachBeach(beach) { - d3_geom_voronoiDetachCircle(beach); - d3_geom_voronoiBeaches.remove(beach); - d3_geom_voronoiBeachPool.push(beach); - d3_geom_voronoiRedBlackNode(beach); - } - function d3_geom_voronoiRemoveBeach(beach) { - var circle = beach.circle, x = circle.x, y = circle.cy, vertex = { - x: x, - y: y - }, previous = beach.P, next = beach.N, disappearing = [ beach ]; - d3_geom_voronoiDetachBeach(beach); - var lArc = previous; - while (lArc.circle && abs(x - lArc.circle.x) < ε && abs(y - lArc.circle.cy) < ε) { - previous = lArc.P; - disappearing.unshift(lArc); - d3_geom_voronoiDetachBeach(lArc); - lArc = previous; - } - disappearing.unshift(lArc); - d3_geom_voronoiDetachCircle(lArc); - var rArc = next; - while (rArc.circle && abs(x - rArc.circle.x) < ε && abs(y - rArc.circle.cy) < ε) { - next = rArc.N; - disappearing.push(rArc); - d3_geom_voronoiDetachBeach(rArc); - rArc = next; - } - disappearing.push(rArc); - d3_geom_voronoiDetachCircle(rArc); - var nArcs = disappearing.length, iArc; - for (iArc = 1; iArc < nArcs; ++iArc) { - rArc = disappearing[iArc]; - lArc = disappearing[iArc - 1]; - d3_geom_voronoiSetEdgeEnd(rArc.edge, lArc.site, rArc.site, vertex); - } - lArc = disappearing[0]; - rArc = disappearing[nArcs - 1]; - rArc.edge = d3_geom_voronoiCreateEdge(lArc.site, rArc.site, null, vertex); - d3_geom_voronoiAttachCircle(lArc); - d3_geom_voronoiAttachCircle(rArc); - } - function d3_geom_voronoiAddBeach(site) { - var x = site.x, directrix = site.y, lArc, rArc, dxl, dxr, node = d3_geom_voronoiBeaches._; - while (node) { - dxl = d3_geom_voronoiLeftBreakPoint(node, directrix) - x; - if (dxl > ε) node = node.L; else { - dxr = x - d3_geom_voronoiRightBreakPoint(node, directrix); - if (dxr > ε) { - if (!node.R) { - lArc = node; - break; - } - node = node.R; - } else { - if (dxl > -ε) { - lArc = node.P; - rArc = node; - } else if (dxr > -ε) { - lArc = node; - rArc = node.N; - } else { - lArc = rArc = node; - } - break; - } - } - } - var newArc = d3_geom_voronoiCreateBeach(site); - d3_geom_voronoiBeaches.insert(lArc, newArc); - if (!lArc && !rArc) return; - if (lArc === rArc) { - d3_geom_voronoiDetachCircle(lArc); - rArc = d3_geom_voronoiCreateBeach(lArc.site); - d3_geom_voronoiBeaches.insert(newArc, rArc); - newArc.edge = rArc.edge = d3_geom_voronoiCreateEdge(lArc.site, newArc.site); - d3_geom_voronoiAttachCircle(lArc); - d3_geom_voronoiAttachCircle(rArc); - return; - } - if (!rArc) { - newArc.edge = d3_geom_voronoiCreateEdge(lArc.site, newArc.site); - return; - } - d3_geom_voronoiDetachCircle(lArc); - d3_geom_voronoiDetachCircle(rArc); - var lSite = lArc.site, ax = lSite.x, ay = lSite.y, bx = site.x - ax, by = site.y - ay, rSite = rArc.site, cx = rSite.x - ax, cy = rSite.y - ay, d = 2 * (bx * cy - by * cx), hb = bx * bx + by * by, hc = cx * cx + cy * cy, vertex = { - x: (cy * hb - by * hc) / d + ax, - y: (bx * hc - cx * hb) / d + ay - }; - d3_geom_voronoiSetEdgeEnd(rArc.edge, lSite, rSite, vertex); - newArc.edge = d3_geom_voronoiCreateEdge(lSite, site, null, vertex); - rArc.edge = d3_geom_voronoiCreateEdge(site, rSite, null, vertex); - d3_geom_voronoiAttachCircle(lArc); - d3_geom_voronoiAttachCircle(rArc); - } - function d3_geom_voronoiLeftBreakPoint(arc, directrix) { - var site = arc.site, rfocx = site.x, rfocy = site.y, pby2 = rfocy - directrix; - if (!pby2) return rfocx; - var lArc = arc.P; - if (!lArc) return -Infinity; - site = lArc.site; - var lfocx = site.x, lfocy = site.y, plby2 = lfocy - directrix; - if (!plby2) return lfocx; - var hl = lfocx - rfocx, aby2 = 1 / pby2 - 1 / plby2, b = hl / plby2; - if (aby2) return (-b + Math.sqrt(b * b - 2 * aby2 * (hl * hl / (-2 * plby2) - lfocy + plby2 / 2 + rfocy - pby2 / 2))) / aby2 + rfocx; - return (rfocx + lfocx) / 2; - } - function d3_geom_voronoiRightBreakPoint(arc, directrix) { - var rArc = arc.N; - if (rArc) return d3_geom_voronoiLeftBreakPoint(rArc, directrix); - var site = arc.site; - return site.y === directrix ? site.x : Infinity; - } - function d3_geom_voronoiCell(site) { - this.site = site; - this.edges = []; - } - d3_geom_voronoiCell.prototype.prepare = function() { - var halfEdges = this.edges, iHalfEdge = halfEdges.length, edge; - while (iHalfEdge--) { - edge = halfEdges[iHalfEdge].edge; - if (!edge.b || !edge.a) halfEdges.splice(iHalfEdge, 1); - } - halfEdges.sort(d3_geom_voronoiHalfEdgeOrder); - return halfEdges.length; - }; - function d3_geom_voronoiCloseCells(extent) { - var x0 = extent[0][0], x1 = extent[1][0], y0 = extent[0][1], y1 = extent[1][1], x2, y2, x3, y3, cells = d3_geom_voronoiCells, iCell = cells.length, cell, iHalfEdge, halfEdges, nHalfEdges, start, end; - while (iCell--) { - cell = cells[iCell]; - if (!cell || !cell.prepare()) continue; - halfEdges = cell.edges; - nHalfEdges = halfEdges.length; - iHalfEdge = 0; - while (iHalfEdge < nHalfEdges) { - end = halfEdges[iHalfEdge].end(), x3 = end.x, y3 = end.y; - start = halfEdges[++iHalfEdge % nHalfEdges].start(), x2 = start.x, y2 = start.y; - if (abs(x3 - x2) > ε || abs(y3 - y2) > ε) { - halfEdges.splice(iHalfEdge, 0, new d3_geom_voronoiHalfEdge(d3_geom_voronoiCreateBorderEdge(cell.site, end, abs(x3 - x0) < ε && y1 - y3 > ε ? { - x: x0, - y: abs(x2 - x0) < ε ? y2 : y1 - } : abs(y3 - y1) < ε && x1 - x3 > ε ? { - x: abs(y2 - y1) < ε ? x2 : x1, - y: y1 - } : abs(x3 - x1) < ε && y3 - y0 > ε ? { - x: x1, - y: abs(x2 - x1) < ε ? y2 : y0 - } : abs(y3 - y0) < ε && x3 - x0 > ε ? { - x: abs(y2 - y0) < ε ? x2 : x0, - y: y0 - } : null), cell.site, null)); - ++nHalfEdges; - } - } - } - } - function d3_geom_voronoiHalfEdgeOrder(a, b) { - return b.angle - a.angle; - } - function d3_geom_voronoiCircle() { - d3_geom_voronoiRedBlackNode(this); - this.x = this.y = this.arc = this.site = this.cy = null; - } - function d3_geom_voronoiAttachCircle(arc) { - var lArc = arc.P, rArc = arc.N; - if (!lArc || !rArc) return; - var lSite = lArc.site, cSite = arc.site, rSite = rArc.site; - if (lSite === rSite) return; - var bx = cSite.x, by = cSite.y, ax = lSite.x - bx, ay = lSite.y - by, cx = rSite.x - bx, cy = rSite.y - by; - var d = 2 * (ax * cy - ay * cx); - if (d >= -ε2) return; - var ha = ax * ax + ay * ay, hc = cx * cx + cy * cy, x = (cy * ha - ay * hc) / d, y = (ax * hc - cx * ha) / d, cy = y + by; - var circle = d3_geom_voronoiCirclePool.pop() || new d3_geom_voronoiCircle(); - circle.arc = arc; - circle.site = cSite; - circle.x = x + bx; - circle.y = cy + Math.sqrt(x * x + y * y); - circle.cy = cy; - arc.circle = circle; - var before = null, node = d3_geom_voronoiCircles._; - while (node) { - if (circle.y < node.y || circle.y === node.y && circle.x <= node.x) { - if (node.L) node = node.L; else { - before = node.P; - break; - } - } else { - if (node.R) node = node.R; else { - before = node; - break; - } - } - } - d3_geom_voronoiCircles.insert(before, circle); - if (!before) d3_geom_voronoiFirstCircle = circle; - } - function d3_geom_voronoiDetachCircle(arc) { - var circle = arc.circle; - if (circle) { - if (!circle.P) d3_geom_voronoiFirstCircle = circle.N; - d3_geom_voronoiCircles.remove(circle); - d3_geom_voronoiCirclePool.push(circle); - d3_geom_voronoiRedBlackNode(circle); - arc.circle = null; - } - } - function d3_geom_voronoiClipEdges(extent) { - var edges = d3_geom_voronoiEdges, clip = d3_geom_clipLine(extent[0][0], extent[0][1], extent[1][0], extent[1][1]), i = edges.length, e; - while (i--) { - e = edges[i]; - if (!d3_geom_voronoiConnectEdge(e, extent) || !clip(e) || abs(e.a.x - e.b.x) < ε && abs(e.a.y - e.b.y) < ε) { - e.a = e.b = null; - edges.splice(i, 1); - } - } - } - function d3_geom_voronoiConnectEdge(edge, extent) { - var vb = edge.b; - if (vb) return true; - var va = edge.a, x0 = extent[0][0], x1 = extent[1][0], y0 = extent[0][1], y1 = extent[1][1], lSite = edge.l, rSite = edge.r, lx = lSite.x, ly = lSite.y, rx = rSite.x, ry = rSite.y, fx = (lx + rx) / 2, fy = (ly + ry) / 2, fm, fb; - if (ry === ly) { - if (fx < x0 || fx >= x1) return; - if (lx > rx) { - if (!va) va = { - x: fx, - y: y0 - }; else if (va.y >= y1) return; - vb = { - x: fx, - y: y1 - }; - } else { - if (!va) va = { - x: fx, - y: y1 - }; else if (va.y < y0) return; - vb = { - x: fx, - y: y0 - }; - } - } else { - fm = (lx - rx) / (ry - ly); - fb = fy - fm * fx; - if (fm < -1 || fm > 1) { - if (lx > rx) { - if (!va) va = { - x: (y0 - fb) / fm, - y: y0 - }; else if (va.y >= y1) return; - vb = { - x: (y1 - fb) / fm, - y: y1 - }; - } else { - if (!va) va = { - x: (y1 - fb) / fm, - y: y1 - }; else if (va.y < y0) return; - vb = { - x: (y0 - fb) / fm, - y: y0 - }; - } - } else { - if (ly < ry) { - if (!va) va = { - x: x0, - y: fm * x0 + fb - }; else if (va.x >= x1) return; - vb = { - x: x1, - y: fm * x1 + fb - }; - } else { - if (!va) va = { - x: x1, - y: fm * x1 + fb - }; else if (va.x < x0) return; - vb = { - x: x0, - y: fm * x0 + fb - }; - } - } - } - edge.a = va; - edge.b = vb; - return true; - } - function d3_geom_voronoiEdge(lSite, rSite) { - this.l = lSite; - this.r = rSite; - this.a = this.b = null; - } - function d3_geom_voronoiCreateEdge(lSite, rSite, va, vb) { - var edge = new d3_geom_voronoiEdge(lSite, rSite); - d3_geom_voronoiEdges.push(edge); - if (va) d3_geom_voronoiSetEdgeEnd(edge, lSite, rSite, va); - if (vb) d3_geom_voronoiSetEdgeEnd(edge, rSite, lSite, vb); - d3_geom_voronoiCells[lSite.i].edges.push(new d3_geom_voronoiHalfEdge(edge, lSite, rSite)); - d3_geom_voronoiCells[rSite.i].edges.push(new d3_geom_voronoiHalfEdge(edge, rSite, lSite)); - return edge; - } - function d3_geom_voronoiCreateBorderEdge(lSite, va, vb) { - var edge = new d3_geom_voronoiEdge(lSite, null); - edge.a = va; - edge.b = vb; - d3_geom_voronoiEdges.push(edge); - return edge; - } - function d3_geom_voronoiSetEdgeEnd(edge, lSite, rSite, vertex) { - if (!edge.a && !edge.b) { - edge.a = vertex; - edge.l = lSite; - edge.r = rSite; - } else if (edge.l === rSite) { - edge.b = vertex; - } else { - edge.a = vertex; - } - } - function d3_geom_voronoiHalfEdge(edge, lSite, rSite) { - var va = edge.a, vb = edge.b; - this.edge = edge; - this.site = lSite; - this.angle = rSite ? Math.atan2(rSite.y - lSite.y, rSite.x - lSite.x) : edge.l === lSite ? Math.atan2(vb.x - va.x, va.y - vb.y) : Math.atan2(va.x - vb.x, vb.y - va.y); - } - d3_geom_voronoiHalfEdge.prototype = { - start: function() { - return this.edge.l === this.site ? this.edge.a : this.edge.b; - }, - end: function() { - return this.edge.l === this.site ? this.edge.b : this.edge.a; - } - }; - function d3_geom_voronoiRedBlackTree() { - this._ = null; - } - function d3_geom_voronoiRedBlackNode(node) { - node.U = node.C = node.L = node.R = node.P = node.N = null; - } - d3_geom_voronoiRedBlackTree.prototype = { - insert: function(after, node) { - var parent, grandpa, uncle; - if (after) { - node.P = after; - node.N = after.N; - if (after.N) after.N.P = node; - after.N = node; - if (after.R) { - after = after.R; - while (after.L) after = after.L; - after.L = node; - } else { - after.R = node; - } - parent = after; - } else if (this._) { - after = d3_geom_voronoiRedBlackFirst(this._); - node.P = null; - node.N = after; - after.P = after.L = node; - parent = after; - } else { - node.P = node.N = null; - this._ = node; - parent = null; - } - node.L = node.R = null; - node.U = parent; - node.C = true; - after = node; - while (parent && parent.C) { - grandpa = parent.U; - if (parent === grandpa.L) { - uncle = grandpa.R; - if (uncle && uncle.C) { - parent.C = uncle.C = false; - grandpa.C = true; - after = grandpa; - } else { - if (after === parent.R) { - d3_geom_voronoiRedBlackRotateLeft(this, parent); - after = parent; - parent = after.U; - } - parent.C = false; - grandpa.C = true; - d3_geom_voronoiRedBlackRotateRight(this, grandpa); - } - } else { - uncle = grandpa.L; - if (uncle && uncle.C) { - parent.C = uncle.C = false; - grandpa.C = true; - after = grandpa; - } else { - if (after === parent.L) { - d3_geom_voronoiRedBlackRotateRight(this, parent); - after = parent; - parent = after.U; - } - parent.C = false; - grandpa.C = true; - d3_geom_voronoiRedBlackRotateLeft(this, grandpa); - } - } - parent = after.U; - } - this._.C = false; - }, - remove: function(node) { - if (node.N) node.N.P = node.P; - if (node.P) node.P.N = node.N; - node.N = node.P = null; - var parent = node.U, sibling, left = node.L, right = node.R, next, red; - if (!left) next = right; else if (!right) next = left; else next = d3_geom_voronoiRedBlackFirst(right); - if (parent) { - if (parent.L === node) parent.L = next; else parent.R = next; - } else { - this._ = next; - } - if (left && right) { - red = next.C; - next.C = node.C; - next.L = left; - left.U = next; - if (next !== right) { - parent = next.U; - next.U = node.U; - node = next.R; - parent.L = node; - next.R = right; - right.U = next; - } else { - next.U = parent; - parent = next; - node = next.R; - } - } else { - red = node.C; - node = next; - } - if (node) node.U = parent; - if (red) return; - if (node && node.C) { - node.C = false; - return; - } - do { - if (node === this._) break; - if (node === parent.L) { - sibling = parent.R; - if (sibling.C) { - sibling.C = false; - parent.C = true; - d3_geom_voronoiRedBlackRotateLeft(this, parent); - sibling = parent.R; - } - if (sibling.L && sibling.L.C || sibling.R && sibling.R.C) { - if (!sibling.R || !sibling.R.C) { - sibling.L.C = false; - sibling.C = true; - d3_geom_voronoiRedBlackRotateRight(this, sibling); - sibling = parent.R; - } - sibling.C = parent.C; - parent.C = sibling.R.C = false; - d3_geom_voronoiRedBlackRotateLeft(this, parent); - node = this._; - break; - } - } else { - sibling = parent.L; - if (sibling.C) { - sibling.C = false; - parent.C = true; - d3_geom_voronoiRedBlackRotateRight(this, parent); - sibling = parent.L; - } - if (sibling.L && sibling.L.C || sibling.R && sibling.R.C) { - if (!sibling.L || !sibling.L.C) { - sibling.R.C = false; - sibling.C = true; - d3_geom_voronoiRedBlackRotateLeft(this, sibling); - sibling = parent.L; - } - sibling.C = parent.C; - parent.C = sibling.L.C = false; - d3_geom_voronoiRedBlackRotateRight(this, parent); - node = this._; - break; - } - } - sibling.C = true; - node = parent; - parent = parent.U; - } while (!node.C); - if (node) node.C = false; - } - }; - function d3_geom_voronoiRedBlackRotateLeft(tree, node) { - var p = node, q = node.R, parent = p.U; - if (parent) { - if (parent.L === p) parent.L = q; else parent.R = q; - } else { - tree._ = q; - } - q.U = parent; - p.U = q; - p.R = q.L; - if (p.R) p.R.U = p; - q.L = p; - } - function d3_geom_voronoiRedBlackRotateRight(tree, node) { - var p = node, q = node.L, parent = p.U; - if (parent) { - if (parent.L === p) parent.L = q; else parent.R = q; - } else { - tree._ = q; - } - q.U = parent; - p.U = q; - p.L = q.R; - if (p.L) p.L.U = p; - q.R = p; - } - function d3_geom_voronoiRedBlackFirst(node) { - while (node.L) node = node.L; - return node; - } - function d3_geom_voronoi(sites, bbox) { - var site = sites.sort(d3_geom_voronoiVertexOrder).pop(), x0, y0, circle; - d3_geom_voronoiEdges = []; - d3_geom_voronoiCells = new Array(sites.length); - d3_geom_voronoiBeaches = new d3_geom_voronoiRedBlackTree(); - d3_geom_voronoiCircles = new d3_geom_voronoiRedBlackTree(); - while (true) { - circle = d3_geom_voronoiFirstCircle; - if (site && (!circle || site.y < circle.y || site.y === circle.y && site.x < circle.x)) { - if (site.x !== x0 || site.y !== y0) { - d3_geom_voronoiCells[site.i] = new d3_geom_voronoiCell(site); - d3_geom_voronoiAddBeach(site); - x0 = site.x, y0 = site.y; - } - site = sites.pop(); - } else if (circle) { - d3_geom_voronoiRemoveBeach(circle.arc); - } else { - break; - } - } - if (bbox) d3_geom_voronoiClipEdges(bbox), d3_geom_voronoiCloseCells(bbox); - var diagram = { - cells: d3_geom_voronoiCells, - edges: d3_geom_voronoiEdges - }; - d3_geom_voronoiBeaches = d3_geom_voronoiCircles = d3_geom_voronoiEdges = d3_geom_voronoiCells = null; - return diagram; - } - function d3_geom_voronoiVertexOrder(a, b) { - return b.y - a.y || b.x - a.x; - } - d3.geom.voronoi = function(points) { - var x = d3_geom_pointX, y = d3_geom_pointY, fx = x, fy = y, clipExtent = d3_geom_voronoiClipExtent; - if (points) return voronoi(points); - function voronoi(data) { - var polygons = new Array(data.length), x0 = clipExtent[0][0], y0 = clipExtent[0][1], x1 = clipExtent[1][0], y1 = clipExtent[1][1]; - d3_geom_voronoi(sites(data), clipExtent).cells.forEach(function(cell, i) { - var edges = cell.edges, site = cell.site, polygon = polygons[i] = edges.length ? edges.map(function(e) { - var s = e.start(); - return [ s.x, s.y ]; - }) : site.x >= x0 && site.x <= x1 && site.y >= y0 && site.y <= y1 ? [ [ x0, y1 ], [ x1, y1 ], [ x1, y0 ], [ x0, y0 ] ] : []; - polygon.point = data[i]; - }); - return polygons; - } - function sites(data) { - return data.map(function(d, i) { - return { - x: Math.round(fx(d, i) / ε) * ε, - y: Math.round(fy(d, i) / ε) * ε, - i: i - }; - }); - } - voronoi.links = function(data) { - return d3_geom_voronoi(sites(data)).edges.filter(function(edge) { - return edge.l && edge.r; - }).map(function(edge) { - return { - source: data[edge.l.i], - target: data[edge.r.i] - }; - }); - }; - voronoi.triangles = function(data) { - var triangles = []; - d3_geom_voronoi(sites(data)).cells.forEach(function(cell, i) { - var site = cell.site, edges = cell.edges.sort(d3_geom_voronoiHalfEdgeOrder), j = -1, m = edges.length, e0, s0, e1 = edges[m - 1].edge, s1 = e1.l === site ? e1.r : e1.l; - while (++j < m) { - e0 = e1; - s0 = s1; - e1 = edges[j].edge; - s1 = e1.l === site ? e1.r : e1.l; - if (i < s0.i && i < s1.i && d3_geom_voronoiTriangleArea(site, s0, s1) < 0) { - triangles.push([ data[i], data[s0.i], data[s1.i] ]); - } - } - }); - return triangles; - }; - voronoi.x = function(_) { - return arguments.length ? (fx = d3_functor(x = _), voronoi) : x; - }; - voronoi.y = function(_) { - return arguments.length ? (fy = d3_functor(y = _), voronoi) : y; - }; - voronoi.clipExtent = function(_) { - if (!arguments.length) return clipExtent === d3_geom_voronoiClipExtent ? null : clipExtent; - clipExtent = _ == null ? d3_geom_voronoiClipExtent : _; - return voronoi; - }; - voronoi.size = function(_) { - if (!arguments.length) return clipExtent === d3_geom_voronoiClipExtent ? null : clipExtent && clipExtent[1]; - return voronoi.clipExtent(_ && [ [ 0, 0 ], _ ]); - }; - return voronoi; - }; - var d3_geom_voronoiClipExtent = [ [ -1e6, -1e6 ], [ 1e6, 1e6 ] ]; - function d3_geom_voronoiTriangleArea(a, b, c) { - return (a.x - c.x) * (b.y - a.y) - (a.x - b.x) * (c.y - a.y); - } - d3.geom.delaunay = function(vertices) { - return d3.geom.voronoi().triangles(vertices); - }; - d3.geom.quadtree = function(points, x1, y1, x2, y2) { - var x = d3_geom_pointX, y = d3_geom_pointY, compat; - if (compat = arguments.length) { - x = d3_geom_quadtreeCompatX; - y = d3_geom_quadtreeCompatY; - if (compat === 3) { - y2 = y1; - x2 = x1; - y1 = x1 = 0; - } - return quadtree(points); - } - function quadtree(data) { - var d, fx = d3_functor(x), fy = d3_functor(y), xs, ys, i, n, x1_, y1_, x2_, y2_; - if (x1 != null) { - x1_ = x1, y1_ = y1, x2_ = x2, y2_ = y2; - } else { - x2_ = y2_ = -(x1_ = y1_ = Infinity); - xs = [], ys = []; - n = data.length; - if (compat) for (i = 0; i < n; ++i) { - d = data[i]; - if (d.x < x1_) x1_ = d.x; - if (d.y < y1_) y1_ = d.y; - if (d.x > x2_) x2_ = d.x; - if (d.y > y2_) y2_ = d.y; - xs.push(d.x); - ys.push(d.y); - } else for (i = 0; i < n; ++i) { - var x_ = +fx(d = data[i], i), y_ = +fy(d, i); - if (x_ < x1_) x1_ = x_; - if (y_ < y1_) y1_ = y_; - if (x_ > x2_) x2_ = x_; - if (y_ > y2_) y2_ = y_; - xs.push(x_); - ys.push(y_); - } - } - var dx = x2_ - x1_, dy = y2_ - y1_; - if (dx > dy) y2_ = y1_ + dx; else x2_ = x1_ + dy; - function insert(n, d, x, y, x1, y1, x2, y2) { - if (isNaN(x) || isNaN(y)) return; - if (n.leaf) { - var nx = n.x, ny = n.y; - if (nx != null) { - if (abs(nx - x) + abs(ny - y) < .01) { - insertChild(n, d, x, y, x1, y1, x2, y2); - } else { - var nPoint = n.point; - n.x = n.y = n.point = null; - insertChild(n, nPoint, nx, ny, x1, y1, x2, y2); - insertChild(n, d, x, y, x1, y1, x2, y2); - } - } else { - n.x = x, n.y = y, n.point = d; - } - } else { - insertChild(n, d, x, y, x1, y1, x2, y2); - } - } - function insertChild(n, d, x, y, x1, y1, x2, y2) { - var sx = (x1 + x2) * .5, sy = (y1 + y2) * .5, right = x >= sx, bottom = y >= sy, i = (bottom << 1) + right; - n.leaf = false; - n = n.nodes[i] || (n.nodes[i] = d3_geom_quadtreeNode()); - if (right) x1 = sx; else x2 = sx; - if (bottom) y1 = sy; else y2 = sy; - insert(n, d, x, y, x1, y1, x2, y2); - } - var root = d3_geom_quadtreeNode(); - root.add = function(d) { - insert(root, d, +fx(d, ++i), +fy(d, i), x1_, y1_, x2_, y2_); - }; - root.visit = function(f) { - d3_geom_quadtreeVisit(f, root, x1_, y1_, x2_, y2_); - }; - i = -1; - if (x1 == null) { - while (++i < n) { - insert(root, data[i], xs[i], ys[i], x1_, y1_, x2_, y2_); - } - --i; - } else data.forEach(root.add); - xs = ys = data = d = null; - return root; - } - quadtree.x = function(_) { - return arguments.length ? (x = _, quadtree) : x; - }; - quadtree.y = function(_) { - return arguments.length ? (y = _, quadtree) : y; - }; - quadtree.extent = function(_) { - if (!arguments.length) return x1 == null ? null : [ [ x1, y1 ], [ x2, y2 ] ]; - if (_ == null) x1 = y1 = x2 = y2 = null; else x1 = +_[0][0], y1 = +_[0][1], x2 = +_[1][0], - y2 = +_[1][1]; - return quadtree; - }; - quadtree.size = function(_) { - if (!arguments.length) return x1 == null ? null : [ x2 - x1, y2 - y1 ]; - if (_ == null) x1 = y1 = x2 = y2 = null; else x1 = y1 = 0, x2 = +_[0], y2 = +_[1]; - return quadtree; - }; - return quadtree; - }; - function d3_geom_quadtreeCompatX(d) { - return d.x; - } - function d3_geom_quadtreeCompatY(d) { - return d.y; - } - function d3_geom_quadtreeNode() { - return { - leaf: true, - nodes: [], - point: null, - x: null, - y: null - }; - } - function d3_geom_quadtreeVisit(f, node, x1, y1, x2, y2) { - if (!f(node, x1, y1, x2, y2)) { - var sx = (x1 + x2) * .5, sy = (y1 + y2) * .5, children = node.nodes; - if (children[0]) d3_geom_quadtreeVisit(f, children[0], x1, y1, sx, sy); - if (children[1]) d3_geom_quadtreeVisit(f, children[1], sx, y1, x2, sy); - if (children[2]) d3_geom_quadtreeVisit(f, children[2], x1, sy, sx, y2); - if (children[3]) d3_geom_quadtreeVisit(f, children[3], sx, sy, x2, y2); - } - } - d3.interpolateRgb = d3_interpolateRgb; - function d3_interpolateRgb(a, b) { - a = d3.rgb(a); - b = d3.rgb(b); - var ar = a.r, ag = a.g, ab = a.b, br = b.r - ar, bg = b.g - ag, bb = b.b - ab; - return function(t) { - return "#" + d3_rgb_hex(Math.round(ar + br * t)) + d3_rgb_hex(Math.round(ag + bg * t)) + d3_rgb_hex(Math.round(ab + bb * t)); - }; - } - d3.interpolateObject = d3_interpolateObject; - function d3_interpolateObject(a, b) { - var i = {}, c = {}, k; - for (k in a) { - if (k in b) { - i[k] = d3_interpolate(a[k], b[k]); - } else { - c[k] = a[k]; - } - } - for (k in b) { - if (!(k in a)) { - c[k] = b[k]; - } - } - return function(t) { - for (k in i) c[k] = i[k](t); - return c; - }; - } - d3.interpolateNumber = d3_interpolateNumber; - function d3_interpolateNumber(a, b) { - b -= a = +a; - return function(t) { - return a + b * t; - }; - } - d3.interpolateString = d3_interpolateString; - function d3_interpolateString(a, b) { - var bi = d3_interpolate_numberA.lastIndex = d3_interpolate_numberB.lastIndex = 0, am, bm, bs, i = -1, s = [], q = []; - a = a + "", b = b + ""; - while ((am = d3_interpolate_numberA.exec(a)) && (bm = d3_interpolate_numberB.exec(b))) { - if ((bs = bm.index) > bi) { - bs = b.slice(bi, bs); - if (s[i]) s[i] += bs; else s[++i] = bs; - } - if ((am = am[0]) === (bm = bm[0])) { - if (s[i]) s[i] += bm; else s[++i] = bm; - } else { - s[++i] = null; - q.push({ - i: i, - x: d3_interpolateNumber(am, bm) - }); - } - bi = d3_interpolate_numberB.lastIndex; - } - if (bi < b.length) { - bs = b.slice(bi); - if (s[i]) s[i] += bs; else s[++i] = bs; - } - return s.length < 2 ? q[0] ? (b = q[0].x, function(t) { - return b(t) + ""; - }) : function() { - return b; - } : (b = q.length, function(t) { - for (var i = 0, o; i < b; ++i) s[(o = q[i]).i] = o.x(t); - return s.join(""); - }); - } - var d3_interpolate_numberA = /[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g, d3_interpolate_numberB = new RegExp(d3_interpolate_numberA.source, "g"); - d3.interpolate = d3_interpolate; - function d3_interpolate(a, b) { - var i = d3.interpolators.length, f; - while (--i >= 0 && !(f = d3.interpolators[i](a, b))) ; - return f; - } - d3.interpolators = [ function(a, b) { - var t = typeof b; - return (t === "string" ? d3_rgb_names.has(b) || /^(#|rgb\(|hsl\()/.test(b) ? d3_interpolateRgb : d3_interpolateString : b instanceof d3_color ? d3_interpolateRgb : Array.isArray(b) ? d3_interpolateArray : t === "object" && isNaN(b) ? d3_interpolateObject : d3_interpolateNumber)(a, b); - } ]; - d3.interpolateArray = d3_interpolateArray; - function d3_interpolateArray(a, b) { - var x = [], c = [], na = a.length, nb = b.length, n0 = Math.min(a.length, b.length), i; - for (i = 0; i < n0; ++i) x.push(d3_interpolate(a[i], b[i])); - for (;i < na; ++i) c[i] = a[i]; - for (;i < nb; ++i) c[i] = b[i]; - return function(t) { - for (i = 0; i < n0; ++i) c[i] = x[i](t); - return c; - }; - } - var d3_ease_default = function() { - return d3_identity; - }; - var d3_ease = d3.map({ - linear: d3_ease_default, - poly: d3_ease_poly, - quad: function() { - return d3_ease_quad; - }, - cubic: function() { - return d3_ease_cubic; - }, - sin: function() { - return d3_ease_sin; - }, - exp: function() { - return d3_ease_exp; - }, - circle: function() { - return d3_ease_circle; - }, - elastic: d3_ease_elastic, - back: d3_ease_back, - bounce: function() { - return d3_ease_bounce; - } - }); - var d3_ease_mode = d3.map({ - "in": d3_identity, - out: d3_ease_reverse, - "in-out": d3_ease_reflect, - "out-in": function(f) { - return d3_ease_reflect(d3_ease_reverse(f)); - } - }); - d3.ease = function(name) { - var i = name.indexOf("-"), t = i >= 0 ? name.slice(0, i) : name, m = i >= 0 ? name.slice(i + 1) : "in"; - t = d3_ease.get(t) || d3_ease_default; - m = d3_ease_mode.get(m) || d3_identity; - return d3_ease_clamp(m(t.apply(null, d3_arraySlice.call(arguments, 1)))); - }; - function d3_ease_clamp(f) { - return function(t) { - return t <= 0 ? 0 : t >= 1 ? 1 : f(t); - }; - } - function d3_ease_reverse(f) { - return function(t) { - return 1 - f(1 - t); - }; - } - function d3_ease_reflect(f) { - return function(t) { - return .5 * (t < .5 ? f(2 * t) : 2 - f(2 - 2 * t)); - }; - } - function d3_ease_quad(t) { - return t * t; - } - function d3_ease_cubic(t) { - return t * t * t; - } - function d3_ease_cubicInOut(t) { - if (t <= 0) return 0; - if (t >= 1) return 1; - var t2 = t * t, t3 = t2 * t; - return 4 * (t < .5 ? t3 : 3 * (t - t2) + t3 - .75); - } - function d3_ease_poly(e) { - return function(t) { - return Math.pow(t, e); - }; - } - function d3_ease_sin(t) { - return 1 - Math.cos(t * halfπ); - } - function d3_ease_exp(t) { - return Math.pow(2, 10 * (t - 1)); - } - function d3_ease_circle(t) { - return 1 - Math.sqrt(1 - t * t); - } - function d3_ease_elastic(a, p) { - var s; - if (arguments.length < 2) p = .45; - if (arguments.length) s = p / τ * Math.asin(1 / a); else a = 1, s = p / 4; - return function(t) { - return 1 + a * Math.pow(2, -10 * t) * Math.sin((t - s) * τ / p); - }; - } - function d3_ease_back(s) { - if (!s) s = 1.70158; - return function(t) { - return t * t * ((s + 1) * t - s); - }; - } - function d3_ease_bounce(t) { - return t < 1 / 2.75 ? 7.5625 * t * t : t < 2 / 2.75 ? 7.5625 * (t -= 1.5 / 2.75) * t + .75 : t < 2.5 / 2.75 ? 7.5625 * (t -= 2.25 / 2.75) * t + .9375 : 7.5625 * (t -= 2.625 / 2.75) * t + .984375; - } - d3.interpolateHcl = d3_interpolateHcl; - function d3_interpolateHcl(a, b) { - a = d3.hcl(a); - b = d3.hcl(b); - var ah = a.h, ac = a.c, al = a.l, bh = b.h - ah, bc = b.c - ac, bl = b.l - al; - if (isNaN(bc)) bc = 0, ac = isNaN(ac) ? b.c : ac; - if (isNaN(bh)) bh = 0, ah = isNaN(ah) ? b.h : ah; else if (bh > 180) bh -= 360; else if (bh < -180) bh += 360; - return function(t) { - return d3_hcl_lab(ah + bh * t, ac + bc * t, al + bl * t) + ""; - }; - } - d3.interpolateHsl = d3_interpolateHsl; - function d3_interpolateHsl(a, b) { - a = d3.hsl(a); - b = d3.hsl(b); - var ah = a.h, as = a.s, al = a.l, bh = b.h - ah, bs = b.s - as, bl = b.l - al; - if (isNaN(bs)) bs = 0, as = isNaN(as) ? b.s : as; - if (isNaN(bh)) bh = 0, ah = isNaN(ah) ? b.h : ah; else if (bh > 180) bh -= 360; else if (bh < -180) bh += 360; - return function(t) { - return d3_hsl_rgb(ah + bh * t, as + bs * t, al + bl * t) + ""; - }; - } - d3.interpolateLab = d3_interpolateLab; - function d3_interpolateLab(a, b) { - a = d3.lab(a); - b = d3.lab(b); - var al = a.l, aa = a.a, ab = a.b, bl = b.l - al, ba = b.a - aa, bb = b.b - ab; - return function(t) { - return d3_lab_rgb(al + bl * t, aa + ba * t, ab + bb * t) + ""; - }; - } - d3.interpolateRound = d3_interpolateRound; - function d3_interpolateRound(a, b) { - b -= a; - return function(t) { - return Math.round(a + b * t); - }; - } - d3.transform = function(string) { - var g = d3_document.createElementNS(d3.ns.prefix.svg, "g"); - return (d3.transform = function(string) { - if (string != null) { - g.setAttribute("transform", string); - var t = g.transform.baseVal.consolidate(); - } - return new d3_transform(t ? t.matrix : d3_transformIdentity); - })(string); - }; - function d3_transform(m) { - var r0 = [ m.a, m.b ], r1 = [ m.c, m.d ], kx = d3_transformNormalize(r0), kz = d3_transformDot(r0, r1), ky = d3_transformNormalize(d3_transformCombine(r1, r0, -kz)) || 0; - if (r0[0] * r1[1] < r1[0] * r0[1]) { - r0[0] *= -1; - r0[1] *= -1; - kx *= -1; - kz *= -1; - } - this.rotate = (kx ? Math.atan2(r0[1], r0[0]) : Math.atan2(-r1[0], r1[1])) * d3_degrees; - this.translate = [ m.e, m.f ]; - this.scale = [ kx, ky ]; - this.skew = ky ? Math.atan2(kz, ky) * d3_degrees : 0; - } - d3_transform.prototype.toString = function() { - return "translate(" + this.translate + ")rotate(" + this.rotate + ")skewX(" + this.skew + ")scale(" + this.scale + ")"; - }; - function d3_transformDot(a, b) { - return a[0] * b[0] + a[1] * b[1]; - } - function d3_transformNormalize(a) { - var k = Math.sqrt(d3_transformDot(a, a)); - if (k) { - a[0] /= k; - a[1] /= k; - } - return k; - } - function d3_transformCombine(a, b, k) { - a[0] += k * b[0]; - a[1] += k * b[1]; - return a; - } - var d3_transformIdentity = { - a: 1, - b: 0, - c: 0, - d: 1, - e: 0, - f: 0 - }; - d3.interpolateTransform = d3_interpolateTransform; - function d3_interpolateTransform(a, b) { - var s = [], q = [], n, A = d3.transform(a), B = d3.transform(b), ta = A.translate, tb = B.translate, ra = A.rotate, rb = B.rotate, wa = A.skew, wb = B.skew, ka = A.scale, kb = B.scale; - if (ta[0] != tb[0] || ta[1] != tb[1]) { - s.push("translate(", null, ",", null, ")"); - q.push({ - i: 1, - x: d3_interpolateNumber(ta[0], tb[0]) - }, { - i: 3, - x: d3_interpolateNumber(ta[1], tb[1]) - }); - } else if (tb[0] || tb[1]) { - s.push("translate(" + tb + ")"); - } else { - s.push(""); - } - if (ra != rb) { - if (ra - rb > 180) rb += 360; else if (rb - ra > 180) ra += 360; - q.push({ - i: s.push(s.pop() + "rotate(", null, ")") - 2, - x: d3_interpolateNumber(ra, rb) - }); - } else if (rb) { - s.push(s.pop() + "rotate(" + rb + ")"); - } - if (wa != wb) { - q.push({ - i: s.push(s.pop() + "skewX(", null, ")") - 2, - x: d3_interpolateNumber(wa, wb) - }); - } else if (wb) { - s.push(s.pop() + "skewX(" + wb + ")"); - } - if (ka[0] != kb[0] || ka[1] != kb[1]) { - n = s.push(s.pop() + "scale(", null, ",", null, ")"); - q.push({ - i: n - 4, - x: d3_interpolateNumber(ka[0], kb[0]) - }, { - i: n - 2, - x: d3_interpolateNumber(ka[1], kb[1]) - }); - } else if (kb[0] != 1 || kb[1] != 1) { - s.push(s.pop() + "scale(" + kb + ")"); - } - n = q.length; - return function(t) { - var i = -1, o; - while (++i < n) s[(o = q[i]).i] = o.x(t); - return s.join(""); - }; - } - function d3_uninterpolateNumber(a, b) { - b = b - (a = +a) ? 1 / (b - a) : 0; - return function(x) { - return (x - a) * b; - }; - } - function d3_uninterpolateClamp(a, b) { - b = b - (a = +a) ? 1 / (b - a) : 0; - return function(x) { - return Math.max(0, Math.min(1, (x - a) * b)); - }; - } - d3.layout = {}; - d3.layout.bundle = function() { - return function(links) { - var paths = [], i = -1, n = links.length; - while (++i < n) paths.push(d3_layout_bundlePath(links[i])); - return paths; - }; - }; - function d3_layout_bundlePath(link) { - var start = link.source, end = link.target, lca = d3_layout_bundleLeastCommonAncestor(start, end), points = [ start ]; - while (start !== lca) { - start = start.parent; - points.push(start); - } - var k = points.length; - while (end !== lca) { - points.splice(k, 0, end); - end = end.parent; - } - return points; - } - function d3_layout_bundleAncestors(node) { - var ancestors = [], parent = node.parent; - while (parent != null) { - ancestors.push(node); - node = parent; - parent = parent.parent; - } - ancestors.push(node); - return ancestors; - } - function d3_layout_bundleLeastCommonAncestor(a, b) { - if (a === b) return a; - var aNodes = d3_layout_bundleAncestors(a), bNodes = d3_layout_bundleAncestors(b), aNode = aNodes.pop(), bNode = bNodes.pop(), sharedNode = null; - while (aNode === bNode) { - sharedNode = aNode; - aNode = aNodes.pop(); - bNode = bNodes.pop(); - } - return sharedNode; - } - d3.layout.chord = function() { - var chord = {}, chords, groups, matrix, n, padding = 0, sortGroups, sortSubgroups, sortChords; - function relayout() { - var subgroups = {}, groupSums = [], groupIndex = d3.range(n), subgroupIndex = [], k, x, x0, i, j; - chords = []; - groups = []; - k = 0, i = -1; - while (++i < n) { - x = 0, j = -1; - while (++j < n) { - x += matrix[i][j]; - } - groupSums.push(x); - subgroupIndex.push(d3.range(n)); - k += x; - } - if (sortGroups) { - groupIndex.sort(function(a, b) { - return sortGroups(groupSums[a], groupSums[b]); - }); - } - if (sortSubgroups) { - subgroupIndex.forEach(function(d, i) { - d.sort(function(a, b) { - return sortSubgroups(matrix[i][a], matrix[i][b]); - }); - }); - } - k = (τ - padding * n) / k; - x = 0, i = -1; - while (++i < n) { - x0 = x, j = -1; - while (++j < n) { - var di = groupIndex[i], dj = subgroupIndex[di][j], v = matrix[di][dj], a0 = x, a1 = x += v * k; - subgroups[di + "-" + dj] = { - index: di, - subindex: dj, - startAngle: a0, - endAngle: a1, - value: v - }; - } - groups[di] = { - index: di, - startAngle: x0, - endAngle: x, - value: (x - x0) / k - }; - x += padding; - } - i = -1; - while (++i < n) { - j = i - 1; - while (++j < n) { - var source = subgroups[i + "-" + j], target = subgroups[j + "-" + i]; - if (source.value || target.value) { - chords.push(source.value < target.value ? { - source: target, - target: source - } : { - source: source, - target: target - }); - } - } - } - if (sortChords) resort(); - } - function resort() { - chords.sort(function(a, b) { - return sortChords((a.source.value + a.target.value) / 2, (b.source.value + b.target.value) / 2); - }); - } - chord.matrix = function(x) { - if (!arguments.length) return matrix; - n = (matrix = x) && matrix.length; - chords = groups = null; - return chord; - }; - chord.padding = function(x) { - if (!arguments.length) return padding; - padding = x; - chords = groups = null; - return chord; - }; - chord.sortGroups = function(x) { - if (!arguments.length) return sortGroups; - sortGroups = x; - chords = groups = null; - return chord; - }; - chord.sortSubgroups = function(x) { - if (!arguments.length) return sortSubgroups; - sortSubgroups = x; - chords = null; - return chord; - }; - chord.sortChords = function(x) { - if (!arguments.length) return sortChords; - sortChords = x; - if (chords) resort(); - return chord; - }; - chord.chords = function() { - if (!chords) relayout(); - return chords; - }; - chord.groups = function() { - if (!groups) relayout(); - return groups; - }; - return chord; - }; - d3.layout.force = function() { - var force = {}, event = d3.dispatch("start", "tick", "end"), size = [ 1, 1 ], drag, alpha, friction = .9, linkDistance = d3_layout_forceLinkDistance, linkStrength = d3_layout_forceLinkStrength, charge = -30, chargeDistance2 = d3_layout_forceChargeDistance2, gravity = .1, theta2 = .64, nodes = [], links = [], distances, strengths, charges; - function repulse(node) { - return function(quad, x1, _, x2) { - if (quad.point !== node) { - var dx = quad.cx - node.x, dy = quad.cy - node.y, dw = x2 - x1, dn = dx * dx + dy * dy; - if (dw * dw / theta2 < dn) { - if (dn < chargeDistance2) { - var k = quad.charge / dn; - node.px -= dx * k; - node.py -= dy * k; - } - return true; - } - if (quad.point && dn && dn < chargeDistance2) { - var k = quad.pointCharge / dn; - node.px -= dx * k; - node.py -= dy * k; - } - } - return !quad.charge; - }; - } - force.tick = function() { - if ((alpha *= .99) < .005) { - event.end({ - type: "end", - alpha: alpha = 0 - }); - return true; - } - var n = nodes.length, m = links.length, q, i, o, s, t, l, k, x, y; - for (i = 0; i < m; ++i) { - o = links[i]; - s = o.source; - t = o.target; - x = t.x - s.x; - y = t.y - s.y; - if (l = x * x + y * y) { - l = alpha * strengths[i] * ((l = Math.sqrt(l)) - distances[i]) / l; - x *= l; - y *= l; - t.x -= x * (k = s.weight / (t.weight + s.weight)); - t.y -= y * k; - s.x += x * (k = 1 - k); - s.y += y * k; - } - } - if (k = alpha * gravity) { - x = size[0] / 2; - y = size[1] / 2; - i = -1; - if (k) while (++i < n) { - o = nodes[i]; - o.x += (x - o.x) * k; - o.y += (y - o.y) * k; - } - } - if (charge) { - d3_layout_forceAccumulate(q = d3.geom.quadtree(nodes), alpha, charges); - i = -1; - while (++i < n) { - if (!(o = nodes[i]).fixed) { - q.visit(repulse(o)); - } - } - } - i = -1; - while (++i < n) { - o = nodes[i]; - if (o.fixed) { - o.x = o.px; - o.y = o.py; - } else { - o.x -= (o.px - (o.px = o.x)) * friction; - o.y -= (o.py - (o.py = o.y)) * friction; - } - } - event.tick({ - type: "tick", - alpha: alpha - }); - }; - force.nodes = function(x) { - if (!arguments.length) return nodes; - nodes = x; - return force; - }; - force.links = function(x) { - if (!arguments.length) return links; - links = x; - return force; - }; - force.size = function(x) { - if (!arguments.length) return size; - size = x; - return force; - }; - force.linkDistance = function(x) { - if (!arguments.length) return linkDistance; - linkDistance = typeof x === "function" ? x : +x; - return force; - }; - force.distance = force.linkDistance; - force.linkStrength = function(x) { - if (!arguments.length) return linkStrength; - linkStrength = typeof x === "function" ? x : +x; - return force; - }; - force.friction = function(x) { - if (!arguments.length) return friction; - friction = +x; - return force; - }; - force.charge = function(x) { - if (!arguments.length) return charge; - charge = typeof x === "function" ? x : +x; - return force; - }; - force.chargeDistance = function(x) { - if (!arguments.length) return Math.sqrt(chargeDistance2); - chargeDistance2 = x * x; - return force; - }; - force.gravity = function(x) { - if (!arguments.length) return gravity; - gravity = +x; - return force; - }; - force.theta = function(x) { - if (!arguments.length) return Math.sqrt(theta2); - theta2 = x * x; - return force; - }; - force.alpha = function(x) { - if (!arguments.length) return alpha; - x = +x; - if (alpha) { - if (x > 0) alpha = x; else alpha = 0; - } else if (x > 0) { - event.start({ - type: "start", - alpha: alpha = x - }); - d3.timer(force.tick); - } - return force; - }; - force.start = function() { - var i, n = nodes.length, m = links.length, w = size[0], h = size[1], neighbors, o; - for (i = 0; i < n; ++i) { - (o = nodes[i]).index = i; - o.weight = 0; - } - for (i = 0; i < m; ++i) { - o = links[i]; - if (typeof o.source == "number") o.source = nodes[o.source]; - if (typeof o.target == "number") o.target = nodes[o.target]; - ++o.source.weight; - ++o.target.weight; - } - for (i = 0; i < n; ++i) { - o = nodes[i]; - if (isNaN(o.x)) o.x = position("x", w); - if (isNaN(o.y)) o.y = position("y", h); - if (isNaN(o.px)) o.px = o.x; - if (isNaN(o.py)) o.py = o.y; - } - distances = []; - if (typeof linkDistance === "function") for (i = 0; i < m; ++i) distances[i] = +linkDistance.call(this, links[i], i); else for (i = 0; i < m; ++i) distances[i] = linkDistance; - strengths = []; - if (typeof linkStrength === "function") for (i = 0; i < m; ++i) strengths[i] = +linkStrength.call(this, links[i], i); else for (i = 0; i < m; ++i) strengths[i] = linkStrength; - charges = []; - if (typeof charge === "function") for (i = 0; i < n; ++i) charges[i] = +charge.call(this, nodes[i], i); else for (i = 0; i < n; ++i) charges[i] = charge; - function position(dimension, size) { - if (!neighbors) { - neighbors = new Array(n); - for (j = 0; j < n; ++j) { - neighbors[j] = []; - } - for (j = 0; j < m; ++j) { - var o = links[j]; - neighbors[o.source.index].push(o.target); - neighbors[o.target.index].push(o.source); - } - } - var candidates = neighbors[i], j = -1, m = candidates.length, x; - while (++j < m) if (!isNaN(x = candidates[j][dimension])) return x; - return Math.random() * size; - } - return force.resume(); - }; - force.resume = function() { - return force.alpha(.1); - }; - force.stop = function() { - return force.alpha(0); - }; - force.drag = function() { - if (!drag) drag = d3.behavior.drag().origin(d3_identity).on("dragstart.force", d3_layout_forceDragstart).on("drag.force", dragmove).on("dragend.force", d3_layout_forceDragend); - if (!arguments.length) return drag; - this.on("mouseover.force", d3_layout_forceMouseover).on("mouseout.force", d3_layout_forceMouseout).call(drag); - }; - function dragmove(d) { - d.px = d3.event.x, d.py = d3.event.y; - force.resume(); - } - return d3.rebind(force, event, "on"); - }; - function d3_layout_forceDragstart(d) { - d.fixed |= 2; - } - function d3_layout_forceDragend(d) { - d.fixed &= ~6; - } - function d3_layout_forceMouseover(d) { - d.fixed |= 4; - d.px = d.x, d.py = d.y; - } - function d3_layout_forceMouseout(d) { - d.fixed &= ~4; - } - function d3_layout_forceAccumulate(quad, alpha, charges) { - var cx = 0, cy = 0; - quad.charge = 0; - if (!quad.leaf) { - var nodes = quad.nodes, n = nodes.length, i = -1, c; - while (++i < n) { - c = nodes[i]; - if (c == null) continue; - d3_layout_forceAccumulate(c, alpha, charges); - quad.charge += c.charge; - cx += c.charge * c.cx; - cy += c.charge * c.cy; - } - } - if (quad.point) { - if (!quad.leaf) { - quad.point.x += Math.random() - .5; - quad.point.y += Math.random() - .5; - } - var k = alpha * charges[quad.point.index]; - quad.charge += quad.pointCharge = k; - cx += k * quad.point.x; - cy += k * quad.point.y; - } - quad.cx = cx / quad.charge; - quad.cy = cy / quad.charge; - } - var d3_layout_forceLinkDistance = 20, d3_layout_forceLinkStrength = 1, d3_layout_forceChargeDistance2 = Infinity; - d3.layout.hierarchy = function() { - var sort = d3_layout_hierarchySort, children = d3_layout_hierarchyChildren, value = d3_layout_hierarchyValue; - function hierarchy(root) { - var stack = [ root ], nodes = [], node; - root.depth = 0; - while ((node = stack.pop()) != null) { - nodes.push(node); - if ((childs = children.call(hierarchy, node, node.depth)) && (n = childs.length)) { - var n, childs, child; - while (--n >= 0) { - stack.push(child = childs[n]); - child.parent = node; - child.depth = node.depth + 1; - } - if (value) node.value = 0; - node.children = childs; - } else { - if (value) node.value = +value.call(hierarchy, node, node.depth) || 0; - delete node.children; - } - } - d3_layout_hierarchyVisitAfter(root, function(node) { - var childs, parent; - if (sort && (childs = node.children)) childs.sort(sort); - if (value && (parent = node.parent)) parent.value += node.value; - }); - return nodes; - } - hierarchy.sort = function(x) { - if (!arguments.length) return sort; - sort = x; - return hierarchy; - }; - hierarchy.children = function(x) { - if (!arguments.length) return children; - children = x; - return hierarchy; - }; - hierarchy.value = function(x) { - if (!arguments.length) return value; - value = x; - return hierarchy; - }; - hierarchy.revalue = function(root) { - if (value) { - d3_layout_hierarchyVisitBefore(root, function(node) { - if (node.children) node.value = 0; - }); - d3_layout_hierarchyVisitAfter(root, function(node) { - var parent; - if (!node.children) node.value = +value.call(hierarchy, node, node.depth) || 0; - if (parent = node.parent) parent.value += node.value; - }); - } - return root; - }; - return hierarchy; - }; - function d3_layout_hierarchyRebind(object, hierarchy) { - d3.rebind(object, hierarchy, "sort", "children", "value"); - object.nodes = object; - object.links = d3_layout_hierarchyLinks; - return object; - } - function d3_layout_hierarchyVisitBefore(node, callback) { - var nodes = [ node ]; - while ((node = nodes.pop()) != null) { - callback(node); - if ((children = node.children) && (n = children.length)) { - var n, children; - while (--n >= 0) nodes.push(children[n]); - } - } - } - function d3_layout_hierarchyVisitAfter(node, callback) { - var nodes = [ node ], nodes2 = []; - while ((node = nodes.pop()) != null) { - nodes2.push(node); - if ((children = node.children) && (n = children.length)) { - var i = -1, n, children; - while (++i < n) nodes.push(children[i]); - } - } - while ((node = nodes2.pop()) != null) { - callback(node); - } - } - function d3_layout_hierarchyChildren(d) { - return d.children; - } - function d3_layout_hierarchyValue(d) { - return d.value; - } - function d3_layout_hierarchySort(a, b) { - return b.value - a.value; - } - function d3_layout_hierarchyLinks(nodes) { - return d3.merge(nodes.map(function(parent) { - return (parent.children || []).map(function(child) { - return { - source: parent, - target: child - }; - }); - })); - } - d3.layout.partition = function() { - var hierarchy = d3.layout.hierarchy(), size = [ 1, 1 ]; - function position(node, x, dx, dy) { - var children = node.children; - node.x = x; - node.y = node.depth * dy; - node.dx = dx; - node.dy = dy; - if (children && (n = children.length)) { - var i = -1, n, c, d; - dx = node.value ? dx / node.value : 0; - while (++i < n) { - position(c = children[i], x, d = c.value * dx, dy); - x += d; - } - } - } - function depth(node) { - var children = node.children, d = 0; - if (children && (n = children.length)) { - var i = -1, n; - while (++i < n) d = Math.max(d, depth(children[i])); - } - return 1 + d; - } - function partition(d, i) { - var nodes = hierarchy.call(this, d, i); - position(nodes[0], 0, size[0], size[1] / depth(nodes[0])); - return nodes; - } - partition.size = function(x) { - if (!arguments.length) return size; - size = x; - return partition; - }; - return d3_layout_hierarchyRebind(partition, hierarchy); - }; - d3.layout.pie = function() { - var value = Number, sort = d3_layout_pieSortByValue, startAngle = 0, endAngle = τ; - function pie(data) { - var values = data.map(function(d, i) { - return +value.call(pie, d, i); - }); - var a = +(typeof startAngle === "function" ? startAngle.apply(this, arguments) : startAngle); - var k = ((typeof endAngle === "function" ? endAngle.apply(this, arguments) : endAngle) - a) / d3.sum(values); - var index = d3.range(data.length); - if (sort != null) index.sort(sort === d3_layout_pieSortByValue ? function(i, j) { - return values[j] - values[i]; - } : function(i, j) { - return sort(data[i], data[j]); - }); - var arcs = []; - index.forEach(function(i) { - var d; - arcs[i] = { - data: data[i], - value: d = values[i], - startAngle: a, - endAngle: a += d * k - }; - }); - return arcs; - } - pie.value = function(x) { - if (!arguments.length) return value; - value = x; - return pie; - }; - pie.sort = function(x) { - if (!arguments.length) return sort; - sort = x; - return pie; - }; - pie.startAngle = function(x) { - if (!arguments.length) return startAngle; - startAngle = x; - return pie; - }; - pie.endAngle = function(x) { - if (!arguments.length) return endAngle; - endAngle = x; - return pie; - }; - return pie; - }; - var d3_layout_pieSortByValue = {}; - d3.layout.stack = function() { - var values = d3_identity, order = d3_layout_stackOrderDefault, offset = d3_layout_stackOffsetZero, out = d3_layout_stackOut, x = d3_layout_stackX, y = d3_layout_stackY; - function stack(data, index) { - var series = data.map(function(d, i) { - return values.call(stack, d, i); - }); - var points = series.map(function(d) { - return d.map(function(v, i) { - return [ x.call(stack, v, i), y.call(stack, v, i) ]; - }); - }); - var orders = order.call(stack, points, index); - series = d3.permute(series, orders); - points = d3.permute(points, orders); - var offsets = offset.call(stack, points, index); - var n = series.length, m = series[0].length, i, j, o; - for (j = 0; j < m; ++j) { - out.call(stack, series[0][j], o = offsets[j], points[0][j][1]); - for (i = 1; i < n; ++i) { - out.call(stack, series[i][j], o += points[i - 1][j][1], points[i][j][1]); - } - } - return data; - } - stack.values = function(x) { - if (!arguments.length) return values; - values = x; - return stack; - }; - stack.order = function(x) { - if (!arguments.length) return order; - order = typeof x === "function" ? x : d3_layout_stackOrders.get(x) || d3_layout_stackOrderDefault; - return stack; - }; - stack.offset = function(x) { - if (!arguments.length) return offset; - offset = typeof x === "function" ? x : d3_layout_stackOffsets.get(x) || d3_layout_stackOffsetZero; - return stack; - }; - stack.x = function(z) { - if (!arguments.length) return x; - x = z; - return stack; - }; - stack.y = function(z) { - if (!arguments.length) return y; - y = z; - return stack; - }; - stack.out = function(z) { - if (!arguments.length) return out; - out = z; - return stack; - }; - return stack; - }; - function d3_layout_stackX(d) { - return d.x; - } - function d3_layout_stackY(d) { - return d.y; - } - function d3_layout_stackOut(d, y0, y) { - d.y0 = y0; - d.y = y; - } - var d3_layout_stackOrders = d3.map({ - "inside-out": function(data) { - var n = data.length, i, j, max = data.map(d3_layout_stackMaxIndex), sums = data.map(d3_layout_stackReduceSum), index = d3.range(n).sort(function(a, b) { - return max[a] - max[b]; - }), top = 0, bottom = 0, tops = [], bottoms = []; - for (i = 0; i < n; ++i) { - j = index[i]; - if (top < bottom) { - top += sums[j]; - tops.push(j); - } else { - bottom += sums[j]; - bottoms.push(j); - } - } - return bottoms.reverse().concat(tops); - }, - reverse: function(data) { - return d3.range(data.length).reverse(); - }, - "default": d3_layout_stackOrderDefault - }); - var d3_layout_stackOffsets = d3.map({ - silhouette: function(data) { - var n = data.length, m = data[0].length, sums = [], max = 0, i, j, o, y0 = []; - for (j = 0; j < m; ++j) { - for (i = 0, o = 0; i < n; i++) o += data[i][j][1]; - if (o > max) max = o; - sums.push(o); - } - for (j = 0; j < m; ++j) { - y0[j] = (max - sums[j]) / 2; - } - return y0; - }, - wiggle: function(data) { - var n = data.length, x = data[0], m = x.length, i, j, k, s1, s2, s3, dx, o, o0, y0 = []; - y0[0] = o = o0 = 0; - for (j = 1; j < m; ++j) { - for (i = 0, s1 = 0; i < n; ++i) s1 += data[i][j][1]; - for (i = 0, s2 = 0, dx = x[j][0] - x[j - 1][0]; i < n; ++i) { - for (k = 0, s3 = (data[i][j][1] - data[i][j - 1][1]) / (2 * dx); k < i; ++k) { - s3 += (data[k][j][1] - data[k][j - 1][1]) / dx; - } - s2 += s3 * data[i][j][1]; - } - y0[j] = o -= s1 ? s2 / s1 * dx : 0; - if (o < o0) o0 = o; - } - for (j = 0; j < m; ++j) y0[j] -= o0; - return y0; - }, - expand: function(data) { - var n = data.length, m = data[0].length, k = 1 / n, i, j, o, y0 = []; - for (j = 0; j < m; ++j) { - for (i = 0, o = 0; i < n; i++) o += data[i][j][1]; - if (o) for (i = 0; i < n; i++) data[i][j][1] /= o; else for (i = 0; i < n; i++) data[i][j][1] = k; - } - for (j = 0; j < m; ++j) y0[j] = 0; - return y0; - }, - zero: d3_layout_stackOffsetZero - }); - function d3_layout_stackOrderDefault(data) { - return d3.range(data.length); - } - function d3_layout_stackOffsetZero(data) { - var j = -1, m = data[0].length, y0 = []; - while (++j < m) y0[j] = 0; - return y0; - } - function d3_layout_stackMaxIndex(array) { - var i = 1, j = 0, v = array[0][1], k, n = array.length; - for (;i < n; ++i) { - if ((k = array[i][1]) > v) { - j = i; - v = k; - } - } - return j; - } - function d3_layout_stackReduceSum(d) { - return d.reduce(d3_layout_stackSum, 0); - } - function d3_layout_stackSum(p, d) { - return p + d[1]; - } - d3.layout.histogram = function() { - var frequency = true, valuer = Number, ranger = d3_layout_histogramRange, binner = d3_layout_histogramBinSturges; - function histogram(data, i) { - var bins = [], values = data.map(valuer, this), range = ranger.call(this, values, i), thresholds = binner.call(this, range, values, i), bin, i = -1, n = values.length, m = thresholds.length - 1, k = frequency ? 1 : 1 / n, x; - while (++i < m) { - bin = bins[i] = []; - bin.dx = thresholds[i + 1] - (bin.x = thresholds[i]); - bin.y = 0; - } - if (m > 0) { - i = -1; - while (++i < n) { - x = values[i]; - if (x >= range[0] && x <= range[1]) { - bin = bins[d3.bisect(thresholds, x, 1, m) - 1]; - bin.y += k; - bin.push(data[i]); - } - } - } - return bins; - } - histogram.value = function(x) { - if (!arguments.length) return valuer; - valuer = x; - return histogram; - }; - histogram.range = function(x) { - if (!arguments.length) return ranger; - ranger = d3_functor(x); - return histogram; - }; - histogram.bins = function(x) { - if (!arguments.length) return binner; - binner = typeof x === "number" ? function(range) { - return d3_layout_histogramBinFixed(range, x); - } : d3_functor(x); - return histogram; - }; - histogram.frequency = function(x) { - if (!arguments.length) return frequency; - frequency = !!x; - return histogram; - }; - return histogram; - }; - function d3_layout_histogramBinSturges(range, values) { - return d3_layout_histogramBinFixed(range, Math.ceil(Math.log(values.length) / Math.LN2 + 1)); - } - function d3_layout_histogramBinFixed(range, n) { - var x = -1, b = +range[0], m = (range[1] - b) / n, f = []; - while (++x <= n) f[x] = m * x + b; - return f; - } - function d3_layout_histogramRange(values) { - return [ d3.min(values), d3.max(values) ]; - } - d3.layout.pack = function() { - var hierarchy = d3.layout.hierarchy().sort(d3_layout_packSort), padding = 0, size = [ 1, 1 ], radius; - function pack(d, i) { - var nodes = hierarchy.call(this, d, i), root = nodes[0], w = size[0], h = size[1], r = radius == null ? Math.sqrt : typeof radius === "function" ? radius : function() { - return radius; - }; - root.x = root.y = 0; - d3_layout_hierarchyVisitAfter(root, function(d) { - d.r = +r(d.value); - }); - d3_layout_hierarchyVisitAfter(root, d3_layout_packSiblings); - if (padding) { - var dr = padding * (radius ? 1 : Math.max(2 * root.r / w, 2 * root.r / h)) / 2; - d3_layout_hierarchyVisitAfter(root, function(d) { - d.r += dr; - }); - d3_layout_hierarchyVisitAfter(root, d3_layout_packSiblings); - d3_layout_hierarchyVisitAfter(root, function(d) { - d.r -= dr; - }); - } - d3_layout_packTransform(root, w / 2, h / 2, radius ? 1 : 1 / Math.max(2 * root.r / w, 2 * root.r / h)); - return nodes; - } - pack.size = function(_) { - if (!arguments.length) return size; - size = _; - return pack; - }; - pack.radius = function(_) { - if (!arguments.length) return radius; - radius = _ == null || typeof _ === "function" ? _ : +_; - return pack; - }; - pack.padding = function(_) { - if (!arguments.length) return padding; - padding = +_; - return pack; - }; - return d3_layout_hierarchyRebind(pack, hierarchy); - }; - function d3_layout_packSort(a, b) { - return a.value - b.value; - } - function d3_layout_packInsert(a, b) { - var c = a._pack_next; - a._pack_next = b; - b._pack_prev = a; - b._pack_next = c; - c._pack_prev = b; - } - function d3_layout_packSplice(a, b) { - a._pack_next = b; - b._pack_prev = a; - } - function d3_layout_packIntersects(a, b) { - var dx = b.x - a.x, dy = b.y - a.y, dr = a.r + b.r; - return .999 * dr * dr > dx * dx + dy * dy; - } - function d3_layout_packSiblings(node) { - if (!(nodes = node.children) || !(n = nodes.length)) return; - var nodes, xMin = Infinity, xMax = -Infinity, yMin = Infinity, yMax = -Infinity, a, b, c, i, j, k, n; - function bound(node) { - xMin = Math.min(node.x - node.r, xMin); - xMax = Math.max(node.x + node.r, xMax); - yMin = Math.min(node.y - node.r, yMin); - yMax = Math.max(node.y + node.r, yMax); - } - nodes.forEach(d3_layout_packLink); - a = nodes[0]; - a.x = -a.r; - a.y = 0; - bound(a); - if (n > 1) { - b = nodes[1]; - b.x = b.r; - b.y = 0; - bound(b); - if (n > 2) { - c = nodes[2]; - d3_layout_packPlace(a, b, c); - bound(c); - d3_layout_packInsert(a, c); - a._pack_prev = c; - d3_layout_packInsert(c, b); - b = a._pack_next; - for (i = 3; i < n; i++) { - d3_layout_packPlace(a, b, c = nodes[i]); - var isect = 0, s1 = 1, s2 = 1; - for (j = b._pack_next; j !== b; j = j._pack_next, s1++) { - if (d3_layout_packIntersects(j, c)) { - isect = 1; - break; - } - } - if (isect == 1) { - for (k = a._pack_prev; k !== j._pack_prev; k = k._pack_prev, s2++) { - if (d3_layout_packIntersects(k, c)) { - break; - } - } - } - if (isect) { - if (s1 < s2 || s1 == s2 && b.r < a.r) d3_layout_packSplice(a, b = j); else d3_layout_packSplice(a = k, b); - i--; - } else { - d3_layout_packInsert(a, c); - b = c; - bound(c); - } - } - } - } - var cx = (xMin + xMax) / 2, cy = (yMin + yMax) / 2, cr = 0; - for (i = 0; i < n; i++) { - c = nodes[i]; - c.x -= cx; - c.y -= cy; - cr = Math.max(cr, c.r + Math.sqrt(c.x * c.x + c.y * c.y)); - } - node.r = cr; - nodes.forEach(d3_layout_packUnlink); - } - function d3_layout_packLink(node) { - node._pack_next = node._pack_prev = node; - } - function d3_layout_packUnlink(node) { - delete node._pack_next; - delete node._pack_prev; - } - function d3_layout_packTransform(node, x, y, k) { - var children = node.children; - node.x = x += k * node.x; - node.y = y += k * node.y; - node.r *= k; - if (children) { - var i = -1, n = children.length; - while (++i < n) d3_layout_packTransform(children[i], x, y, k); - } - } - function d3_layout_packPlace(a, b, c) { - var db = a.r + c.r, dx = b.x - a.x, dy = b.y - a.y; - if (db && (dx || dy)) { - var da = b.r + c.r, dc = dx * dx + dy * dy; - da *= da; - db *= db; - var x = .5 + (db - da) / (2 * dc), y = Math.sqrt(Math.max(0, 2 * da * (db + dc) - (db -= dc) * db - da * da)) / (2 * dc); - c.x = a.x + x * dx + y * dy; - c.y = a.y + x * dy - y * dx; - } else { - c.x = a.x + db; - c.y = a.y; - } - } - d3.layout.tree = function() { - var hierarchy = d3.layout.hierarchy().sort(null).value(null), separation = d3_layout_treeSeparation, size = [ 1, 1 ], nodeSize = null; - function tree(d, i) { - var nodes = hierarchy.call(this, d, i), root0 = nodes[0], root1 = wrapTree(root0); - d3_layout_hierarchyVisitAfter(root1, firstWalk), root1.parent.m = -root1.z; - d3_layout_hierarchyVisitBefore(root1, secondWalk); - if (nodeSize) d3_layout_hierarchyVisitBefore(root0, sizeNode); else { - var left = root0, right = root0, bottom = root0; - d3_layout_hierarchyVisitBefore(root0, function(node) { - if (node.x < left.x) left = node; - if (node.x > right.x) right = node; - if (node.depth > bottom.depth) bottom = node; - }); - var tx = separation(left, right) / 2 - left.x, kx = size[0] / (right.x + separation(right, left) / 2 + tx), ky = size[1] / (bottom.depth || 1); - d3_layout_hierarchyVisitBefore(root0, function(node) { - node.x = (node.x + tx) * kx; - node.y = node.depth * ky; - }); - } - return nodes; - } - function wrapTree(root0) { - var root1 = { - A: null, - children: [ root0 ] - }, queue = [ root1 ], node1; - while ((node1 = queue.pop()) != null) { - for (var children = node1.children, child, i = 0, n = children.length; i < n; ++i) { - queue.push((children[i] = child = { - _: children[i], - parent: node1, - children: (child = children[i].children) && child.slice() || [], - A: null, - a: null, - z: 0, - m: 0, - c: 0, - s: 0, - t: null, - i: i - }).a = child); - } - } - return root1.children[0]; - } - function firstWalk(v) { - var children = v.children, siblings = v.parent.children, w = v.i ? siblings[v.i - 1] : null; - if (children.length) { - d3_layout_treeShift(v); - var midpoint = (children[0].z + children[children.length - 1].z) / 2; - if (w) { - v.z = w.z + separation(v._, w._); - v.m = v.z - midpoint; - } else { - v.z = midpoint; - } - } else if (w) { - v.z = w.z + separation(v._, w._); - } - v.parent.A = apportion(v, w, v.parent.A || siblings[0]); - } - function secondWalk(v) { - v._.x = v.z + v.parent.m; - v.m += v.parent.m; - } - function apportion(v, w, ancestor) { - if (w) { - var vip = v, vop = v, vim = w, vom = vip.parent.children[0], sip = vip.m, sop = vop.m, sim = vim.m, som = vom.m, shift; - while (vim = d3_layout_treeRight(vim), vip = d3_layout_treeLeft(vip), vim && vip) { - vom = d3_layout_treeLeft(vom); - vop = d3_layout_treeRight(vop); - vop.a = v; - shift = vim.z + sim - vip.z - sip + separation(vim._, vip._); - if (shift > 0) { - d3_layout_treeMove(d3_layout_treeAncestor(vim, v, ancestor), v, shift); - sip += shift; - sop += shift; - } - sim += vim.m; - sip += vip.m; - som += vom.m; - sop += vop.m; - } - if (vim && !d3_layout_treeRight(vop)) { - vop.t = vim; - vop.m += sim - sop; - } - if (vip && !d3_layout_treeLeft(vom)) { - vom.t = vip; - vom.m += sip - som; - ancestor = v; - } - } - return ancestor; - } - function sizeNode(node) { - node.x *= size[0]; - node.y = node.depth * size[1]; - } - tree.separation = function(x) { - if (!arguments.length) return separation; - separation = x; - return tree; - }; - tree.size = function(x) { - if (!arguments.length) return nodeSize ? null : size; - nodeSize = (size = x) == null ? sizeNode : null; - return tree; - }; - tree.nodeSize = function(x) { - if (!arguments.length) return nodeSize ? size : null; - nodeSize = (size = x) == null ? null : sizeNode; - return tree; - }; - return d3_layout_hierarchyRebind(tree, hierarchy); - }; - function d3_layout_treeSeparation(a, b) { - return a.parent == b.parent ? 1 : 2; - } - function d3_layout_treeLeft(v) { - var children = v.children; - return children.length ? children[0] : v.t; - } - function d3_layout_treeRight(v) { - var children = v.children, n; - return (n = children.length) ? children[n - 1] : v.t; - } - function d3_layout_treeMove(wm, wp, shift) { - var change = shift / (wp.i - wm.i); - wp.c -= change; - wp.s += shift; - wm.c += change; - wp.z += shift; - wp.m += shift; - } - function d3_layout_treeShift(v) { - var shift = 0, change = 0, children = v.children, i = children.length, w; - while (--i >= 0) { - w = children[i]; - w.z += shift; - w.m += shift; - shift += w.s + (change += w.c); - } - } - function d3_layout_treeAncestor(vim, v, ancestor) { - return vim.a.parent === v.parent ? vim.a : ancestor; - } - d3.layout.cluster = function() { - var hierarchy = d3.layout.hierarchy().sort(null).value(null), separation = d3_layout_treeSeparation, size = [ 1, 1 ], nodeSize = false; - function cluster(d, i) { - var nodes = hierarchy.call(this, d, i), root = nodes[0], previousNode, x = 0; - d3_layout_hierarchyVisitAfter(root, function(node) { - var children = node.children; - if (children && children.length) { - node.x = d3_layout_clusterX(children); - node.y = d3_layout_clusterY(children); - } else { - node.x = previousNode ? x += separation(node, previousNode) : 0; - node.y = 0; - previousNode = node; - } - }); - var left = d3_layout_clusterLeft(root), right = d3_layout_clusterRight(root), x0 = left.x - separation(left, right) / 2, x1 = right.x + separation(right, left) / 2; - d3_layout_hierarchyVisitAfter(root, nodeSize ? function(node) { - node.x = (node.x - root.x) * size[0]; - node.y = (root.y - node.y) * size[1]; - } : function(node) { - node.x = (node.x - x0) / (x1 - x0) * size[0]; - node.y = (1 - (root.y ? node.y / root.y : 1)) * size[1]; - }); - return nodes; - } - cluster.separation = function(x) { - if (!arguments.length) return separation; - separation = x; - return cluster; - }; - cluster.size = function(x) { - if (!arguments.length) return nodeSize ? null : size; - nodeSize = (size = x) == null; - return cluster; - }; - cluster.nodeSize = function(x) { - if (!arguments.length) return nodeSize ? size : null; - nodeSize = (size = x) != null; - return cluster; - }; - return d3_layout_hierarchyRebind(cluster, hierarchy); - }; - function d3_layout_clusterY(children) { - return 1 + d3.max(children, function(child) { - return child.y; - }); - } - function d3_layout_clusterX(children) { - return children.reduce(function(x, child) { - return x + child.x; - }, 0) / children.length; - } - function d3_layout_clusterLeft(node) { - var children = node.children; - return children && children.length ? d3_layout_clusterLeft(children[0]) : node; - } - function d3_layout_clusterRight(node) { - var children = node.children, n; - return children && (n = children.length) ? d3_layout_clusterRight(children[n - 1]) : node; - } - d3.layout.treemap = function() { - var hierarchy = d3.layout.hierarchy(), round = Math.round, size = [ 1, 1 ], padding = null, pad = d3_layout_treemapPadNull, sticky = false, stickies, mode = "squarify", ratio = .5 * (1 + Math.sqrt(5)); - function scale(children, k) { - var i = -1, n = children.length, child, area; - while (++i < n) { - area = (child = children[i]).value * (k < 0 ? 0 : k); - child.area = isNaN(area) || area <= 0 ? 0 : area; - } - } - function squarify(node) { - var children = node.children; - if (children && children.length) { - var rect = pad(node), row = [], remaining = children.slice(), child, best = Infinity, score, u = mode === "slice" ? rect.dx : mode === "dice" ? rect.dy : mode === "slice-dice" ? node.depth & 1 ? rect.dy : rect.dx : Math.min(rect.dx, rect.dy), n; - scale(remaining, rect.dx * rect.dy / node.value); - row.area = 0; - while ((n = remaining.length) > 0) { - row.push(child = remaining[n - 1]); - row.area += child.area; - if (mode !== "squarify" || (score = worst(row, u)) <= best) { - remaining.pop(); - best = score; - } else { - row.area -= row.pop().area; - position(row, u, rect, false); - u = Math.min(rect.dx, rect.dy); - row.length = row.area = 0; - best = Infinity; - } - } - if (row.length) { - position(row, u, rect, true); - row.length = row.area = 0; - } - children.forEach(squarify); - } - } - function stickify(node) { - var children = node.children; - if (children && children.length) { - var rect = pad(node), remaining = children.slice(), child, row = []; - scale(remaining, rect.dx * rect.dy / node.value); - row.area = 0; - while (child = remaining.pop()) { - row.push(child); - row.area += child.area; - if (child.z != null) { - position(row, child.z ? rect.dx : rect.dy, rect, !remaining.length); - row.length = row.area = 0; - } - } - children.forEach(stickify); - } - } - function worst(row, u) { - var s = row.area, r, rmax = 0, rmin = Infinity, i = -1, n = row.length; - while (++i < n) { - if (!(r = row[i].area)) continue; - if (r < rmin) rmin = r; - if (r > rmax) rmax = r; - } - s *= s; - u *= u; - return s ? Math.max(u * rmax * ratio / s, s / (u * rmin * ratio)) : Infinity; - } - function position(row, u, rect, flush) { - var i = -1, n = row.length, x = rect.x, y = rect.y, v = u ? round(row.area / u) : 0, o; - if (u == rect.dx) { - if (flush || v > rect.dy) v = rect.dy; - while (++i < n) { - o = row[i]; - o.x = x; - o.y = y; - o.dy = v; - x += o.dx = Math.min(rect.x + rect.dx - x, v ? round(o.area / v) : 0); - } - o.z = true; - o.dx += rect.x + rect.dx - x; - rect.y += v; - rect.dy -= v; - } else { - if (flush || v > rect.dx) v = rect.dx; - while (++i < n) { - o = row[i]; - o.x = x; - o.y = y; - o.dx = v; - y += o.dy = Math.min(rect.y + rect.dy - y, v ? round(o.area / v) : 0); - } - o.z = false; - o.dy += rect.y + rect.dy - y; - rect.x += v; - rect.dx -= v; - } - } - function treemap(d) { - var nodes = stickies || hierarchy(d), root = nodes[0]; - root.x = 0; - root.y = 0; - root.dx = size[0]; - root.dy = size[1]; - if (stickies) hierarchy.revalue(root); - scale([ root ], root.dx * root.dy / root.value); - (stickies ? stickify : squarify)(root); - if (sticky) stickies = nodes; - return nodes; - } - treemap.size = function(x) { - if (!arguments.length) return size; - size = x; - return treemap; - }; - treemap.padding = function(x) { - if (!arguments.length) return padding; - function padFunction(node) { - var p = x.call(treemap, node, node.depth); - return p == null ? d3_layout_treemapPadNull(node) : d3_layout_treemapPad(node, typeof p === "number" ? [ p, p, p, p ] : p); - } - function padConstant(node) { - return d3_layout_treemapPad(node, x); - } - var type; - pad = (padding = x) == null ? d3_layout_treemapPadNull : (type = typeof x) === "function" ? padFunction : type === "number" ? (x = [ x, x, x, x ], - padConstant) : padConstant; - return treemap; - }; - treemap.round = function(x) { - if (!arguments.length) return round != Number; - round = x ? Math.round : Number; - return treemap; - }; - treemap.sticky = function(x) { - if (!arguments.length) return sticky; - sticky = x; - stickies = null; - return treemap; - }; - treemap.ratio = function(x) { - if (!arguments.length) return ratio; - ratio = x; - return treemap; - }; - treemap.mode = function(x) { - if (!arguments.length) return mode; - mode = x + ""; - return treemap; - }; - return d3_layout_hierarchyRebind(treemap, hierarchy); - }; - function d3_layout_treemapPadNull(node) { - return { - x: node.x, - y: node.y, - dx: node.dx, - dy: node.dy - }; - } - function d3_layout_treemapPad(node, padding) { - var x = node.x + padding[3], y = node.y + padding[0], dx = node.dx - padding[1] - padding[3], dy = node.dy - padding[0] - padding[2]; - if (dx < 0) { - x += dx / 2; - dx = 0; - } - if (dy < 0) { - y += dy / 2; - dy = 0; - } - return { - x: x, - y: y, - dx: dx, - dy: dy - }; - } - d3.random = { - normal: function(µ, σ) { - var n = arguments.length; - if (n < 2) σ = 1; - if (n < 1) µ = 0; - return function() { - var x, y, r; - do { - x = Math.random() * 2 - 1; - y = Math.random() * 2 - 1; - r = x * x + y * y; - } while (!r || r > 1); - return µ + σ * x * Math.sqrt(-2 * Math.log(r) / r); - }; - }, - logNormal: function() { - var random = d3.random.normal.apply(d3, arguments); - return function() { - return Math.exp(random()); - }; - }, - bates: function(m) { - var random = d3.random.irwinHall(m); - return function() { - return random() / m; - }; - }, - irwinHall: function(m) { - return function() { - for (var s = 0, j = 0; j < m; j++) s += Math.random(); - return s; - }; - } - }; - d3.scale = {}; - function d3_scaleExtent(domain) { - var start = domain[0], stop = domain[domain.length - 1]; - return start < stop ? [ start, stop ] : [ stop, start ]; - } - function d3_scaleRange(scale) { - return scale.rangeExtent ? scale.rangeExtent() : d3_scaleExtent(scale.range()); - } - function d3_scale_bilinear(domain, range, uninterpolate, interpolate) { - var u = uninterpolate(domain[0], domain[1]), i = interpolate(range[0], range[1]); - return function(x) { - return i(u(x)); - }; - } - function d3_scale_nice(domain, nice) { - var i0 = 0, i1 = domain.length - 1, x0 = domain[i0], x1 = domain[i1], dx; - if (x1 < x0) { - dx = i0, i0 = i1, i1 = dx; - dx = x0, x0 = x1, x1 = dx; - } - domain[i0] = nice.floor(x0); - domain[i1] = nice.ceil(x1); - return domain; - } - function d3_scale_niceStep(step) { - return step ? { - floor: function(x) { - return Math.floor(x / step) * step; - }, - ceil: function(x) { - return Math.ceil(x / step) * step; - } - } : d3_scale_niceIdentity; - } - var d3_scale_niceIdentity = { - floor: d3_identity, - ceil: d3_identity - }; - function d3_scale_polylinear(domain, range, uninterpolate, interpolate) { - var u = [], i = [], j = 0, k = Math.min(domain.length, range.length) - 1; - if (domain[k] < domain[0]) { - domain = domain.slice().reverse(); - range = range.slice().reverse(); - } - while (++j <= k) { - u.push(uninterpolate(domain[j - 1], domain[j])); - i.push(interpolate(range[j - 1], range[j])); - } - return function(x) { - var j = d3.bisect(domain, x, 1, k) - 1; - return i[j](u[j](x)); - }; - } - d3.scale.linear = function() { - return d3_scale_linear([ 0, 1 ], [ 0, 1 ], d3_interpolate, false); - }; - function d3_scale_linear(domain, range, interpolate, clamp) { - var output, input; - function rescale() { - var linear = Math.min(domain.length, range.length) > 2 ? d3_scale_polylinear : d3_scale_bilinear, uninterpolate = clamp ? d3_uninterpolateClamp : d3_uninterpolateNumber; - output = linear(domain, range, uninterpolate, interpolate); - input = linear(range, domain, uninterpolate, d3_interpolate); - return scale; - } - function scale(x) { - return output(x); - } - scale.invert = function(y) { - return input(y); - }; - scale.domain = function(x) { - if (!arguments.length) return domain; - domain = x.map(Number); - return rescale(); - }; - scale.range = function(x) { - if (!arguments.length) return range; - range = x; - return rescale(); - }; - scale.rangeRound = function(x) { - return scale.range(x).interpolate(d3_interpolateRound); - }; - scale.clamp = function(x) { - if (!arguments.length) return clamp; - clamp = x; - return rescale(); - }; - scale.interpolate = function(x) { - if (!arguments.length) return interpolate; - interpolate = x; - return rescale(); - }; - scale.ticks = function(m) { - return d3_scale_linearTicks(domain, m); - }; - scale.tickFormat = function(m, format) { - return d3_scale_linearTickFormat(domain, m, format); - }; - scale.nice = function(m) { - d3_scale_linearNice(domain, m); - return rescale(); - }; - scale.copy = function() { - return d3_scale_linear(domain, range, interpolate, clamp); - }; - return rescale(); - } - function d3_scale_linearRebind(scale, linear) { - return d3.rebind(scale, linear, "range", "rangeRound", "interpolate", "clamp"); - } - function d3_scale_linearNice(domain, m) { - return d3_scale_nice(domain, d3_scale_niceStep(d3_scale_linearTickRange(domain, m)[2])); - } - function d3_scale_linearTickRange(domain, m) { - if (m == null) m = 10; - var extent = d3_scaleExtent(domain), span = extent[1] - extent[0], step = Math.pow(10, Math.floor(Math.log(span / m) / Math.LN10)), err = m / span * step; - if (err <= .15) step *= 10; else if (err <= .35) step *= 5; else if (err <= .75) step *= 2; - extent[0] = Math.ceil(extent[0] / step) * step; - extent[1] = Math.floor(extent[1] / step) * step + step * .5; - extent[2] = step; - return extent; - } - function d3_scale_linearTicks(domain, m) { - return d3.range.apply(d3, d3_scale_linearTickRange(domain, m)); - } - function d3_scale_linearTickFormat(domain, m, format) { - var range = d3_scale_linearTickRange(domain, m); - if (format) { - var match = d3_format_re.exec(format); - match.shift(); - if (match[8] === "s") { - var prefix = d3.formatPrefix(Math.max(abs(range[0]), abs(range[1]))); - if (!match[7]) match[7] = "." + d3_scale_linearPrecision(prefix.scale(range[2])); - match[8] = "f"; - format = d3.format(match.join("")); - return function(d) { - return format(prefix.scale(d)) + prefix.symbol; - }; - } - if (!match[7]) match[7] = "." + d3_scale_linearFormatPrecision(match[8], range); - format = match.join(""); - } else { - format = ",." + d3_scale_linearPrecision(range[2]) + "f"; - } - return d3.format(format); - } - var d3_scale_linearFormatSignificant = { - s: 1, - g: 1, - p: 1, - r: 1, - e: 1 - }; - function d3_scale_linearPrecision(value) { - return -Math.floor(Math.log(value) / Math.LN10 + .01); - } - function d3_scale_linearFormatPrecision(type, range) { - var p = d3_scale_linearPrecision(range[2]); - return type in d3_scale_linearFormatSignificant ? Math.abs(p - d3_scale_linearPrecision(Math.max(abs(range[0]), abs(range[1])))) + +(type !== "e") : p - (type === "%") * 2; - } - d3.scale.log = function() { - return d3_scale_log(d3.scale.linear().domain([ 0, 1 ]), 10, true, [ 1, 10 ]); - }; - function d3_scale_log(linear, base, positive, domain) { - function log(x) { - return (positive ? Math.log(x < 0 ? 0 : x) : -Math.log(x > 0 ? 0 : -x)) / Math.log(base); - } - function pow(x) { - return positive ? Math.pow(base, x) : -Math.pow(base, -x); - } - function scale(x) { - return linear(log(x)); - } - scale.invert = function(x) { - return pow(linear.invert(x)); - }; - scale.domain = function(x) { - if (!arguments.length) return domain; - positive = x[0] >= 0; - linear.domain((domain = x.map(Number)).map(log)); - return scale; - }; - scale.base = function(_) { - if (!arguments.length) return base; - base = +_; - linear.domain(domain.map(log)); - return scale; - }; - scale.nice = function() { - var niced = d3_scale_nice(domain.map(log), positive ? Math : d3_scale_logNiceNegative); - linear.domain(niced); - domain = niced.map(pow); - return scale; - }; - scale.ticks = function() { - var extent = d3_scaleExtent(domain), ticks = [], u = extent[0], v = extent[1], i = Math.floor(log(u)), j = Math.ceil(log(v)), n = base % 1 ? 2 : base; - if (isFinite(j - i)) { - if (positive) { - for (;i < j; i++) for (var k = 1; k < n; k++) ticks.push(pow(i) * k); - ticks.push(pow(i)); - } else { - ticks.push(pow(i)); - for (;i++ < j; ) for (var k = n - 1; k > 0; k--) ticks.push(pow(i) * k); - } - for (i = 0; ticks[i] < u; i++) {} - for (j = ticks.length; ticks[j - 1] > v; j--) {} - ticks = ticks.slice(i, j); - } - return ticks; - }; - scale.tickFormat = function(n, format) { - if (!arguments.length) return d3_scale_logFormat; - if (arguments.length < 2) format = d3_scale_logFormat; else if (typeof format !== "function") format = d3.format(format); - var k = Math.max(.1, n / scale.ticks().length), f = positive ? (e = 1e-12, Math.ceil) : (e = -1e-12, - Math.floor), e; - return function(d) { - return d / pow(f(log(d) + e)) <= k ? format(d) : ""; - }; - }; - scale.copy = function() { - return d3_scale_log(linear.copy(), base, positive, domain); - }; - return d3_scale_linearRebind(scale, linear); - } - var d3_scale_logFormat = d3.format(".0e"), d3_scale_logNiceNegative = { - floor: function(x) { - return -Math.ceil(-x); - }, - ceil: function(x) { - return -Math.floor(-x); - } - }; - d3.scale.pow = function() { - return d3_scale_pow(d3.scale.linear(), 1, [ 0, 1 ]); - }; - function d3_scale_pow(linear, exponent, domain) { - var powp = d3_scale_powPow(exponent), powb = d3_scale_powPow(1 / exponent); - function scale(x) { - return linear(powp(x)); - } - scale.invert = function(x) { - return powb(linear.invert(x)); - }; - scale.domain = function(x) { - if (!arguments.length) return domain; - linear.domain((domain = x.map(Number)).map(powp)); - return scale; - }; - scale.ticks = function(m) { - return d3_scale_linearTicks(domain, m); - }; - scale.tickFormat = function(m, format) { - return d3_scale_linearTickFormat(domain, m, format); - }; - scale.nice = function(m) { - return scale.domain(d3_scale_linearNice(domain, m)); - }; - scale.exponent = function(x) { - if (!arguments.length) return exponent; - powp = d3_scale_powPow(exponent = x); - powb = d3_scale_powPow(1 / exponent); - linear.domain(domain.map(powp)); - return scale; - }; - scale.copy = function() { - return d3_scale_pow(linear.copy(), exponent, domain); - }; - return d3_scale_linearRebind(scale, linear); - } - function d3_scale_powPow(e) { - return function(x) { - return x < 0 ? -Math.pow(-x, e) : Math.pow(x, e); - }; - } - d3.scale.sqrt = function() { - return d3.scale.pow().exponent(.5); - }; - d3.scale.ordinal = function() { - return d3_scale_ordinal([], { - t: "range", - a: [ [] ] - }); - }; - function d3_scale_ordinal(domain, ranger) { - var index, range, rangeBand; - function scale(x) { - return range[((index.get(x) || (ranger.t === "range" ? index.set(x, domain.push(x)) : NaN)) - 1) % range.length]; - } - function steps(start, step) { - return d3.range(domain.length).map(function(i) { - return start + step * i; - }); - } - scale.domain = function(x) { - if (!arguments.length) return domain; - domain = []; - index = new d3_Map(); - var i = -1, n = x.length, xi; - while (++i < n) if (!index.has(xi = x[i])) index.set(xi, domain.push(xi)); - return scale[ranger.t].apply(scale, ranger.a); - }; - scale.range = function(x) { - if (!arguments.length) return range; - range = x; - rangeBand = 0; - ranger = { - t: "range", - a: arguments - }; - return scale; - }; - scale.rangePoints = function(x, padding) { - if (arguments.length < 2) padding = 0; - var start = x[0], stop = x[1], step = (stop - start) / (Math.max(1, domain.length - 1) + padding); - range = steps(domain.length < 2 ? (start + stop) / 2 : start + step * padding / 2, step); - rangeBand = 0; - ranger = { - t: "rangePoints", - a: arguments - }; - return scale; - }; - scale.rangeBands = function(x, padding, outerPadding) { - if (arguments.length < 2) padding = 0; - if (arguments.length < 3) outerPadding = padding; - var reverse = x[1] < x[0], start = x[reverse - 0], stop = x[1 - reverse], step = (stop - start) / (domain.length - padding + 2 * outerPadding); - range = steps(start + step * outerPadding, step); - if (reverse) range.reverse(); - rangeBand = step * (1 - padding); - ranger = { - t: "rangeBands", - a: arguments - }; - return scale; - }; - scale.rangeRoundBands = function(x, padding, outerPadding) { - if (arguments.length < 2) padding = 0; - if (arguments.length < 3) outerPadding = padding; - var reverse = x[1] < x[0], start = x[reverse - 0], stop = x[1 - reverse], step = Math.floor((stop - start) / (domain.length - padding + 2 * outerPadding)), error = stop - start - (domain.length - padding) * step; - range = steps(start + Math.round(error / 2), step); - if (reverse) range.reverse(); - rangeBand = Math.round(step * (1 - padding)); - ranger = { - t: "rangeRoundBands", - a: arguments - }; - return scale; - }; - scale.rangeBand = function() { - return rangeBand; - }; - scale.rangeExtent = function() { - return d3_scaleExtent(ranger.a[0]); - }; - scale.copy = function() { - return d3_scale_ordinal(domain, ranger); - }; - return scale.domain(domain); - } - d3.scale.category10 = function() { - return d3.scale.ordinal().range(d3_category10); - }; - d3.scale.category20 = function() { - return d3.scale.ordinal().range(d3_category20); - }; - d3.scale.category20b = function() { - return d3.scale.ordinal().range(d3_category20b); - }; - d3.scale.category20c = function() { - return d3.scale.ordinal().range(d3_category20c); - }; - var d3_category10 = [ 2062260, 16744206, 2924588, 14034728, 9725885, 9197131, 14907330, 8355711, 12369186, 1556175 ].map(d3_rgbString); - var d3_category20 = [ 2062260, 11454440, 16744206, 16759672, 2924588, 10018698, 14034728, 16750742, 9725885, 12955861, 9197131, 12885140, 14907330, 16234194, 8355711, 13092807, 12369186, 14408589, 1556175, 10410725 ].map(d3_rgbString); - var d3_category20b = [ 3750777, 5395619, 7040719, 10264286, 6519097, 9216594, 11915115, 13556636, 9202993, 12426809, 15186514, 15190932, 8666169, 11356490, 14049643, 15177372, 8077683, 10834324, 13528509, 14589654 ].map(d3_rgbString); - var d3_category20c = [ 3244733, 7057110, 10406625, 13032431, 15095053, 16616764, 16625259, 16634018, 3253076, 7652470, 10607003, 13101504, 7695281, 10394312, 12369372, 14342891, 6513507, 9868950, 12434877, 14277081 ].map(d3_rgbString); - d3.scale.quantile = function() { - return d3_scale_quantile([], []); - }; - function d3_scale_quantile(domain, range) { - var thresholds; - function rescale() { - var k = 0, q = range.length; - thresholds = []; - while (++k < q) thresholds[k - 1] = d3.quantile(domain, k / q); - return scale; - } - function scale(x) { - if (!isNaN(x = +x)) return range[d3.bisect(thresholds, x)]; - } - scale.domain = function(x) { - if (!arguments.length) return domain; - domain = x.filter(d3_number).sort(d3_ascending); - return rescale(); - }; - scale.range = function(x) { - if (!arguments.length) return range; - range = x; - return rescale(); - }; - scale.quantiles = function() { - return thresholds; - }; - scale.invertExtent = function(y) { - y = range.indexOf(y); - return y < 0 ? [ NaN, NaN ] : [ y > 0 ? thresholds[y - 1] : domain[0], y < thresholds.length ? thresholds[y] : domain[domain.length - 1] ]; - }; - scale.copy = function() { - return d3_scale_quantile(domain, range); - }; - return rescale(); - } - d3.scale.quantize = function() { - return d3_scale_quantize(0, 1, [ 0, 1 ]); - }; - function d3_scale_quantize(x0, x1, range) { - var kx, i; - function scale(x) { - return range[Math.max(0, Math.min(i, Math.floor(kx * (x - x0))))]; - } - function rescale() { - kx = range.length / (x1 - x0); - i = range.length - 1; - return scale; - } - scale.domain = function(x) { - if (!arguments.length) return [ x0, x1 ]; - x0 = +x[0]; - x1 = +x[x.length - 1]; - return rescale(); - }; - scale.range = function(x) { - if (!arguments.length) return range; - range = x; - return rescale(); - }; - scale.invertExtent = function(y) { - y = range.indexOf(y); - y = y < 0 ? NaN : y / kx + x0; - return [ y, y + 1 / kx ]; - }; - scale.copy = function() { - return d3_scale_quantize(x0, x1, range); - }; - return rescale(); - } - d3.scale.threshold = function() { - return d3_scale_threshold([ .5 ], [ 0, 1 ]); - }; - function d3_scale_threshold(domain, range) { - function scale(x) { - if (x <= x) return range[d3.bisect(domain, x)]; - } - scale.domain = function(_) { - if (!arguments.length) return domain; - domain = _; - return scale; - }; - scale.range = function(_) { - if (!arguments.length) return range; - range = _; - return scale; - }; - scale.invertExtent = function(y) { - y = range.indexOf(y); - return [ domain[y - 1], domain[y] ]; - }; - scale.copy = function() { - return d3_scale_threshold(domain, range); - }; - return scale; - } - d3.scale.identity = function() { - return d3_scale_identity([ 0, 1 ]); - }; - function d3_scale_identity(domain) { - function identity(x) { - return +x; - } - identity.invert = identity; - identity.domain = identity.range = function(x) { - if (!arguments.length) return domain; - domain = x.map(identity); - return identity; - }; - identity.ticks = function(m) { - return d3_scale_linearTicks(domain, m); - }; - identity.tickFormat = function(m, format) { - return d3_scale_linearTickFormat(domain, m, format); - }; - identity.copy = function() { - return d3_scale_identity(domain); - }; - return identity; - } - d3.svg = {}; - d3.svg.arc = function() { - var innerRadius = d3_svg_arcInnerRadius, outerRadius = d3_svg_arcOuterRadius, startAngle = d3_svg_arcStartAngle, endAngle = d3_svg_arcEndAngle; - function arc() { - var r0 = innerRadius.apply(this, arguments), r1 = outerRadius.apply(this, arguments), a0 = startAngle.apply(this, arguments) + d3_svg_arcOffset, a1 = endAngle.apply(this, arguments) + d3_svg_arcOffset, da = (a1 < a0 && (da = a0, - a0 = a1, a1 = da), a1 - a0), df = da < π ? "0" : "1", c0 = Math.cos(a0), s0 = Math.sin(a0), c1 = Math.cos(a1), s1 = Math.sin(a1); - return da >= d3_svg_arcMax ? r0 ? "M0," + r1 + "A" + r1 + "," + r1 + " 0 1,1 0," + -r1 + "A" + r1 + "," + r1 + " 0 1,1 0," + r1 + "M0," + r0 + "A" + r0 + "," + r0 + " 0 1,0 0," + -r0 + "A" + r0 + "," + r0 + " 0 1,0 0," + r0 + "Z" : "M0," + r1 + "A" + r1 + "," + r1 + " 0 1,1 0," + -r1 + "A" + r1 + "," + r1 + " 0 1,1 0," + r1 + "Z" : r0 ? "M" + r1 * c0 + "," + r1 * s0 + "A" + r1 + "," + r1 + " 0 " + df + ",1 " + r1 * c1 + "," + r1 * s1 + "L" + r0 * c1 + "," + r0 * s1 + "A" + r0 + "," + r0 + " 0 " + df + ",0 " + r0 * c0 + "," + r0 * s0 + "Z" : "M" + r1 * c0 + "," + r1 * s0 + "A" + r1 + "," + r1 + " 0 " + df + ",1 " + r1 * c1 + "," + r1 * s1 + "L0,0" + "Z"; - } - arc.innerRadius = function(v) { - if (!arguments.length) return innerRadius; - innerRadius = d3_functor(v); - return arc; - }; - arc.outerRadius = function(v) { - if (!arguments.length) return outerRadius; - outerRadius = d3_functor(v); - return arc; - }; - arc.startAngle = function(v) { - if (!arguments.length) return startAngle; - startAngle = d3_functor(v); - return arc; - }; - arc.endAngle = function(v) { - if (!arguments.length) return endAngle; - endAngle = d3_functor(v); - return arc; - }; - arc.centroid = function() { - var r = (innerRadius.apply(this, arguments) + outerRadius.apply(this, arguments)) / 2, a = (startAngle.apply(this, arguments) + endAngle.apply(this, arguments)) / 2 + d3_svg_arcOffset; - return [ Math.cos(a) * r, Math.sin(a) * r ]; - }; - return arc; - }; - var d3_svg_arcOffset = -halfπ, d3_svg_arcMax = τ - ε; - function d3_svg_arcInnerRadius(d) { - return d.innerRadius; - } - function d3_svg_arcOuterRadius(d) { - return d.outerRadius; - } - function d3_svg_arcStartAngle(d) { - return d.startAngle; - } - function d3_svg_arcEndAngle(d) { - return d.endAngle; - } - function d3_svg_line(projection) { - var x = d3_geom_pointX, y = d3_geom_pointY, defined = d3_true, interpolate = d3_svg_lineLinear, interpolateKey = interpolate.key, tension = .7; - function line(data) { - var segments = [], points = [], i = -1, n = data.length, d, fx = d3_functor(x), fy = d3_functor(y); - function segment() { - segments.push("M", interpolate(projection(points), tension)); - } - while (++i < n) { - if (defined.call(this, d = data[i], i)) { - points.push([ +fx.call(this, d, i), +fy.call(this, d, i) ]); - } else if (points.length) { - segment(); - points = []; - } - } - if (points.length) segment(); - return segments.length ? segments.join("") : null; - } - line.x = function(_) { - if (!arguments.length) return x; - x = _; - return line; - }; - line.y = function(_) { - if (!arguments.length) return y; - y = _; - return line; - }; - line.defined = function(_) { - if (!arguments.length) return defined; - defined = _; - return line; - }; - line.interpolate = function(_) { - if (!arguments.length) return interpolateKey; - if (typeof _ === "function") interpolateKey = interpolate = _; else interpolateKey = (interpolate = d3_svg_lineInterpolators.get(_) || d3_svg_lineLinear).key; - return line; - }; - line.tension = function(_) { - if (!arguments.length) return tension; - tension = _; - return line; - }; - return line; - } - d3.svg.line = function() { - return d3_svg_line(d3_identity); - }; - var d3_svg_lineInterpolators = d3.map({ - linear: d3_svg_lineLinear, - "linear-closed": d3_svg_lineLinearClosed, - step: d3_svg_lineStep, - "step-before": d3_svg_lineStepBefore, - "step-after": d3_svg_lineStepAfter, - basis: d3_svg_lineBasis, - "basis-open": d3_svg_lineBasisOpen, - "basis-closed": d3_svg_lineBasisClosed, - bundle: d3_svg_lineBundle, - cardinal: d3_svg_lineCardinal, - "cardinal-open": d3_svg_lineCardinalOpen, - "cardinal-closed": d3_svg_lineCardinalClosed, - monotone: d3_svg_lineMonotone - }); - d3_svg_lineInterpolators.forEach(function(key, value) { - value.key = key; - value.closed = /-closed$/.test(key); - }); - function d3_svg_lineLinear(points) { - return points.join("L"); - } - function d3_svg_lineLinearClosed(points) { - return d3_svg_lineLinear(points) + "Z"; - } - function d3_svg_lineStep(points) { - var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ]; - while (++i < n) path.push("H", (p[0] + (p = points[i])[0]) / 2, "V", p[1]); - if (n > 1) path.push("H", p[0]); - return path.join(""); - } - function d3_svg_lineStepBefore(points) { - var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ]; - while (++i < n) path.push("V", (p = points[i])[1], "H", p[0]); - return path.join(""); - } - function d3_svg_lineStepAfter(points) { - var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ]; - while (++i < n) path.push("H", (p = points[i])[0], "V", p[1]); - return path.join(""); - } - function d3_svg_lineCardinalOpen(points, tension) { - return points.length < 4 ? d3_svg_lineLinear(points) : points[1] + d3_svg_lineHermite(points.slice(1, points.length - 1), d3_svg_lineCardinalTangents(points, tension)); - } - function d3_svg_lineCardinalClosed(points, tension) { - return points.length < 3 ? d3_svg_lineLinear(points) : points[0] + d3_svg_lineHermite((points.push(points[0]), - points), d3_svg_lineCardinalTangents([ points[points.length - 2] ].concat(points, [ points[1] ]), tension)); - } - function d3_svg_lineCardinal(points, tension) { - return points.length < 3 ? d3_svg_lineLinear(points) : points[0] + d3_svg_lineHermite(points, d3_svg_lineCardinalTangents(points, tension)); - } - function d3_svg_lineHermite(points, tangents) { - if (tangents.length < 1 || points.length != tangents.length && points.length != tangents.length + 2) { - return d3_svg_lineLinear(points); - } - var quad = points.length != tangents.length, path = "", p0 = points[0], p = points[1], t0 = tangents[0], t = t0, pi = 1; - if (quad) { - path += "Q" + (p[0] - t0[0] * 2 / 3) + "," + (p[1] - t0[1] * 2 / 3) + "," + p[0] + "," + p[1]; - p0 = points[1]; - pi = 2; - } - if (tangents.length > 1) { - t = tangents[1]; - p = points[pi]; - pi++; - path += "C" + (p0[0] + t0[0]) + "," + (p0[1] + t0[1]) + "," + (p[0] - t[0]) + "," + (p[1] - t[1]) + "," + p[0] + "," + p[1]; - for (var i = 2; i < tangents.length; i++, pi++) { - p = points[pi]; - t = tangents[i]; - path += "S" + (p[0] - t[0]) + "," + (p[1] - t[1]) + "," + p[0] + "," + p[1]; - } - } - if (quad) { - var lp = points[pi]; - path += "Q" + (p[0] + t[0] * 2 / 3) + "," + (p[1] + t[1] * 2 / 3) + "," + lp[0] + "," + lp[1]; - } - return path; - } - function d3_svg_lineCardinalTangents(points, tension) { - var tangents = [], a = (1 - tension) / 2, p0, p1 = points[0], p2 = points[1], i = 1, n = points.length; - while (++i < n) { - p0 = p1; - p1 = p2; - p2 = points[i]; - tangents.push([ a * (p2[0] - p0[0]), a * (p2[1] - p0[1]) ]); - } - return tangents; - } - function d3_svg_lineBasis(points) { - if (points.length < 3) return d3_svg_lineLinear(points); - var i = 1, n = points.length, pi = points[0], x0 = pi[0], y0 = pi[1], px = [ x0, x0, x0, (pi = points[1])[0] ], py = [ y0, y0, y0, pi[1] ], path = [ x0, ",", y0, "L", d3_svg_lineDot4(d3_svg_lineBasisBezier3, px), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, py) ]; - points.push(points[n - 1]); - while (++i <= n) { - pi = points[i]; - px.shift(); - px.push(pi[0]); - py.shift(); - py.push(pi[1]); - d3_svg_lineBasisBezier(path, px, py); - } - points.pop(); - path.push("L", pi); - return path.join(""); - } - function d3_svg_lineBasisOpen(points) { - if (points.length < 4) return d3_svg_lineLinear(points); - var path = [], i = -1, n = points.length, pi, px = [ 0 ], py = [ 0 ]; - while (++i < 3) { - pi = points[i]; - px.push(pi[0]); - py.push(pi[1]); - } - path.push(d3_svg_lineDot4(d3_svg_lineBasisBezier3, px) + "," + d3_svg_lineDot4(d3_svg_lineBasisBezier3, py)); - --i; - while (++i < n) { - pi = points[i]; - px.shift(); - px.push(pi[0]); - py.shift(); - py.push(pi[1]); - d3_svg_lineBasisBezier(path, px, py); - } - return path.join(""); - } - function d3_svg_lineBasisClosed(points) { - var path, i = -1, n = points.length, m = n + 4, pi, px = [], py = []; - while (++i < 4) { - pi = points[i % n]; - px.push(pi[0]); - py.push(pi[1]); - } - path = [ d3_svg_lineDot4(d3_svg_lineBasisBezier3, px), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, py) ]; - --i; - while (++i < m) { - pi = points[i % n]; - px.shift(); - px.push(pi[0]); - py.shift(); - py.push(pi[1]); - d3_svg_lineBasisBezier(path, px, py); - } - return path.join(""); - } - function d3_svg_lineBundle(points, tension) { - var n = points.length - 1; - if (n) { - var x0 = points[0][0], y0 = points[0][1], dx = points[n][0] - x0, dy = points[n][1] - y0, i = -1, p, t; - while (++i <= n) { - p = points[i]; - t = i / n; - p[0] = tension * p[0] + (1 - tension) * (x0 + t * dx); - p[1] = tension * p[1] + (1 - tension) * (y0 + t * dy); - } - } - return d3_svg_lineBasis(points); - } - function d3_svg_lineDot4(a, b) { - return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3]; - } - var d3_svg_lineBasisBezier1 = [ 0, 2 / 3, 1 / 3, 0 ], d3_svg_lineBasisBezier2 = [ 0, 1 / 3, 2 / 3, 0 ], d3_svg_lineBasisBezier3 = [ 0, 1 / 6, 2 / 3, 1 / 6 ]; - function d3_svg_lineBasisBezier(path, x, y) { - path.push("C", d3_svg_lineDot4(d3_svg_lineBasisBezier1, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier1, y), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier2, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier2, y), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, y)); - } - function d3_svg_lineSlope(p0, p1) { - return (p1[1] - p0[1]) / (p1[0] - p0[0]); - } - function d3_svg_lineFiniteDifferences(points) { - var i = 0, j = points.length - 1, m = [], p0 = points[0], p1 = points[1], d = m[0] = d3_svg_lineSlope(p0, p1); - while (++i < j) { - m[i] = (d + (d = d3_svg_lineSlope(p0 = p1, p1 = points[i + 1]))) / 2; - } - m[i] = d; - return m; - } - function d3_svg_lineMonotoneTangents(points) { - var tangents = [], d, a, b, s, m = d3_svg_lineFiniteDifferences(points), i = -1, j = points.length - 1; - while (++i < j) { - d = d3_svg_lineSlope(points[i], points[i + 1]); - if (abs(d) < ε) { - m[i] = m[i + 1] = 0; - } else { - a = m[i] / d; - b = m[i + 1] / d; - s = a * a + b * b; - if (s > 9) { - s = d * 3 / Math.sqrt(s); - m[i] = s * a; - m[i + 1] = s * b; - } - } - } - i = -1; - while (++i <= j) { - s = (points[Math.min(j, i + 1)][0] - points[Math.max(0, i - 1)][0]) / (6 * (1 + m[i] * m[i])); - tangents.push([ s || 0, m[i] * s || 0 ]); - } - return tangents; - } - function d3_svg_lineMonotone(points) { - return points.length < 3 ? d3_svg_lineLinear(points) : points[0] + d3_svg_lineHermite(points, d3_svg_lineMonotoneTangents(points)); - } - d3.svg.line.radial = function() { - var line = d3_svg_line(d3_svg_lineRadial); - line.radius = line.x, delete line.x; - line.angle = line.y, delete line.y; - return line; - }; - function d3_svg_lineRadial(points) { - var point, i = -1, n = points.length, r, a; - while (++i < n) { - point = points[i]; - r = point[0]; - a = point[1] + d3_svg_arcOffset; - point[0] = r * Math.cos(a); - point[1] = r * Math.sin(a); - } - return points; - } - function d3_svg_area(projection) { - var x0 = d3_geom_pointX, x1 = d3_geom_pointX, y0 = 0, y1 = d3_geom_pointY, defined = d3_true, interpolate = d3_svg_lineLinear, interpolateKey = interpolate.key, interpolateReverse = interpolate, L = "L", tension = .7; - function area(data) { - var segments = [], points0 = [], points1 = [], i = -1, n = data.length, d, fx0 = d3_functor(x0), fy0 = d3_functor(y0), fx1 = x0 === x1 ? function() { - return x; - } : d3_functor(x1), fy1 = y0 === y1 ? function() { - return y; - } : d3_functor(y1), x, y; - function segment() { - segments.push("M", interpolate(projection(points1), tension), L, interpolateReverse(projection(points0.reverse()), tension), "Z"); - } - while (++i < n) { - if (defined.call(this, d = data[i], i)) { - points0.push([ x = +fx0.call(this, d, i), y = +fy0.call(this, d, i) ]); - points1.push([ +fx1.call(this, d, i), +fy1.call(this, d, i) ]); - } else if (points0.length) { - segment(); - points0 = []; - points1 = []; - } - } - if (points0.length) segment(); - return segments.length ? segments.join("") : null; - } - area.x = function(_) { - if (!arguments.length) return x1; - x0 = x1 = _; - return area; - }; - area.x0 = function(_) { - if (!arguments.length) return x0; - x0 = _; - return area; - }; - area.x1 = function(_) { - if (!arguments.length) return x1; - x1 = _; - return area; - }; - area.y = function(_) { - if (!arguments.length) return y1; - y0 = y1 = _; - return area; - }; - area.y0 = function(_) { - if (!arguments.length) return y0; - y0 = _; - return area; - }; - area.y1 = function(_) { - if (!arguments.length) return y1; - y1 = _; - return area; - }; - area.defined = function(_) { - if (!arguments.length) return defined; - defined = _; - return area; - }; - area.interpolate = function(_) { - if (!arguments.length) return interpolateKey; - if (typeof _ === "function") interpolateKey = interpolate = _; else interpolateKey = (interpolate = d3_svg_lineInterpolators.get(_) || d3_svg_lineLinear).key; - interpolateReverse = interpolate.reverse || interpolate; - L = interpolate.closed ? "M" : "L"; - return area; - }; - area.tension = function(_) { - if (!arguments.length) return tension; - tension = _; - return area; - }; - return area; - } - d3_svg_lineStepBefore.reverse = d3_svg_lineStepAfter; - d3_svg_lineStepAfter.reverse = d3_svg_lineStepBefore; - d3.svg.area = function() { - return d3_svg_area(d3_identity); - }; - d3.svg.area.radial = function() { - var area = d3_svg_area(d3_svg_lineRadial); - area.radius = area.x, delete area.x; - area.innerRadius = area.x0, delete area.x0; - area.outerRadius = area.x1, delete area.x1; - area.angle = area.y, delete area.y; - area.startAngle = area.y0, delete area.y0; - area.endAngle = area.y1, delete area.y1; - return area; - }; - d3.svg.chord = function() { - var source = d3_source, target = d3_target, radius = d3_svg_chordRadius, startAngle = d3_svg_arcStartAngle, endAngle = d3_svg_arcEndAngle; - function chord(d, i) { - var s = subgroup(this, source, d, i), t = subgroup(this, target, d, i); - return "M" + s.p0 + arc(s.r, s.p1, s.a1 - s.a0) + (equals(s, t) ? curve(s.r, s.p1, s.r, s.p0) : curve(s.r, s.p1, t.r, t.p0) + arc(t.r, t.p1, t.a1 - t.a0) + curve(t.r, t.p1, s.r, s.p0)) + "Z"; - } - function subgroup(self, f, d, i) { - var subgroup = f.call(self, d, i), r = radius.call(self, subgroup, i), a0 = startAngle.call(self, subgroup, i) + d3_svg_arcOffset, a1 = endAngle.call(self, subgroup, i) + d3_svg_arcOffset; - return { - r: r, - a0: a0, - a1: a1, - p0: [ r * Math.cos(a0), r * Math.sin(a0) ], - p1: [ r * Math.cos(a1), r * Math.sin(a1) ] - }; - } - function equals(a, b) { - return a.a0 == b.a0 && a.a1 == b.a1; - } - function arc(r, p, a) { - return "A" + r + "," + r + " 0 " + +(a > π) + ",1 " + p; - } - function curve(r0, p0, r1, p1) { - return "Q 0,0 " + p1; - } - chord.radius = function(v) { - if (!arguments.length) return radius; - radius = d3_functor(v); - return chord; - }; - chord.source = function(v) { - if (!arguments.length) return source; - source = d3_functor(v); - return chord; - }; - chord.target = function(v) { - if (!arguments.length) return target; - target = d3_functor(v); - return chord; - }; - chord.startAngle = function(v) { - if (!arguments.length) return startAngle; - startAngle = d3_functor(v); - return chord; - }; - chord.endAngle = function(v) { - if (!arguments.length) return endAngle; - endAngle = d3_functor(v); - return chord; - }; - return chord; - }; - function d3_svg_chordRadius(d) { - return d.radius; - } - d3.svg.diagonal = function() { - var source = d3_source, target = d3_target, projection = d3_svg_diagonalProjection; - function diagonal(d, i) { - var p0 = source.call(this, d, i), p3 = target.call(this, d, i), m = (p0.y + p3.y) / 2, p = [ p0, { - x: p0.x, - y: m - }, { - x: p3.x, - y: m - }, p3 ]; - p = p.map(projection); - return "M" + p[0] + "C" + p[1] + " " + p[2] + " " + p[3]; - } - diagonal.source = function(x) { - if (!arguments.length) return source; - source = d3_functor(x); - return diagonal; - }; - diagonal.target = function(x) { - if (!arguments.length) return target; - target = d3_functor(x); - return diagonal; - }; - diagonal.projection = function(x) { - if (!arguments.length) return projection; - projection = x; - return diagonal; - }; - return diagonal; - }; - function d3_svg_diagonalProjection(d) { - return [ d.x, d.y ]; - } - d3.svg.diagonal.radial = function() { - var diagonal = d3.svg.diagonal(), projection = d3_svg_diagonalProjection, projection_ = diagonal.projection; - diagonal.projection = function(x) { - return arguments.length ? projection_(d3_svg_diagonalRadialProjection(projection = x)) : projection; - }; - return diagonal; - }; - function d3_svg_diagonalRadialProjection(projection) { - return function() { - var d = projection.apply(this, arguments), r = d[0], a = d[1] + d3_svg_arcOffset; - return [ r * Math.cos(a), r * Math.sin(a) ]; - }; - } - d3.svg.symbol = function() { - var type = d3_svg_symbolType, size = d3_svg_symbolSize; - function symbol(d, i) { - return (d3_svg_symbols.get(type.call(this, d, i)) || d3_svg_symbolCircle)(size.call(this, d, i)); - } - symbol.type = function(x) { - if (!arguments.length) return type; - type = d3_functor(x); - return symbol; - }; - symbol.size = function(x) { - if (!arguments.length) return size; - size = d3_functor(x); - return symbol; - }; - return symbol; - }; - function d3_svg_symbolSize() { - return 64; - } - function d3_svg_symbolType() { - return "circle"; - } - function d3_svg_symbolCircle(size) { - var r = Math.sqrt(size / π); - return "M0," + r + "A" + r + "," + r + " 0 1,1 0," + -r + "A" + r + "," + r + " 0 1,1 0," + r + "Z"; - } - var d3_svg_symbols = d3.map({ - circle: d3_svg_symbolCircle, - cross: function(size) { - var r = Math.sqrt(size / 5) / 2; - return "M" + -3 * r + "," + -r + "H" + -r + "V" + -3 * r + "H" + r + "V" + -r + "H" + 3 * r + "V" + r + "H" + r + "V" + 3 * r + "H" + -r + "V" + r + "H" + -3 * r + "Z"; - }, - diamond: function(size) { - var ry = Math.sqrt(size / (2 * d3_svg_symbolTan30)), rx = ry * d3_svg_symbolTan30; - return "M0," + -ry + "L" + rx + ",0" + " 0," + ry + " " + -rx + ",0" + "Z"; - }, - square: function(size) { - var r = Math.sqrt(size) / 2; - return "M" + -r + "," + -r + "L" + r + "," + -r + " " + r + "," + r + " " + -r + "," + r + "Z"; - }, - "triangle-down": function(size) { - var rx = Math.sqrt(size / d3_svg_symbolSqrt3), ry = rx * d3_svg_symbolSqrt3 / 2; - return "M0," + ry + "L" + rx + "," + -ry + " " + -rx + "," + -ry + "Z"; - }, - "triangle-up": function(size) { - var rx = Math.sqrt(size / d3_svg_symbolSqrt3), ry = rx * d3_svg_symbolSqrt3 / 2; - return "M0," + -ry + "L" + rx + "," + ry + " " + -rx + "," + ry + "Z"; - } - }); - d3.svg.symbolTypes = d3_svg_symbols.keys(); - var d3_svg_symbolSqrt3 = Math.sqrt(3), d3_svg_symbolTan30 = Math.tan(30 * d3_radians); - function d3_transition(groups, id) { - d3_subclass(groups, d3_transitionPrototype); - groups.id = id; - return groups; - } - var d3_transitionPrototype = [], d3_transitionId = 0, d3_transitionInheritId, d3_transitionInherit; - d3_transitionPrototype.call = d3_selectionPrototype.call; - d3_transitionPrototype.empty = d3_selectionPrototype.empty; - d3_transitionPrototype.node = d3_selectionPrototype.node; - d3_transitionPrototype.size = d3_selectionPrototype.size; - d3.transition = function(selection) { - return arguments.length ? d3_transitionInheritId ? selection.transition() : selection : d3_selectionRoot.transition(); - }; - d3.transition.prototype = d3_transitionPrototype; - d3_transitionPrototype.select = function(selector) { - var id = this.id, subgroups = [], subgroup, subnode, node; - selector = d3_selection_selector(selector); - for (var j = -1, m = this.length; ++j < m; ) { - subgroups.push(subgroup = []); - for (var group = this[j], i = -1, n = group.length; ++i < n; ) { - if ((node = group[i]) && (subnode = selector.call(node, node.__data__, i, j))) { - if ("__data__" in node) subnode.__data__ = node.__data__; - d3_transitionNode(subnode, i, id, node.__transition__[id]); - subgroup.push(subnode); - } else { - subgroup.push(null); - } - } - } - return d3_transition(subgroups, id); - }; - d3_transitionPrototype.selectAll = function(selector) { - var id = this.id, subgroups = [], subgroup, subnodes, node, subnode, transition; - selector = d3_selection_selectorAll(selector); - for (var j = -1, m = this.length; ++j < m; ) { - for (var group = this[j], i = -1, n = group.length; ++i < n; ) { - if (node = group[i]) { - transition = node.__transition__[id]; - subnodes = selector.call(node, node.__data__, i, j); - subgroups.push(subgroup = []); - for (var k = -1, o = subnodes.length; ++k < o; ) { - if (subnode = subnodes[k]) d3_transitionNode(subnode, k, id, transition); - subgroup.push(subnode); - } - } - } - } - return d3_transition(subgroups, id); - }; - d3_transitionPrototype.filter = function(filter) { - var subgroups = [], subgroup, group, node; - if (typeof filter !== "function") filter = d3_selection_filter(filter); - for (var j = 0, m = this.length; j < m; j++) { - subgroups.push(subgroup = []); - for (var group = this[j], i = 0, n = group.length; i < n; i++) { - if ((node = group[i]) && filter.call(node, node.__data__, i, j)) { - subgroup.push(node); - } - } - } - return d3_transition(subgroups, this.id); - }; - d3_transitionPrototype.tween = function(name, tween) { - var id = this.id; - if (arguments.length < 2) return this.node().__transition__[id].tween.get(name); - return d3_selection_each(this, tween == null ? function(node) { - node.__transition__[id].tween.remove(name); - } : function(node) { - node.__transition__[id].tween.set(name, tween); - }); - }; - function d3_transition_tween(groups, name, value, tween) { - var id = groups.id; - return d3_selection_each(groups, typeof value === "function" ? function(node, i, j) { - node.__transition__[id].tween.set(name, tween(value.call(node, node.__data__, i, j))); - } : (value = tween(value), function(node) { - node.__transition__[id].tween.set(name, value); - })); - } - d3_transitionPrototype.attr = function(nameNS, value) { - if (arguments.length < 2) { - for (value in nameNS) this.attr(value, nameNS[value]); - return this; - } - var interpolate = nameNS == "transform" ? d3_interpolateTransform : d3_interpolate, name = d3.ns.qualify(nameNS); - function attrNull() { - this.removeAttribute(name); - } - function attrNullNS() { - this.removeAttributeNS(name.space, name.local); - } - function attrTween(b) { - return b == null ? attrNull : (b += "", function() { - var a = this.getAttribute(name), i; - return a !== b && (i = interpolate(a, b), function(t) { - this.setAttribute(name, i(t)); - }); - }); - } - function attrTweenNS(b) { - return b == null ? attrNullNS : (b += "", function() { - var a = this.getAttributeNS(name.space, name.local), i; - return a !== b && (i = interpolate(a, b), function(t) { - this.setAttributeNS(name.space, name.local, i(t)); - }); - }); - } - return d3_transition_tween(this, "attr." + nameNS, value, name.local ? attrTweenNS : attrTween); - }; - d3_transitionPrototype.attrTween = function(nameNS, tween) { - var name = d3.ns.qualify(nameNS); - function attrTween(d, i) { - var f = tween.call(this, d, i, this.getAttribute(name)); - return f && function(t) { - this.setAttribute(name, f(t)); - }; - } - function attrTweenNS(d, i) { - var f = tween.call(this, d, i, this.getAttributeNS(name.space, name.local)); - return f && function(t) { - this.setAttributeNS(name.space, name.local, f(t)); - }; - } - return this.tween("attr." + nameNS, name.local ? attrTweenNS : attrTween); - }; - d3_transitionPrototype.style = function(name, value, priority) { - var n = arguments.length; - if (n < 3) { - if (typeof name !== "string") { - if (n < 2) value = ""; - for (priority in name) this.style(priority, name[priority], value); - return this; - } - priority = ""; - } - function styleNull() { - this.style.removeProperty(name); - } - function styleString(b) { - return b == null ? styleNull : (b += "", function() { - var a = d3_window.getComputedStyle(this, null).getPropertyValue(name), i; - return a !== b && (i = d3_interpolate(a, b), function(t) { - this.style.setProperty(name, i(t), priority); - }); - }); - } - return d3_transition_tween(this, "style." + name, value, styleString); - }; - d3_transitionPrototype.styleTween = function(name, tween, priority) { - if (arguments.length < 3) priority = ""; - function styleTween(d, i) { - var f = tween.call(this, d, i, d3_window.getComputedStyle(this, null).getPropertyValue(name)); - return f && function(t) { - this.style.setProperty(name, f(t), priority); - }; - } - return this.tween("style." + name, styleTween); - }; - d3_transitionPrototype.text = function(value) { - return d3_transition_tween(this, "text", value, d3_transition_text); - }; - function d3_transition_text(b) { - if (b == null) b = ""; - return function() { - this.textContent = b; - }; - } - d3_transitionPrototype.remove = function() { - return this.each("end.transition", function() { - var p; - if (this.__transition__.count < 2 && (p = this.parentNode)) p.removeChild(this); - }); - }; - d3_transitionPrototype.ease = function(value) { - var id = this.id; - if (arguments.length < 1) return this.node().__transition__[id].ease; - if (typeof value !== "function") value = d3.ease.apply(d3, arguments); - return d3_selection_each(this, function(node) { - node.__transition__[id].ease = value; - }); - }; - d3_transitionPrototype.delay = function(value) { - var id = this.id; - if (arguments.length < 1) return this.node().__transition__[id].delay; - return d3_selection_each(this, typeof value === "function" ? function(node, i, j) { - node.__transition__[id].delay = +value.call(node, node.__data__, i, j); - } : (value = +value, function(node) { - node.__transition__[id].delay = value; - })); - }; - d3_transitionPrototype.duration = function(value) { - var id = this.id; - if (arguments.length < 1) return this.node().__transition__[id].duration; - return d3_selection_each(this, typeof value === "function" ? function(node, i, j) { - node.__transition__[id].duration = Math.max(1, value.call(node, node.__data__, i, j)); - } : (value = Math.max(1, value), function(node) { - node.__transition__[id].duration = value; - })); - }; - d3_transitionPrototype.each = function(type, listener) { - var id = this.id; - if (arguments.length < 2) { - var inherit = d3_transitionInherit, inheritId = d3_transitionInheritId; - d3_transitionInheritId = id; - d3_selection_each(this, function(node, i, j) { - d3_transitionInherit = node.__transition__[id]; - type.call(node, node.__data__, i, j); - }); - d3_transitionInherit = inherit; - d3_transitionInheritId = inheritId; - } else { - d3_selection_each(this, function(node) { - var transition = node.__transition__[id]; - (transition.event || (transition.event = d3.dispatch("start", "end"))).on(type, listener); - }); - } - return this; - }; - d3_transitionPrototype.transition = function() { - var id0 = this.id, id1 = ++d3_transitionId, subgroups = [], subgroup, group, node, transition; - for (var j = 0, m = this.length; j < m; j++) { - subgroups.push(subgroup = []); - for (var group = this[j], i = 0, n = group.length; i < n; i++) { - if (node = group[i]) { - transition = Object.create(node.__transition__[id0]); - transition.delay += transition.duration; - d3_transitionNode(node, i, id1, transition); - } - subgroup.push(node); - } - } - return d3_transition(subgroups, id1); - }; - function d3_transitionNode(node, i, id, inherit) { - var lock = node.__transition__ || (node.__transition__ = { - active: 0, - count: 0 - }), transition = lock[id]; - if (!transition) { - var time = inherit.time; - transition = lock[id] = { - tween: new d3_Map(), - time: time, - ease: inherit.ease, - delay: inherit.delay, - duration: inherit.duration - }; - ++lock.count; - d3.timer(function(elapsed) { - var d = node.__data__, ease = transition.ease, delay = transition.delay, duration = transition.duration, timer = d3_timer_active, tweened = []; - timer.t = delay + time; - if (delay <= elapsed) return start(elapsed - delay); - timer.c = start; - function start(elapsed) { - if (lock.active > id) return stop(); - lock.active = id; - transition.event && transition.event.start.call(node, d, i); - transition.tween.forEach(function(key, value) { - if (value = value.call(node, d, i)) { - tweened.push(value); - } - }); - d3.timer(function() { - timer.c = tick(elapsed || 1) ? d3_true : tick; - return 1; - }, 0, time); - } - function tick(elapsed) { - if (lock.active !== id) return stop(); - var t = elapsed / duration, e = ease(t), n = tweened.length; - while (n > 0) { - tweened[--n].call(node, e); - } - if (t >= 1) { - transition.event && transition.event.end.call(node, d, i); - return stop(); - } - } - function stop() { - if (--lock.count) delete lock[id]; else delete node.__transition__; - return 1; - } - }, 0, time); - } - } - d3.svg.axis = function() { - var scale = d3.scale.linear(), orient = d3_svg_axisDefaultOrient, innerTickSize = 6, outerTickSize = 6, tickPadding = 3, tickArguments_ = [ 10 ], tickValues = null, tickFormat_; - function axis(g) { - g.each(function() { - var g = d3.select(this); - var scale0 = this.__chart__ || scale, scale1 = this.__chart__ = scale.copy(); - var ticks = tickValues == null ? scale1.ticks ? scale1.ticks.apply(scale1, tickArguments_) : scale1.domain() : tickValues, tickFormat = tickFormat_ == null ? scale1.tickFormat ? scale1.tickFormat.apply(scale1, tickArguments_) : d3_identity : tickFormat_, tick = g.selectAll(".tick").data(ticks, scale1), tickEnter = tick.enter().insert("g", ".domain").attr("class", "tick").style("opacity", ε), tickExit = d3.transition(tick.exit()).style("opacity", ε).remove(), tickUpdate = d3.transition(tick.order()).style("opacity", 1), tickTransform; - var range = d3_scaleRange(scale1), path = g.selectAll(".domain").data([ 0 ]), pathUpdate = (path.enter().append("path").attr("class", "domain"), - d3.transition(path)); - tickEnter.append("line"); - tickEnter.append("text"); - var lineEnter = tickEnter.select("line"), lineUpdate = tickUpdate.select("line"), text = tick.select("text").text(tickFormat), textEnter = tickEnter.select("text"), textUpdate = tickUpdate.select("text"); - switch (orient) { - case "bottom": - { - tickTransform = d3_svg_axisX; - lineEnter.attr("y2", innerTickSize); - textEnter.attr("y", Math.max(innerTickSize, 0) + tickPadding); - lineUpdate.attr("x2", 0).attr("y2", innerTickSize); - textUpdate.attr("x", 0).attr("y", Math.max(innerTickSize, 0) + tickPadding); - text.attr("dy", ".71em").style("text-anchor", "middle"); - pathUpdate.attr("d", "M" + range[0] + "," + outerTickSize + "V0H" + range[1] + "V" + outerTickSize); - break; - } - - case "top": - { - tickTransform = d3_svg_axisX; - lineEnter.attr("y2", -innerTickSize); - textEnter.attr("y", -(Math.max(innerTickSize, 0) + tickPadding)); - lineUpdate.attr("x2", 0).attr("y2", -innerTickSize); - textUpdate.attr("x", 0).attr("y", -(Math.max(innerTickSize, 0) + tickPadding)); - text.attr("dy", "0em").style("text-anchor", "middle"); - pathUpdate.attr("d", "M" + range[0] + "," + -outerTickSize + "V0H" + range[1] + "V" + -outerTickSize); - break; - } - - case "left": - { - tickTransform = d3_svg_axisY; - lineEnter.attr("x2", -innerTickSize); - textEnter.attr("x", -(Math.max(innerTickSize, 0) + tickPadding)); - lineUpdate.attr("x2", -innerTickSize).attr("y2", 0); - textUpdate.attr("x", -(Math.max(innerTickSize, 0) + tickPadding)).attr("y", 0); - text.attr("dy", ".32em").style("text-anchor", "end"); - pathUpdate.attr("d", "M" + -outerTickSize + "," + range[0] + "H0V" + range[1] + "H" + -outerTickSize); - break; - } - - case "right": - { - tickTransform = d3_svg_axisY; - lineEnter.attr("x2", innerTickSize); - textEnter.attr("x", Math.max(innerTickSize, 0) + tickPadding); - lineUpdate.attr("x2", innerTickSize).attr("y2", 0); - textUpdate.attr("x", Math.max(innerTickSize, 0) + tickPadding).attr("y", 0); - text.attr("dy", ".32em").style("text-anchor", "start"); - pathUpdate.attr("d", "M" + outerTickSize + "," + range[0] + "H0V" + range[1] + "H" + outerTickSize); - break; - } - } - if (scale1.rangeBand) { - var x = scale1, dx = x.rangeBand() / 2; - scale0 = scale1 = function(d) { - return x(d) + dx; - }; - } else if (scale0.rangeBand) { - scale0 = scale1; - } else { - tickExit.call(tickTransform, scale1); - } - tickEnter.call(tickTransform, scale0); - tickUpdate.call(tickTransform, scale1); - }); - } - axis.scale = function(x) { - if (!arguments.length) return scale; - scale = x; - return axis; - }; - axis.orient = function(x) { - if (!arguments.length) return orient; - orient = x in d3_svg_axisOrients ? x + "" : d3_svg_axisDefaultOrient; - return axis; - }; - axis.ticks = function() { - if (!arguments.length) return tickArguments_; - tickArguments_ = arguments; - return axis; - }; - axis.tickValues = function(x) { - if (!arguments.length) return tickValues; - tickValues = x; - return axis; - }; - axis.tickFormat = function(x) { - if (!arguments.length) return tickFormat_; - tickFormat_ = x; - return axis; - }; - axis.tickSize = function(x) { - var n = arguments.length; - if (!n) return innerTickSize; - innerTickSize = +x; - outerTickSize = +arguments[n - 1]; - return axis; - }; - axis.innerTickSize = function(x) { - if (!arguments.length) return innerTickSize; - innerTickSize = +x; - return axis; - }; - axis.outerTickSize = function(x) { - if (!arguments.length) return outerTickSize; - outerTickSize = +x; - return axis; - }; - axis.tickPadding = function(x) { - if (!arguments.length) return tickPadding; - tickPadding = +x; - return axis; - }; - axis.tickSubdivide = function() { - return arguments.length && axis; - }; - return axis; - }; - var d3_svg_axisDefaultOrient = "bottom", d3_svg_axisOrients = { - top: 1, - right: 1, - bottom: 1, - left: 1 - }; - function d3_svg_axisX(selection, x) { - selection.attr("transform", function(d) { - return "translate(" + x(d) + ",0)"; - }); - } - function d3_svg_axisY(selection, y) { - selection.attr("transform", function(d) { - return "translate(0," + y(d) + ")"; - }); - } - d3.svg.brush = function() { - var event = d3_eventDispatch(brush, "brushstart", "brush", "brushend"), x = null, y = null, xExtent = [ 0, 0 ], yExtent = [ 0, 0 ], xExtentDomain, yExtentDomain, xClamp = true, yClamp = true, resizes = d3_svg_brushResizes[0]; - function brush(g) { - g.each(function() { - var g = d3.select(this).style("pointer-events", "all").style("-webkit-tap-highlight-color", "rgba(0,0,0,0)").on("mousedown.brush", brushstart).on("touchstart.brush", brushstart); - var background = g.selectAll(".background").data([ 0 ]); - background.enter().append("rect").attr("class", "background").style("visibility", "hidden").style("cursor", "crosshair"); - g.selectAll(".extent").data([ 0 ]).enter().append("rect").attr("class", "extent").style("cursor", "move"); - var resize = g.selectAll(".resize").data(resizes, d3_identity); - resize.exit().remove(); - resize.enter().append("g").attr("class", function(d) { - return "resize " + d; - }).style("cursor", function(d) { - return d3_svg_brushCursor[d]; - }).append("rect").attr("x", function(d) { - return /[ew]$/.test(d) ? -3 : null; - }).attr("y", function(d) { - return /^[ns]/.test(d) ? -3 : null; - }).attr("width", 6).attr("height", 6).style("visibility", "hidden"); - resize.style("display", brush.empty() ? "none" : null); - var gUpdate = d3.transition(g), backgroundUpdate = d3.transition(background), range; - if (x) { - range = d3_scaleRange(x); - backgroundUpdate.attr("x", range[0]).attr("width", range[1] - range[0]); - redrawX(gUpdate); - } - if (y) { - range = d3_scaleRange(y); - backgroundUpdate.attr("y", range[0]).attr("height", range[1] - range[0]); - redrawY(gUpdate); - } - redraw(gUpdate); - }); - } - brush.event = function(g) { - g.each(function() { - var event_ = event.of(this, arguments), extent1 = { - x: xExtent, - y: yExtent, - i: xExtentDomain, - j: yExtentDomain - }, extent0 = this.__chart__ || extent1; - this.__chart__ = extent1; - if (d3_transitionInheritId) { - d3.select(this).transition().each("start.brush", function() { - xExtentDomain = extent0.i; - yExtentDomain = extent0.j; - xExtent = extent0.x; - yExtent = extent0.y; - event_({ - type: "brushstart" - }); - }).tween("brush:brush", function() { - var xi = d3_interpolateArray(xExtent, extent1.x), yi = d3_interpolateArray(yExtent, extent1.y); - xExtentDomain = yExtentDomain = null; - return function(t) { - xExtent = extent1.x = xi(t); - yExtent = extent1.y = yi(t); - event_({ - type: "brush", - mode: "resize" - }); - }; - }).each("end.brush", function() { - xExtentDomain = extent1.i; - yExtentDomain = extent1.j; - event_({ - type: "brush", - mode: "resize" - }); - event_({ - type: "brushend" - }); - }); - } else { - event_({ - type: "brushstart" - }); - event_({ - type: "brush", - mode: "resize" - }); - event_({ - type: "brushend" - }); - } - }); - }; - function redraw(g) { - g.selectAll(".resize").attr("transform", function(d) { - return "translate(" + xExtent[+/e$/.test(d)] + "," + yExtent[+/^s/.test(d)] + ")"; - }); - } - function redrawX(g) { - g.select(".extent").attr("x", xExtent[0]); - g.selectAll(".extent,.n>rect,.s>rect").attr("width", xExtent[1] - xExtent[0]); - } - function redrawY(g) { - g.select(".extent").attr("y", yExtent[0]); - g.selectAll(".extent,.e>rect,.w>rect").attr("height", yExtent[1] - yExtent[0]); - } - function brushstart() { - var target = this, eventTarget = d3.select(d3.event.target), event_ = event.of(target, arguments), g = d3.select(target), resizing = eventTarget.datum(), resizingX = !/^(n|s)$/.test(resizing) && x, resizingY = !/^(e|w)$/.test(resizing) && y, dragging = eventTarget.classed("extent"), dragRestore = d3_event_dragSuppress(), center, origin = d3.mouse(target), offset; - var w = d3.select(d3_window).on("keydown.brush", keydown).on("keyup.brush", keyup); - if (d3.event.changedTouches) { - w.on("touchmove.brush", brushmove).on("touchend.brush", brushend); - } else { - w.on("mousemove.brush", brushmove).on("mouseup.brush", brushend); - } - g.interrupt().selectAll("*").interrupt(); - if (dragging) { - origin[0] = xExtent[0] - origin[0]; - origin[1] = yExtent[0] - origin[1]; - } else if (resizing) { - var ex = +/w$/.test(resizing), ey = +/^n/.test(resizing); - offset = [ xExtent[1 - ex] - origin[0], yExtent[1 - ey] - origin[1] ]; - origin[0] = xExtent[ex]; - origin[1] = yExtent[ey]; - } else if (d3.event.altKey) center = origin.slice(); - g.style("pointer-events", "none").selectAll(".resize").style("display", null); - d3.select("body").style("cursor", eventTarget.style("cursor")); - event_({ - type: "brushstart" - }); - brushmove(); - function keydown() { - if (d3.event.keyCode == 32) { - if (!dragging) { - center = null; - origin[0] -= xExtent[1]; - origin[1] -= yExtent[1]; - dragging = 2; - } - d3_eventPreventDefault(); - } - } - function keyup() { - if (d3.event.keyCode == 32 && dragging == 2) { - origin[0] += xExtent[1]; - origin[1] += yExtent[1]; - dragging = 0; - d3_eventPreventDefault(); - } - } - function brushmove() { - var point = d3.mouse(target), moved = false; - if (offset) { - point[0] += offset[0]; - point[1] += offset[1]; - } - if (!dragging) { - if (d3.event.altKey) { - if (!center) center = [ (xExtent[0] + xExtent[1]) / 2, (yExtent[0] + yExtent[1]) / 2 ]; - origin[0] = xExtent[+(point[0] < center[0])]; - origin[1] = yExtent[+(point[1] < center[1])]; - } else center = null; - } - if (resizingX && move1(point, x, 0)) { - redrawX(g); - moved = true; - } - if (resizingY && move1(point, y, 1)) { - redrawY(g); - moved = true; - } - if (moved) { - redraw(g); - event_({ - type: "brush", - mode: dragging ? "move" : "resize" - }); - } - } - function move1(point, scale, i) { - var range = d3_scaleRange(scale), r0 = range[0], r1 = range[1], position = origin[i], extent = i ? yExtent : xExtent, size = extent[1] - extent[0], min, max; - if (dragging) { - r0 -= position; - r1 -= size + position; - } - min = (i ? yClamp : xClamp) ? Math.max(r0, Math.min(r1, point[i])) : point[i]; - if (dragging) { - max = (min += position) + size; - } else { - if (center) position = Math.max(r0, Math.min(r1, 2 * center[i] - min)); - if (position < min) { - max = min; - min = position; - } else { - max = position; - } - } - if (extent[0] != min || extent[1] != max) { - if (i) yExtentDomain = null; else xExtentDomain = null; - extent[0] = min; - extent[1] = max; - return true; - } - } - function brushend() { - brushmove(); - g.style("pointer-events", "all").selectAll(".resize").style("display", brush.empty() ? "none" : null); - d3.select("body").style("cursor", null); - w.on("mousemove.brush", null).on("mouseup.brush", null).on("touchmove.brush", null).on("touchend.brush", null).on("keydown.brush", null).on("keyup.brush", null); - dragRestore(); - event_({ - type: "brushend" - }); - } - } - brush.x = function(z) { - if (!arguments.length) return x; - x = z; - resizes = d3_svg_brushResizes[!x << 1 | !y]; - return brush; - }; - brush.y = function(z) { - if (!arguments.length) return y; - y = z; - resizes = d3_svg_brushResizes[!x << 1 | !y]; - return brush; - }; - brush.clamp = function(z) { - if (!arguments.length) return x && y ? [ xClamp, yClamp ] : x ? xClamp : y ? yClamp : null; - if (x && y) xClamp = !!z[0], yClamp = !!z[1]; else if (x) xClamp = !!z; else if (y) yClamp = !!z; - return brush; - }; - brush.extent = function(z) { - var x0, x1, y0, y1, t; - if (!arguments.length) { - if (x) { - if (xExtentDomain) { - x0 = xExtentDomain[0], x1 = xExtentDomain[1]; - } else { - x0 = xExtent[0], x1 = xExtent[1]; - if (x.invert) x0 = x.invert(x0), x1 = x.invert(x1); - if (x1 < x0) t = x0, x0 = x1, x1 = t; - } - } - if (y) { - if (yExtentDomain) { - y0 = yExtentDomain[0], y1 = yExtentDomain[1]; - } else { - y0 = yExtent[0], y1 = yExtent[1]; - if (y.invert) y0 = y.invert(y0), y1 = y.invert(y1); - if (y1 < y0) t = y0, y0 = y1, y1 = t; - } - } - return x && y ? [ [ x0, y0 ], [ x1, y1 ] ] : x ? [ x0, x1 ] : y && [ y0, y1 ]; - } - if (x) { - x0 = z[0], x1 = z[1]; - if (y) x0 = x0[0], x1 = x1[0]; - xExtentDomain = [ x0, x1 ]; - if (x.invert) x0 = x(x0), x1 = x(x1); - if (x1 < x0) t = x0, x0 = x1, x1 = t; - if (x0 != xExtent[0] || x1 != xExtent[1]) xExtent = [ x0, x1 ]; - } - if (y) { - y0 = z[0], y1 = z[1]; - if (x) y0 = y0[1], y1 = y1[1]; - yExtentDomain = [ y0, y1 ]; - if (y.invert) y0 = y(y0), y1 = y(y1); - if (y1 < y0) t = y0, y0 = y1, y1 = t; - if (y0 != yExtent[0] || y1 != yExtent[1]) yExtent = [ y0, y1 ]; - } - return brush; - }; - brush.clear = function() { - if (!brush.empty()) { - xExtent = [ 0, 0 ], yExtent = [ 0, 0 ]; - xExtentDomain = yExtentDomain = null; - } - return brush; - }; - brush.empty = function() { - return !!x && xExtent[0] == xExtent[1] || !!y && yExtent[0] == yExtent[1]; - }; - return d3.rebind(brush, event, "on"); - }; - var d3_svg_brushCursor = { - n: "ns-resize", - e: "ew-resize", - s: "ns-resize", - w: "ew-resize", - nw: "nwse-resize", - ne: "nesw-resize", - se: "nwse-resize", - sw: "nesw-resize" - }; - var d3_svg_brushResizes = [ [ "n", "e", "s", "w", "nw", "ne", "se", "sw" ], [ "e", "w" ], [ "n", "s" ], [] ]; - var d3_time_format = d3_time.format = d3_locale_enUS.timeFormat; - var d3_time_formatUtc = d3_time_format.utc; - var d3_time_formatIso = d3_time_formatUtc("%Y-%m-%dT%H:%M:%S.%LZ"); - d3_time_format.iso = Date.prototype.toISOString && +new Date("2000-01-01T00:00:00.000Z") ? d3_time_formatIsoNative : d3_time_formatIso; - function d3_time_formatIsoNative(date) { - return date.toISOString(); - } - d3_time_formatIsoNative.parse = function(string) { - var date = new Date(string); - return isNaN(date) ? null : date; - }; - d3_time_formatIsoNative.toString = d3_time_formatIso.toString; - d3_time.second = d3_time_interval(function(date) { - return new d3_date(Math.floor(date / 1e3) * 1e3); - }, function(date, offset) { - date.setTime(date.getTime() + Math.floor(offset) * 1e3); - }, function(date) { - return date.getSeconds(); - }); - d3_time.seconds = d3_time.second.range; - d3_time.seconds.utc = d3_time.second.utc.range; - d3_time.minute = d3_time_interval(function(date) { - return new d3_date(Math.floor(date / 6e4) * 6e4); - }, function(date, offset) { - date.setTime(date.getTime() + Math.floor(offset) * 6e4); - }, function(date) { - return date.getMinutes(); - }); - d3_time.minutes = d3_time.minute.range; - d3_time.minutes.utc = d3_time.minute.utc.range; - d3_time.hour = d3_time_interval(function(date) { - var timezone = date.getTimezoneOffset() / 60; - return new d3_date((Math.floor(date / 36e5 - timezone) + timezone) * 36e5); - }, function(date, offset) { - date.setTime(date.getTime() + Math.floor(offset) * 36e5); - }, function(date) { - return date.getHours(); - }); - d3_time.hours = d3_time.hour.range; - d3_time.hours.utc = d3_time.hour.utc.range; - d3_time.month = d3_time_interval(function(date) { - date = d3_time.day(date); - date.setDate(1); - return date; - }, function(date, offset) { - date.setMonth(date.getMonth() + offset); - }, function(date) { - return date.getMonth(); - }); - d3_time.months = d3_time.month.range; - d3_time.months.utc = d3_time.month.utc.range; - function d3_time_scale(linear, methods, format) { - function scale(x) { - return linear(x); - } - scale.invert = function(x) { - return d3_time_scaleDate(linear.invert(x)); - }; - scale.domain = function(x) { - if (!arguments.length) return linear.domain().map(d3_time_scaleDate); - linear.domain(x); - return scale; - }; - function tickMethod(extent, count) { - var span = extent[1] - extent[0], target = span / count, i = d3.bisect(d3_time_scaleSteps, target); - return i == d3_time_scaleSteps.length ? [ methods.year, d3_scale_linearTickRange(extent.map(function(d) { - return d / 31536e6; - }), count)[2] ] : !i ? [ d3_time_scaleMilliseconds, d3_scale_linearTickRange(extent, count)[2] ] : methods[target / d3_time_scaleSteps[i - 1] < d3_time_scaleSteps[i] / target ? i - 1 : i]; - } - scale.nice = function(interval, skip) { - var domain = scale.domain(), extent = d3_scaleExtent(domain), method = interval == null ? tickMethod(extent, 10) : typeof interval === "number" && tickMethod(extent, interval); - if (method) interval = method[0], skip = method[1]; - function skipped(date) { - return !isNaN(date) && !interval.range(date, d3_time_scaleDate(+date + 1), skip).length; - } - return scale.domain(d3_scale_nice(domain, skip > 1 ? { - floor: function(date) { - while (skipped(date = interval.floor(date))) date = d3_time_scaleDate(date - 1); - return date; - }, - ceil: function(date) { - while (skipped(date = interval.ceil(date))) date = d3_time_scaleDate(+date + 1); - return date; - } - } : interval)); - }; - scale.ticks = function(interval, skip) { - var extent = d3_scaleExtent(scale.domain()), method = interval == null ? tickMethod(extent, 10) : typeof interval === "number" ? tickMethod(extent, interval) : !interval.range && [ { - range: interval - }, skip ]; - if (method) interval = method[0], skip = method[1]; - return interval.range(extent[0], d3_time_scaleDate(+extent[1] + 1), skip < 1 ? 1 : skip); - }; - scale.tickFormat = function() { - return format; - }; - scale.copy = function() { - return d3_time_scale(linear.copy(), methods, format); - }; - return d3_scale_linearRebind(scale, linear); - } - function d3_time_scaleDate(t) { - return new Date(t); - } - var d3_time_scaleSteps = [ 1e3, 5e3, 15e3, 3e4, 6e4, 3e5, 9e5, 18e5, 36e5, 108e5, 216e5, 432e5, 864e5, 1728e5, 6048e5, 2592e6, 7776e6, 31536e6 ]; - var d3_time_scaleLocalMethods = [ [ d3_time.second, 1 ], [ d3_time.second, 5 ], [ d3_time.second, 15 ], [ d3_time.second, 30 ], [ d3_time.minute, 1 ], [ d3_time.minute, 5 ], [ d3_time.minute, 15 ], [ d3_time.minute, 30 ], [ d3_time.hour, 1 ], [ d3_time.hour, 3 ], [ d3_time.hour, 6 ], [ d3_time.hour, 12 ], [ d3_time.day, 1 ], [ d3_time.day, 2 ], [ d3_time.week, 1 ], [ d3_time.month, 1 ], [ d3_time.month, 3 ], [ d3_time.year, 1 ] ]; - var d3_time_scaleLocalFormat = d3_time_format.multi([ [ ".%L", function(d) { - return d.getMilliseconds(); - } ], [ ":%S", function(d) { - return d.getSeconds(); - } ], [ "%I:%M", function(d) { - return d.getMinutes(); - } ], [ "%I %p", function(d) { - return d.getHours(); - } ], [ "%a %d", function(d) { - return d.getDay() && d.getDate() != 1; - } ], [ "%b %d", function(d) { - return d.getDate() != 1; - } ], [ "%B", function(d) { - return d.getMonth(); - } ], [ "%Y", d3_true ] ]); - var d3_time_scaleMilliseconds = { - range: function(start, stop, step) { - return d3.range(Math.ceil(start / step) * step, +stop, step).map(d3_time_scaleDate); - }, - floor: d3_identity, - ceil: d3_identity - }; - d3_time_scaleLocalMethods.year = d3_time.year; - d3_time.scale = function() { - return d3_time_scale(d3.scale.linear(), d3_time_scaleLocalMethods, d3_time_scaleLocalFormat); - }; - var d3_time_scaleUtcMethods = d3_time_scaleLocalMethods.map(function(m) { - return [ m[0].utc, m[1] ]; - }); - var d3_time_scaleUtcFormat = d3_time_formatUtc.multi([ [ ".%L", function(d) { - return d.getUTCMilliseconds(); - } ], [ ":%S", function(d) { - return d.getUTCSeconds(); - } ], [ "%I:%M", function(d) { - return d.getUTCMinutes(); - } ], [ "%I %p", function(d) { - return d.getUTCHours(); - } ], [ "%a %d", function(d) { - return d.getUTCDay() && d.getUTCDate() != 1; - } ], [ "%b %d", function(d) { - return d.getUTCDate() != 1; - } ], [ "%B", function(d) { - return d.getUTCMonth(); - } ], [ "%Y", d3_true ] ]); - d3_time_scaleUtcMethods.year = d3_time.year.utc; - d3_time.scale.utc = function() { - return d3_time_scale(d3.scale.linear(), d3_time_scaleUtcMethods, d3_time_scaleUtcFormat); - }; - d3.text = d3_xhrType(function(request) { - return request.responseText; - }); - d3.json = function(url, callback) { - return d3_xhr(url, "application/json", d3_json, callback); - }; - function d3_json(request) { - return JSON.parse(request.responseText); - } - d3.html = function(url, callback) { - return d3_xhr(url, "text/html", d3_html, callback); - }; - function d3_html(request) { - var range = d3_document.createRange(); - range.selectNode(d3_document.body); - return range.createContextualFragment(request.responseText); - } - d3.xml = d3_xhrType(function(request) { - return request.responseXML; - }); - if (typeof define === "function" && define.amd) define(d3); else if (typeof module === "object" && module.exports) module.exports = d3; - this.d3 = d3; -}(); \ No newline at end of file diff --git a/BuildTools/CommonDistFiles/web_plugins/d3/d3.min.js b/BuildTools/CommonDistFiles/web_plugins/d3/d3.min.js deleted file mode 100644 index b4943ee46..000000000 --- a/BuildTools/CommonDistFiles/web_plugins/d3/d3.min.js +++ /dev/null @@ -1,5 +0,0 @@ -!function(){function n(n,t){return t>n?-1:n>t?1:n>=t?0:0/0}function t(n){return null!=n&&!isNaN(n)}function e(n){return{left:function(t,e,r,u){for(arguments.length<3&&(r=0),arguments.length<4&&(u=t.length);u>r;){var i=r+u>>>1;n(t[i],e)<0?r=i+1:u=i}return r},right:function(t,e,r,u){for(arguments.length<3&&(r=0),arguments.length<4&&(u=t.length);u>r;){var i=r+u>>>1;n(t[i],e)>0?u=i:r=i+1}return r}}}function r(n){return n.length}function u(n){for(var t=1;n*t%1;)t*=10;return t}function i(n,t){try{for(var e in t)Object.defineProperty(n.prototype,e,{value:t[e],enumerable:!1})}catch(r){n.prototype=t}}function o(){}function a(n){return oa+n in this}function c(n){return n=oa+n,n in this&&delete this[n]}function l(){var n=[];return this.forEach(function(t){n.push(t)}),n}function s(){var n=0;for(var t in this)t.charCodeAt(0)===aa&&++n;return n}function f(){for(var n in this)if(n.charCodeAt(0)===aa)return!1;return!0}function h(){}function g(n,t,e){return function(){var r=e.apply(t,arguments);return r===t?n:r}}function p(n,t){if(t in n)return t;t=t.charAt(0).toUpperCase()+t.slice(1);for(var e=0,r=ca.length;r>e;++e){var u=ca[e]+t;if(u in n)return u}}function v(){}function d(){}function m(n){function t(){for(var t,r=e,u=-1,i=r.length;++ue;e++)for(var u,i=n[e],o=0,a=i.length;a>o;o++)(u=i[o])&&t(u,o,e);return n}function U(n){return sa(n,ma),n}function j(n){var t,e;return function(r,u,i){var o,a=n[i].update,c=a.length;for(i!=e&&(e=i,t=0),u>=t&&(t=u+1);!(o=a[t])&&++t0&&(n=n.slice(0,a));var l=xa.get(n);return l&&(n=l,c=Y),a?t?u:r:t?v:i}function O(n,t){return function(e){var r=Vo.event;Vo.event=e,t[0]=this.__data__;try{n.apply(this,t)}finally{Vo.event=r}}}function Y(n,t){var e=O(n,t);return function(n){var t=this,r=n.relatedTarget;r&&(r===t||8&r.compareDocumentPosition(t))||e.call(t,n)}}function I(){var n=".dragsuppress-"+ ++_a,t="click"+n,e=Vo.select(Jo).on("touchmove"+n,y).on("dragstart"+n,y).on("selectstart"+n,y);if(Ma){var r=Wo.style,u=r[Ma];r[Ma]="none"}return function(i){function o(){e.on(t,null)}e.on(n,null),Ma&&(r[Ma]=u),i&&(e.on(t,function(){y(),o()},!0),setTimeout(o,0))}}function Z(n,t){t.changedTouches&&(t=t.changedTouches[0]);var e=n.ownerSVGElement||n;if(e.createSVGPoint){var r=e.createSVGPoint();if(0>ba&&(Jo.scrollX||Jo.scrollY)){e=Vo.select("body").append("svg").style({position:"absolute",top:0,left:0,margin:0,padding:0,border:"none"},"important");var u=e[0][0].getScreenCTM();ba=!(u.f||u.e),e.remove()}return ba?(r.x=t.pageX,r.y=t.pageY):(r.x=t.clientX,r.y=t.clientY),r=r.matrixTransform(n.getScreenCTM().inverse()),[r.x,r.y]}var i=n.getBoundingClientRect();return[t.clientX-i.left-n.clientLeft,t.clientY-i.top-n.clientTop]}function V(){return Vo.event.changedTouches[0].identifier}function X(){return Vo.event.target}function $(){return Jo}function B(n){return n>0?1:0>n?-1:0}function W(n,t,e){return(t[0]-n[0])*(e[1]-n[1])-(t[1]-n[1])*(e[0]-n[0])}function J(n){return n>1?0:-1>n?wa:Math.acos(n)}function G(n){return n>1?ka:-1>n?-ka:Math.asin(n)}function K(n){return((n=Math.exp(n))-1/n)/2}function Q(n){return((n=Math.exp(n))+1/n)/2}function nt(n){return((n=Math.exp(2*n))-1)/(n+1)}function tt(n){return(n=Math.sin(n/2))*n}function et(){}function rt(n,t,e){return this instanceof rt?(this.h=+n,this.s=+t,void(this.l=+e)):arguments.length<2?n instanceof rt?new rt(n.h,n.s,n.l):mt(""+n,yt,rt):new rt(n,t,e)}function ut(n,t,e){function r(n){return n>360?n-=360:0>n&&(n+=360),60>n?i+(o-i)*n/60:180>n?o:240>n?i+(o-i)*(240-n)/60:i}function u(n){return Math.round(255*r(n))}var i,o;return n=isNaN(n)?0:(n%=360)<0?n+360:n,t=isNaN(t)?0:0>t?0:t>1?1:t,e=0>e?0:e>1?1:e,o=.5>=e?e*(1+t):e+t-e*t,i=2*e-o,new gt(u(n+120),u(n),u(n-120))}function it(n,t,e){return this instanceof it?(this.h=+n,this.c=+t,void(this.l=+e)):arguments.length<2?n instanceof it?new it(n.h,n.c,n.l):n instanceof at?lt(n.l,n.a,n.b):lt((n=xt((n=Vo.rgb(n)).r,n.g,n.b)).l,n.a,n.b):new it(n,t,e)}function ot(n,t,e){return isNaN(n)&&(n=0),isNaN(t)&&(t=0),new at(e,Math.cos(n*=Ca)*t,Math.sin(n)*t)}function at(n,t,e){return this instanceof at?(this.l=+n,this.a=+t,void(this.b=+e)):arguments.length<2?n instanceof at?new at(n.l,n.a,n.b):n instanceof it?ot(n.l,n.c,n.h):xt((n=gt(n)).r,n.g,n.b):new at(n,t,e)}function ct(n,t,e){var r=(n+16)/116,u=r+t/500,i=r-e/200;return u=st(u)*Ha,r=st(r)*Fa,i=st(i)*Oa,new gt(ht(3.2404542*u-1.5371385*r-.4985314*i),ht(-.969266*u+1.8760108*r+.041556*i),ht(.0556434*u-.2040259*r+1.0572252*i))}function lt(n,t,e){return n>0?new it(Math.atan2(e,t)*Na,Math.sqrt(t*t+e*e),n):new it(0/0,0/0,n)}function st(n){return n>.206893034?n*n*n:(n-4/29)/7.787037}function ft(n){return n>.008856?Math.pow(n,1/3):7.787037*n+4/29}function ht(n){return Math.round(255*(.00304>=n?12.92*n:1.055*Math.pow(n,1/2.4)-.055))}function gt(n,t,e){return this instanceof gt?(this.r=~~n,this.g=~~t,void(this.b=~~e)):arguments.length<2?n instanceof gt?new gt(n.r,n.g,n.b):mt(""+n,gt,ut):new gt(n,t,e)}function pt(n){return new gt(n>>16,255&n>>8,255&n)}function vt(n){return pt(n)+""}function dt(n){return 16>n?"0"+Math.max(0,n).toString(16):Math.min(255,n).toString(16)}function mt(n,t,e){var r,u,i,o=0,a=0,c=0;if(r=/([a-z]+)\((.*)\)/i.exec(n))switch(u=r[2].split(","),r[1]){case"hsl":return e(parseFloat(u[0]),parseFloat(u[1])/100,parseFloat(u[2])/100);case"rgb":return t(_t(u[0]),_t(u[1]),_t(u[2]))}return(i=Za.get(n))?t(i.r,i.g,i.b):(null==n||"#"!==n.charAt(0)||isNaN(i=parseInt(n.slice(1),16))||(4===n.length?(o=(3840&i)>>4,o=o>>4|o,a=240&i,a=a>>4|a,c=15&i,c=c<<4|c):7===n.length&&(o=(16711680&i)>>16,a=(65280&i)>>8,c=255&i)),t(o,a,c))}function yt(n,t,e){var r,u,i=Math.min(n/=255,t/=255,e/=255),o=Math.max(n,t,e),a=o-i,c=(o+i)/2;return a?(u=.5>c?a/(o+i):a/(2-o-i),r=n==o?(t-e)/a+(e>t?6:0):t==o?(e-n)/a+2:(n-t)/a+4,r*=60):(r=0/0,u=c>0&&1>c?0:r),new rt(r,u,c)}function xt(n,t,e){n=Mt(n),t=Mt(t),e=Mt(e);var r=ft((.4124564*n+.3575761*t+.1804375*e)/Ha),u=ft((.2126729*n+.7151522*t+.072175*e)/Fa),i=ft((.0193339*n+.119192*t+.9503041*e)/Oa);return at(116*u-16,500*(r-u),200*(u-i))}function Mt(n){return(n/=255)<=.04045?n/12.92:Math.pow((n+.055)/1.055,2.4)}function _t(n){var t=parseFloat(n);return"%"===n.charAt(n.length-1)?Math.round(2.55*t):t}function bt(n){return"function"==typeof n?n:function(){return n}}function wt(n){return n}function St(n){return function(t,e,r){return 2===arguments.length&&"function"==typeof e&&(r=e,e=null),kt(t,e,n,r)}}function kt(n,t,e,r){function u(){var n,t=c.status;if(!t&&At(c)||t>=200&&300>t||304===t){try{n=e.call(i,c)}catch(r){return o.error.call(i,r),void 0}o.load.call(i,n)}else o.error.call(i,c)}var i={},o=Vo.dispatch("beforesend","progress","load","error"),a={},c=new XMLHttpRequest,l=null;return!Jo.XDomainRequest||"withCredentials"in c||!/^(http(s)?:)?\/\//.test(n)||(c=new XDomainRequest),"onload"in c?c.onload=c.onerror=u:c.onreadystatechange=function(){c.readyState>3&&u()},c.onprogress=function(n){var t=Vo.event;Vo.event=n;try{o.progress.call(i,c)}finally{Vo.event=t}},i.header=function(n,t){return n=(n+"").toLowerCase(),arguments.length<2?a[n]:(null==t?delete a[n]:a[n]=t+"",i)},i.mimeType=function(n){return arguments.length?(t=null==n?null:n+"",i):t},i.responseType=function(n){return arguments.length?(l=n,i):l},i.response=function(n){return e=n,i},["get","post"].forEach(function(n){i[n]=function(){return i.send.apply(i,[n].concat($o(arguments)))}}),i.send=function(e,r,u){if(2===arguments.length&&"function"==typeof r&&(u=r,r=null),c.open(e,n,!0),null==t||"accept"in a||(a.accept=t+",*/*"),c.setRequestHeader)for(var s in a)c.setRequestHeader(s,a[s]);return null!=t&&c.overrideMimeType&&c.overrideMimeType(t),null!=l&&(c.responseType=l),null!=u&&i.on("error",u).on("load",function(n){u(null,n)}),o.beforesend.call(i,c),c.send(null==r?null:r),i},i.abort=function(){return c.abort(),i},Vo.rebind(i,o,"on"),null==r?i:i.get(Et(r))}function Et(n){return 1===n.length?function(t,e){n(null==t?e:null)}:n}function At(n){var t=n.responseType;return t&&"text"!==t?n.response:n.responseText}function Ct(){var n=Nt(),t=zt()-n;t>24?(isFinite(t)&&(clearTimeout(Ba),Ba=setTimeout(Ct,t)),$a=0):($a=1,Ja(Ct))}function Nt(){var n=Date.now();for(Wa=Va;Wa;)n>=Wa.t&&(Wa.f=Wa.c(n-Wa.t)),Wa=Wa.n;return n}function zt(){for(var n,t=Va,e=1/0;t;)t.f?t=n?n.n=t.n:Va=t.n:(t.t8?function(n){return n/e}:function(n){return n*e},symbol:n}}function qt(n){var t=n.decimal,e=n.thousands,r=n.grouping,u=n.currency,i=r?function(n){for(var t=n.length,u=[],i=0,o=r[0];o>0&&t>0;)u.push(n.substring(t-=o,t+o)),o=r[i=(i+1)%r.length];return u.reverse().join(e)}:wt;return function(n){var e=Ka.exec(n),r=e[1]||" ",o=e[2]||">",a=e[3]||"",c=e[4]||"",l=e[5],s=+e[6],f=e[7],h=e[8],g=e[9],p=1,v="",d="",m=!1;switch(h&&(h=+h.substring(1)),(l||"0"===r&&"="===o)&&(l=r="0",o="=",f&&(s-=Math.floor((s-1)/4))),g){case"n":f=!0,g="g";break;case"%":p=100,d="%",g="f";break;case"p":p=100,d="%",g="r";break;case"b":case"o":case"x":case"X":"#"===c&&(v="0"+g.toLowerCase());case"c":case"d":m=!0,h=0;break;case"s":p=-1,g="r"}"$"===c&&(v=u[0],d=u[1]),"r"!=g||h||(g="g"),null!=h&&("g"==g?h=Math.max(1,Math.min(21,h)):("e"==g||"f"==g)&&(h=Math.max(0,Math.min(20,h)))),g=Qa.get(g)||Rt;var y=l&&f;return function(n){var e=d;if(m&&n%1)return"";var u=0>n||0===n&&0>1/n?(n=-n,"-"):a;if(0>p){var c=Vo.formatPrefix(n,h);n=c.scale(n),e=c.symbol+d}else n*=p;n=g(n,h);var x=n.lastIndexOf("."),M=0>x?n:n.substring(0,x),_=0>x?"":t+n.substring(x+1);!l&&f&&(M=i(M));var b=v.length+M.length+_.length+(y?0:u.length),w=s>b?new Array(b=s-b+1).join(r):"";return y&&(M=i(w+M)),u+=v,n=M+_,("<"===o?u+n+w:">"===o?w+u+n:"^"===o?w.substring(0,b>>=1)+u+n+w.substring(b):u+(y?n:w+n))+e}}}function Rt(n){return n+""}function Dt(){this._=new Date(arguments.length>1?Date.UTC.apply(this,arguments):arguments[0])}function Pt(n,t,e){function r(t){var e=n(t),r=i(e,1);return r-t>t-e?e:r}function u(e){return t(e=n(new tc(e-1)),1),e}function i(n,e){return t(n=new tc(+n),e),n}function o(n,r,i){var o=u(n),a=[];if(i>1)for(;r>o;)e(o)%i||a.push(new Date(+o)),t(o,1);else for(;r>o;)a.push(new Date(+o)),t(o,1);return a}function a(n,t,e){try{tc=Dt;var r=new Dt;return r._=n,o(r,t,e)}finally{tc=Date}}n.floor=n,n.round=r,n.ceil=u,n.offset=i,n.range=o;var c=n.utc=Ut(n);return c.floor=c,c.round=Ut(r),c.ceil=Ut(u),c.offset=Ut(i),c.range=a,n}function Ut(n){return function(t,e){try{tc=Dt;var r=new Dt;return r._=t,n(r,e)._}finally{tc=Date}}}function jt(n){function t(n){function t(t){for(var e,u,i,o=[],a=-1,c=0;++aa;){if(r>=l)return-1;if(u=t.charCodeAt(a++),37===u){if(o=t.charAt(a++),i=N[o in rc?t.charAt(a++):o],!i||(r=i(n,e,r))<0)return-1}else if(u!=e.charCodeAt(r++))return-1}return r}function r(n,t,e){b.lastIndex=0;var r=b.exec(t.slice(e));return r?(n.w=w.get(r[0].toLowerCase()),e+r[0].length):-1}function u(n,t,e){M.lastIndex=0;var r=M.exec(t.slice(e));return r?(n.w=_.get(r[0].toLowerCase()),e+r[0].length):-1}function i(n,t,e){E.lastIndex=0;var r=E.exec(t.slice(e));return r?(n.m=A.get(r[0].toLowerCase()),e+r[0].length):-1}function o(n,t,e){S.lastIndex=0;var r=S.exec(t.slice(e));return r?(n.m=k.get(r[0].toLowerCase()),e+r[0].length):-1}function a(n,t,r){return e(n,C.c.toString(),t,r)}function c(n,t,r){return e(n,C.x.toString(),t,r)}function l(n,t,r){return e(n,C.X.toString(),t,r)}function s(n,t,e){var r=x.get(t.slice(e,e+=2).toLowerCase());return null==r?-1:(n.p=r,e)}var f=n.dateTime,h=n.date,g=n.time,p=n.periods,v=n.days,d=n.shortDays,m=n.months,y=n.shortMonths;t.utc=function(n){function e(n){try{tc=Dt;var t=new tc;return t._=n,r(t)}finally{tc=Date}}var r=t(n);return e.parse=function(n){try{tc=Dt;var t=r.parse(n);return t&&t._}finally{tc=Date}},e.toString=r.toString,e},t.multi=t.utc.multi=ue;var x=Vo.map(),M=Ft(v),_=Ot(v),b=Ft(d),w=Ot(d),S=Ft(m),k=Ot(m),E=Ft(y),A=Ot(y);p.forEach(function(n,t){x.set(n.toLowerCase(),t)});var C={a:function(n){return d[n.getDay()]},A:function(n){return v[n.getDay()]},b:function(n){return y[n.getMonth()]},B:function(n){return m[n.getMonth()]},c:t(f),d:function(n,t){return Ht(n.getDate(),t,2)},e:function(n,t){return Ht(n.getDate(),t,2)},H:function(n,t){return Ht(n.getHours(),t,2)},I:function(n,t){return Ht(n.getHours()%12||12,t,2)},j:function(n,t){return Ht(1+nc.dayOfYear(n),t,3)},L:function(n,t){return Ht(n.getMilliseconds(),t,3)},m:function(n,t){return Ht(n.getMonth()+1,t,2)},M:function(n,t){return Ht(n.getMinutes(),t,2)},p:function(n){return p[+(n.getHours()>=12)]},S:function(n,t){return Ht(n.getSeconds(),t,2)},U:function(n,t){return Ht(nc.sundayOfYear(n),t,2)},w:function(n){return n.getDay()},W:function(n,t){return Ht(nc.mondayOfYear(n),t,2)},x:t(h),X:t(g),y:function(n,t){return Ht(n.getFullYear()%100,t,2)},Y:function(n,t){return Ht(n.getFullYear()%1e4,t,4)},Z:ee,"%":function(){return"%"}},N={a:r,A:u,b:i,B:o,c:a,d:Jt,e:Jt,H:Kt,I:Kt,j:Gt,L:te,m:Wt,M:Qt,p:s,S:ne,U:It,w:Yt,W:Zt,x:c,X:l,y:Xt,Y:Vt,Z:$t,"%":re};return t}function Ht(n,t,e){var r=0>n?"-":"",u=(r?-n:n)+"",i=u.length;return r+(e>i?new Array(e-i+1).join(t)+u:u)}function Ft(n){return new RegExp("^(?:"+n.map(Vo.requote).join("|")+")","i")}function Ot(n){for(var t=new o,e=-1,r=n.length;++e68?1900:2e3)}function Wt(n,t,e){uc.lastIndex=0;var r=uc.exec(t.slice(e,e+2));return r?(n.m=r[0]-1,e+r[0].length):-1}function Jt(n,t,e){uc.lastIndex=0;var r=uc.exec(t.slice(e,e+2));return r?(n.d=+r[0],e+r[0].length):-1}function Gt(n,t,e){uc.lastIndex=0;var r=uc.exec(t.slice(e,e+3));return r?(n.j=+r[0],e+r[0].length):-1}function Kt(n,t,e){uc.lastIndex=0;var r=uc.exec(t.slice(e,e+2));return r?(n.H=+r[0],e+r[0].length):-1}function Qt(n,t,e){uc.lastIndex=0;var r=uc.exec(t.slice(e,e+2));return r?(n.M=+r[0],e+r[0].length):-1}function ne(n,t,e){uc.lastIndex=0;var r=uc.exec(t.slice(e,e+2));return r?(n.S=+r[0],e+r[0].length):-1}function te(n,t,e){uc.lastIndex=0;var r=uc.exec(t.slice(e,e+3));return r?(n.L=+r[0],e+r[0].length):-1}function ee(n){var t=n.getTimezoneOffset(),e=t>0?"-":"+",r=0|ia(t)/60,u=ia(t)%60;return e+Ht(r,"0",2)+Ht(u,"0",2)}function re(n,t,e){ic.lastIndex=0;var r=ic.exec(t.slice(e,e+1));return r?e+r[0].length:-1}function ue(n){for(var t=n.length,e=-1;++e=0?1:-1,a=o*e,c=Math.cos(t),l=Math.sin(t),s=i*l,f=u*c+s*Math.cos(a),h=s*o*Math.sin(a);fc.add(Math.atan2(h,f)),r=n,u=c,i=l}var t,e,r,u,i;hc.point=function(o,a){hc.point=n,r=(t=o)*Ca,u=Math.cos(a=(e=a)*Ca/2+wa/4),i=Math.sin(a)},hc.lineEnd=function(){n(t,e)}}function fe(n){var t=n[0],e=n[1],r=Math.cos(e);return[r*Math.cos(t),r*Math.sin(t),Math.sin(e)]}function he(n,t){return n[0]*t[0]+n[1]*t[1]+n[2]*t[2]}function ge(n,t){return[n[1]*t[2]-n[2]*t[1],n[2]*t[0]-n[0]*t[2],n[0]*t[1]-n[1]*t[0]]}function pe(n,t){n[0]+=t[0],n[1]+=t[1],n[2]+=t[2]}function ve(n,t){return[n[0]*t,n[1]*t,n[2]*t]}function de(n){var t=Math.sqrt(n[0]*n[0]+n[1]*n[1]+n[2]*n[2]);n[0]/=t,n[1]/=t,n[2]/=t}function me(n){return[Math.atan2(n[1],n[0]),G(n[2])]}function ye(n,t){return ia(n[0]-t[0])a;++a)u.point((e=n[a])[0],e[1]);return u.lineEnd(),void 0}var c=new Ae(e,n,null,!0),l=new Ae(e,null,c,!1);c.o=l,i.push(c),o.push(l),c=new Ae(r,n,null,!1),l=new Ae(r,null,c,!0),c.o=l,i.push(c),o.push(l)}}),o.sort(t),Ee(i),Ee(o),i.length){for(var a=0,c=e,l=o.length;l>a;++a)o[a].e=c=!c;for(var s,f,h=i[0];;){for(var g=h,p=!0;g.v;)if((g=g.n)===h)return;s=g.z,u.lineStart();do{if(g.v=g.o.v=!0,g.e){if(p)for(var a=0,l=s.length;l>a;++a)u.point((f=s[a])[0],f[1]);else r(g.x,g.n.x,1,u);g=g.n}else{if(p){s=g.p.z;for(var a=s.length-1;a>=0;--a)u.point((f=s[a])[0],f[1])}else r(g.x,g.p.x,-1,u);g=g.p}g=g.o,s=g.z,p=!p}while(!g.v);u.lineEnd()}}}function Ee(n){if(t=n.length){for(var t,e,r=0,u=n[0];++r0){for(_||(i.polygonStart(),_=!0),i.lineStart();++o1&&2&t&&e.push(e.pop().concat(e.shift())),g.push(e.filter(Ne))}var g,p,v,d=t(i),m=u.invert(r[0],r[1]),y={point:o,lineStart:c,lineEnd:l,polygonStart:function(){y.point=s,y.lineStart=f,y.lineEnd=h,g=[],p=[]},polygonEnd:function(){y.point=o,y.lineStart=c,y.lineEnd=l,g=Vo.merge(g);var n=De(m,p);g.length?(_||(i.polygonStart(),_=!0),ke(g,Le,n,e,i)):n&&(_||(i.polygonStart(),_=!0),i.lineStart(),e(null,null,1,i),i.lineEnd()),_&&(i.polygonEnd(),_=!1),g=p=null},sphere:function(){i.polygonStart(),i.lineStart(),e(null,null,1,i),i.lineEnd(),i.polygonEnd()}},x=ze(),M=t(x),_=!1;return y}}function Ne(n){return n.length>1}function ze(){var n,t=[];return{lineStart:function(){t.push(n=[])},point:function(t,e){n.push([t,e])},lineEnd:v,buffer:function(){var e=t;return t=[],n=null,e},rejoin:function(){t.length>1&&t.push(t.pop().concat(t.shift()))}}}function Le(n,t){return((n=n.x)[0]<0?n[1]-ka-Ea:ka-n[1])-((t=t.x)[0]<0?t[1]-ka-Ea:ka-t[1])}function Te(n){var t,e=0/0,r=0/0,u=0/0;return{lineStart:function(){n.lineStart(),t=1},point:function(i,o){var a=i>0?wa:-wa,c=ia(i-e);ia(c-wa)0?ka:-ka),n.point(u,r),n.lineEnd(),n.lineStart(),n.point(a,r),n.point(i,r),t=0):u!==a&&c>=wa&&(ia(e-u)Ea?Math.atan((Math.sin(t)*(i=Math.cos(r))*Math.sin(e)-Math.sin(r)*(u=Math.cos(t))*Math.sin(n))/(u*i*o)):(t+r)/2}function Re(n,t,e,r){var u;if(null==n)u=e*ka,r.point(-wa,u),r.point(0,u),r.point(wa,u),r.point(wa,0),r.point(wa,-u),r.point(0,-u),r.point(-wa,-u),r.point(-wa,0),r.point(-wa,u);else if(ia(n[0]-t[0])>Ea){var i=n[0]a;++a){var l=t[a],s=l.length;if(s)for(var f=l[0],h=f[0],g=f[1]/2+wa/4,p=Math.sin(g),v=Math.cos(g),d=1;;){d===s&&(d=0),n=l[d];var m=n[0],y=n[1]/2+wa/4,x=Math.sin(y),M=Math.cos(y),_=m-h,b=_>=0?1:-1,w=b*_,S=w>wa,k=p*x;if(fc.add(Math.atan2(k*b*Math.sin(w),v*M+k*Math.cos(w))),i+=S?_+b*Sa:_,S^h>=e^m>=e){var E=ge(fe(f),fe(n));de(E);var A=ge(u,E);de(A);var C=(S^_>=0?-1:1)*G(A[2]);(r>C||r===C&&(E[0]||E[1]))&&(o+=S^_>=0?1:-1)}if(!d++)break;h=m,p=x,v=M,f=n}}return(-Ea>i||Ea>i&&0>fc)^1&o}function Pe(n){function t(n,t){return Math.cos(n)*Math.cos(t)>i}function e(n){var e,i,c,l,s;return{lineStart:function(){l=c=!1,s=1},point:function(f,h){var g,p=[f,h],v=t(f,h),d=o?v?0:u(f,h):v?u(f+(0>f?wa:-wa),h):0;if(!e&&(l=c=v)&&n.lineStart(),v!==c&&(g=r(e,p),(ye(e,g)||ye(p,g))&&(p[0]+=Ea,p[1]+=Ea,v=t(p[0],p[1]))),v!==c)s=0,v?(n.lineStart(),g=r(p,e),n.point(g[0],g[1])):(g=r(e,p),n.point(g[0],g[1]),n.lineEnd()),e=g;else if(a&&e&&o^v){var m;d&i||!(m=r(p,e,!0))||(s=0,o?(n.lineStart(),n.point(m[0][0],m[0][1]),n.point(m[1][0],m[1][1]),n.lineEnd()):(n.point(m[1][0],m[1][1]),n.lineEnd(),n.lineStart(),n.point(m[0][0],m[0][1])))}!v||e&&ye(e,p)||n.point(p[0],p[1]),e=p,c=v,i=d},lineEnd:function(){c&&n.lineEnd(),e=null},clean:function(){return s|(l&&c)<<1}}}function r(n,t,e){var r=fe(n),u=fe(t),o=[1,0,0],a=ge(r,u),c=he(a,a),l=a[0],s=c-l*l;if(!s)return!e&&n;var f=i*c/s,h=-i*l/s,g=ge(o,a),p=ve(o,f),v=ve(a,h);pe(p,v);var d=g,m=he(p,d),y=he(d,d),x=m*m-y*(he(p,p)-1);if(!(0>x)){var M=Math.sqrt(x),_=ve(d,(-m-M)/y);if(pe(_,p),_=me(_),!e)return _;var b,w=n[0],S=t[0],k=n[1],E=t[1];w>S&&(b=w,w=S,S=b);var A=S-w,C=ia(A-wa)A;if(!C&&k>E&&(b=k,k=E,E=b),N?C?k+E>0^_[1]<(ia(_[0]-w)wa^(w<=_[0]&&_[0]<=S)){var z=ve(d,(-m+M)/y);return pe(z,p),[_,me(z)]}}}function u(t,e){var r=o?n:wa-n,u=0;return-r>t?u|=1:t>r&&(u|=2),-r>e?u|=4:e>r&&(u|=8),u}var i=Math.cos(n),o=i>0,a=ia(i)>Ea,c=sr(n,6*Ca);return Ce(t,e,c,o?[0,-n]:[-wa,n-wa])}function Ue(n,t,e,r){return function(u){var i,o=u.a,a=u.b,c=o.x,l=o.y,s=a.x,f=a.y,h=0,g=1,p=s-c,v=f-l;if(i=n-c,p||!(i>0)){if(i/=p,0>p){if(h>i)return;g>i&&(g=i)}else if(p>0){if(i>g)return;i>h&&(h=i)}if(i=e-c,p||!(0>i)){if(i/=p,0>p){if(i>g)return;i>h&&(h=i)}else if(p>0){if(h>i)return;g>i&&(g=i)}if(i=t-l,v||!(i>0)){if(i/=v,0>v){if(h>i)return;g>i&&(g=i)}else if(v>0){if(i>g)return;i>h&&(h=i)}if(i=r-l,v||!(0>i)){if(i/=v,0>v){if(i>g)return;i>h&&(h=i)}else if(v>0){if(h>i)return;g>i&&(g=i)}return h>0&&(u.a={x:c+h*p,y:l+h*v}),1>g&&(u.b={x:c+g*p,y:l+g*v}),u}}}}}}function je(n,t,e,r){function u(r,u){return ia(r[0]-n)0?0:3:ia(r[0]-e)0?2:1:ia(r[1]-t)0?1:0:u>0?3:2}function i(n,t){return o(n.x,t.x)}function o(n,t){var e=u(n,1),r=u(t,1);return e!==r?e-r:0===e?t[1]-n[1]:1===e?n[0]-t[0]:2===e?n[1]-t[1]:t[0]-n[0]}return function(a){function c(n){for(var t=0,e=d.length,r=n[1],u=0;e>u;++u)for(var i,o=1,a=d[u],c=a.length,l=a[0];c>o;++o)i=a[o],l[1]<=r?i[1]>r&&W(l,i,n)>0&&++t:i[1]<=r&&W(l,i,n)<0&&--t,l=i;return 0!==t}function l(i,a,c,l){var s=0,f=0;if(null==i||(s=u(i,c))!==(f=u(a,c))||o(i,a)<0^c>0){do l.point(0===s||3===s?n:e,s>1?r:t);while((s=(s+c+4)%4)!==f)}else l.point(a[0],a[1])}function s(u,i){return u>=n&&e>=u&&i>=t&&r>=i}function f(n,t){s(n,t)&&a.point(n,t)}function h(){N.point=p,d&&d.push(m=[]),S=!0,w=!1,_=b=0/0}function g(){v&&(p(y,x),M&&w&&A.rejoin(),v.push(A.buffer())),N.point=f,w&&a.lineEnd()}function p(n,t){n=Math.max(-Ec,Math.min(Ec,n)),t=Math.max(-Ec,Math.min(Ec,t));var e=s(n,t);if(d&&m.push([n,t]),S)y=n,x=t,M=e,S=!1,e&&(a.lineStart(),a.point(n,t));else if(e&&w)a.point(n,t);else{var r={a:{x:_,y:b},b:{x:n,y:t}};C(r)?(w||(a.lineStart(),a.point(r.a.x,r.a.y)),a.point(r.b.x,r.b.y),e||a.lineEnd(),k=!1):e&&(a.lineStart(),a.point(n,t),k=!1)}_=n,b=t,w=e}var v,d,m,y,x,M,_,b,w,S,k,E=a,A=ze(),C=Ue(n,t,e,r),N={point:f,lineStart:h,lineEnd:g,polygonStart:function(){a=A,v=[],d=[],k=!0},polygonEnd:function(){a=E,v=Vo.merge(v);var t=c([n,r]),e=k&&t,u=v.length;(e||u)&&(a.polygonStart(),e&&(a.lineStart(),l(null,null,1,a),a.lineEnd()),u&&ke(v,i,t,l,a),a.polygonEnd()),v=d=m=null}};return N}}function He(n,t){function e(e,r){return e=n(e,r),t(e[0],e[1])}return n.invert&&t.invert&&(e.invert=function(e,r){return e=t.invert(e,r),e&&n.invert(e[0],e[1])}),e}function Fe(n){var t=0,e=wa/3,r=er(n),u=r(t,e);return u.parallels=function(n){return arguments.length?r(t=n[0]*wa/180,e=n[1]*wa/180):[180*(t/wa),180*(e/wa)]},u}function Oe(n,t){function e(n,t){var e=Math.sqrt(i-2*u*Math.sin(t))/u;return[e*Math.sin(n*=u),o-e*Math.cos(n)]}var r=Math.sin(n),u=(r+Math.sin(t))/2,i=1+r*(2*u-r),o=Math.sqrt(i)/u;return e.invert=function(n,t){var e=o-t;return[Math.atan2(n,e)/u,G((i-(n*n+e*e)*u*u)/(2*u))]},e}function Ye(){function n(n,t){Cc+=u*n-r*t,r=n,u=t}var t,e,r,u;qc.point=function(i,o){qc.point=n,t=r=i,e=u=o},qc.lineEnd=function(){n(t,e)}}function Ie(n,t){Nc>n&&(Nc=n),n>Lc&&(Lc=n),zc>t&&(zc=t),t>Tc&&(Tc=t)}function Ze(){function n(n,t){o.push("M",n,",",t,i)}function t(n,t){o.push("M",n,",",t),a.point=e}function e(n,t){o.push("L",n,",",t)}function r(){a.point=n}function u(){o.push("Z")}var i=Ve(4.5),o=[],a={point:n,lineStart:function(){a.point=t},lineEnd:r,polygonStart:function(){a.lineEnd=u},polygonEnd:function(){a.lineEnd=r,a.point=n},pointRadius:function(n){return i=Ve(n),a},result:function(){if(o.length){var n=o.join("");return o=[],n}}};return a}function Ve(n){return"m0,"+n+"a"+n+","+n+" 0 1,1 0,"+-2*n+"a"+n+","+n+" 0 1,1 0,"+2*n+"z"}function Xe(n,t){vc+=n,dc+=t,++mc}function $e(){function n(n,r){var u=n-t,i=r-e,o=Math.sqrt(u*u+i*i);yc+=o*(t+n)/2,xc+=o*(e+r)/2,Mc+=o,Xe(t=n,e=r)}var t,e;Dc.point=function(r,u){Dc.point=n,Xe(t=r,e=u)}}function Be(){Dc.point=Xe}function We(){function n(n,t){var e=n-r,i=t-u,o=Math.sqrt(e*e+i*i);yc+=o*(r+n)/2,xc+=o*(u+t)/2,Mc+=o,o=u*n-r*t,_c+=o*(r+n),bc+=o*(u+t),wc+=3*o,Xe(r=n,u=t)}var t,e,r,u;Dc.point=function(i,o){Dc.point=n,Xe(t=r=i,e=u=o)},Dc.lineEnd=function(){n(t,e)}}function Je(n){function t(t,e){n.moveTo(t,e),n.arc(t,e,o,0,Sa)}function e(t,e){n.moveTo(t,e),a.point=r}function r(t,e){n.lineTo(t,e)}function u(){a.point=t}function i(){n.closePath()}var o=4.5,a={point:t,lineStart:function(){a.point=e},lineEnd:u,polygonStart:function(){a.lineEnd=i},polygonEnd:function(){a.lineEnd=u,a.point=t},pointRadius:function(n){return o=n,a},result:v};return a}function Ge(n){function t(n){return(a?r:e)(n)}function e(t){return nr(t,function(e,r){e=n(e,r),t.point(e[0],e[1])})}function r(t){function e(e,r){e=n(e,r),t.point(e[0],e[1])}function r(){x=0/0,S.point=i,t.lineStart()}function i(e,r){var i=fe([e,r]),o=n(e,r);u(x,M,y,_,b,w,x=o[0],M=o[1],y=e,_=i[0],b=i[1],w=i[2],a,t),t.point(x,M)}function o(){S.point=e,t.lineEnd()}function c(){r(),S.point=l,S.lineEnd=s}function l(n,t){i(f=n,h=t),g=x,p=M,v=_,d=b,m=w,S.point=i}function s(){u(x,M,y,_,b,w,g,p,f,v,d,m,a,t),S.lineEnd=o,o()}var f,h,g,p,v,d,m,y,x,M,_,b,w,S={point:e,lineStart:r,lineEnd:o,polygonStart:function(){t.polygonStart(),S.lineStart=c},polygonEnd:function(){t.polygonEnd(),S.lineStart=r}};return S}function u(t,e,r,a,c,l,s,f,h,g,p,v,d,m){var y=s-t,x=f-e,M=y*y+x*x;if(M>4*i&&d--){var _=a+g,b=c+p,w=l+v,S=Math.sqrt(_*_+b*b+w*w),k=Math.asin(w/=S),E=ia(ia(w)-1)i||ia((y*z+x*L)/M-.5)>.3||o>a*g+c*p+l*v)&&(u(t,e,r,a,c,l,C,N,E,_/=S,b/=S,w,d,m),m.point(C,N),u(C,N,E,_,b,w,s,f,h,g,p,v,d,m))}}var i=.5,o=Math.cos(30*Ca),a=16;return t.precision=function(n){return arguments.length?(a=(i=n*n)>0&&16,t):Math.sqrt(i) -},t}function Ke(n){var t=Ge(function(t,e){return n([t*Na,e*Na])});return function(n){return rr(t(n))}}function Qe(n){this.stream=n}function nr(n,t){return{point:t,sphere:function(){n.sphere()},lineStart:function(){n.lineStart()},lineEnd:function(){n.lineEnd()},polygonStart:function(){n.polygonStart()},polygonEnd:function(){n.polygonEnd()}}}function tr(n){return er(function(){return n})()}function er(n){function t(n){return n=a(n[0]*Ca,n[1]*Ca),[n[0]*h+c,l-n[1]*h]}function e(n){return n=a.invert((n[0]-c)/h,(l-n[1])/h),n&&[n[0]*Na,n[1]*Na]}function r(){a=He(o=or(m,y,x),i);var n=i(v,d);return c=g-n[0]*h,l=p+n[1]*h,u()}function u(){return s&&(s.valid=!1,s=null),t}var i,o,a,c,l,s,f=Ge(function(n,t){return n=i(n,t),[n[0]*h+c,l-n[1]*h]}),h=150,g=480,p=250,v=0,d=0,m=0,y=0,x=0,M=kc,_=wt,b=null,w=null;return t.stream=function(n){return s&&(s.valid=!1),s=rr(M(o,f(_(n)))),s.valid=!0,s},t.clipAngle=function(n){return arguments.length?(M=null==n?(b=n,kc):Pe((b=+n)*Ca),u()):b},t.clipExtent=function(n){return arguments.length?(w=n,_=n?je(n[0][0],n[0][1],n[1][0],n[1][1]):wt,u()):w},t.scale=function(n){return arguments.length?(h=+n,r()):h},t.translate=function(n){return arguments.length?(g=+n[0],p=+n[1],r()):[g,p]},t.center=function(n){return arguments.length?(v=n[0]%360*Ca,d=n[1]%360*Ca,r()):[v*Na,d*Na]},t.rotate=function(n){return arguments.length?(m=n[0]%360*Ca,y=n[1]%360*Ca,x=n.length>2?n[2]%360*Ca:0,r()):[m*Na,y*Na,x*Na]},Vo.rebind(t,f,"precision"),function(){return i=n.apply(this,arguments),t.invert=i.invert&&e,r()}}function rr(n){return nr(n,function(t,e){n.point(t*Ca,e*Ca)})}function ur(n,t){return[n,t]}function ir(n,t){return[n>wa?n-Sa:-wa>n?n+Sa:n,t]}function or(n,t,e){return n?t||e?He(cr(n),lr(t,e)):cr(n):t||e?lr(t,e):ir}function ar(n){return function(t,e){return t+=n,[t>wa?t-Sa:-wa>t?t+Sa:t,e]}}function cr(n){var t=ar(n);return t.invert=ar(-n),t}function lr(n,t){function e(n,t){var e=Math.cos(t),a=Math.cos(n)*e,c=Math.sin(n)*e,l=Math.sin(t),s=l*r+a*u;return[Math.atan2(c*i-s*o,a*r-l*u),G(s*i+c*o)]}var r=Math.cos(n),u=Math.sin(n),i=Math.cos(t),o=Math.sin(t);return e.invert=function(n,t){var e=Math.cos(t),a=Math.cos(n)*e,c=Math.sin(n)*e,l=Math.sin(t),s=l*i-c*o;return[Math.atan2(c*i+l*o,a*r+s*u),G(s*r-a*u)]},e}function sr(n,t){var e=Math.cos(n),r=Math.sin(n);return function(u,i,o,a){var c=o*t;null!=u?(u=fr(e,u),i=fr(e,i),(o>0?i>u:u>i)&&(u+=o*Sa)):(u=n+o*Sa,i=n-.5*c);for(var l,s=u;o>0?s>i:i>s;s-=c)a.point((l=me([e,-r*Math.cos(s),-r*Math.sin(s)]))[0],l[1])}}function fr(n,t){var e=fe(t);e[0]-=n,de(e);var r=J(-e[1]);return((-e[2]<0?-r:r)+2*Math.PI-Ea)%(2*Math.PI)}function hr(n,t,e){var r=Vo.range(n,t-Ea,e).concat(t);return function(n){return r.map(function(t){return[n,t]})}}function gr(n,t,e){var r=Vo.range(n,t-Ea,e).concat(t);return function(n){return r.map(function(t){return[t,n]})}}function pr(n){return n.source}function vr(n){return n.target}function dr(n,t,e,r){var u=Math.cos(t),i=Math.sin(t),o=Math.cos(r),a=Math.sin(r),c=u*Math.cos(n),l=u*Math.sin(n),s=o*Math.cos(e),f=o*Math.sin(e),h=2*Math.asin(Math.sqrt(tt(r-t)+u*o*tt(e-n))),g=1/Math.sin(h),p=h?function(n){var t=Math.sin(n*=h)*g,e=Math.sin(h-n)*g,r=e*c+t*s,u=e*l+t*f,o=e*i+t*a;return[Math.atan2(u,r)*Na,Math.atan2(o,Math.sqrt(r*r+u*u))*Na]}:function(){return[n*Na,t*Na]};return p.distance=h,p}function mr(){function n(n,u){var i=Math.sin(u*=Ca),o=Math.cos(u),a=ia((n*=Ca)-t),c=Math.cos(a);Pc+=Math.atan2(Math.sqrt((a=o*Math.sin(a))*a+(a=r*i-e*o*c)*a),e*i+r*o*c),t=n,e=i,r=o}var t,e,r;Uc.point=function(u,i){t=u*Ca,e=Math.sin(i*=Ca),r=Math.cos(i),Uc.point=n},Uc.lineEnd=function(){Uc.point=Uc.lineEnd=v}}function yr(n,t){function e(t,e){var r=Math.cos(t),u=Math.cos(e),i=n(r*u);return[i*u*Math.sin(t),i*Math.sin(e)]}return e.invert=function(n,e){var r=Math.sqrt(n*n+e*e),u=t(r),i=Math.sin(u),o=Math.cos(u);return[Math.atan2(n*i,r*o),Math.asin(r&&e*i/r)]},e}function xr(n,t){function e(n,t){o>0?-ka+Ea>t&&(t=-ka+Ea):t>ka-Ea&&(t=ka-Ea);var e=o/Math.pow(u(t),i);return[e*Math.sin(i*n),o-e*Math.cos(i*n)]}var r=Math.cos(n),u=function(n){return Math.tan(wa/4+n/2)},i=n===t?Math.sin(n):Math.log(r/Math.cos(t))/Math.log(u(t)/u(n)),o=r*Math.pow(u(n),i)/i;return i?(e.invert=function(n,t){var e=o-t,r=B(i)*Math.sqrt(n*n+e*e);return[Math.atan2(n,e)/i,2*Math.atan(Math.pow(o/r,1/i))-ka]},e):_r}function Mr(n,t){function e(n,t){var e=i-t;return[e*Math.sin(u*n),i-e*Math.cos(u*n)]}var r=Math.cos(n),u=n===t?Math.sin(n):(r-Math.cos(t))/(t-n),i=r/u+n;return ia(u)u;u++){for(;r>1&&W(n[e[r-2]],n[e[r-1]],n[u])<=0;)--r;e[r++]=u}return e.slice(0,r)}function Ar(n,t){return n[0]-t[0]||n[1]-t[1]}function Cr(n,t,e){return(e[0]-t[0])*(n[1]-t[1])<(e[1]-t[1])*(n[0]-t[0])}function Nr(n,t,e,r){var u=n[0],i=e[0],o=t[0]-u,a=r[0]-i,c=n[1],l=e[1],s=t[1]-c,f=r[1]-l,h=(a*(c-l)-f*(u-i))/(f*o-a*s);return[u+h*o,c+h*s]}function zr(n){var t=n[0],e=n[n.length-1];return!(t[0]-e[0]||t[1]-e[1])}function Lr(){Kr(this),this.edge=this.site=this.circle=null}function Tr(n){var t=Wc.pop()||new Lr;return t.site=n,t}function qr(n){Ir(n),Xc.remove(n),Wc.push(n),Kr(n)}function Rr(n){var t=n.circle,e=t.x,r=t.cy,u={x:e,y:r},i=n.P,o=n.N,a=[n];qr(n);for(var c=i;c.circle&&ia(e-c.circle.x)s;++s)l=a[s],c=a[s-1],Wr(l.edge,c.site,l.site,u);c=a[0],l=a[f-1],l.edge=$r(c.site,l.site,null,u),Yr(c),Yr(l)}function Dr(n){for(var t,e,r,u,i=n.x,o=n.y,a=Xc._;a;)if(r=Pr(a,o)-i,r>Ea)a=a.L;else{if(u=i-Ur(a,o),!(u>Ea)){r>-Ea?(t=a.P,e=a):u>-Ea?(t=a,e=a.N):t=e=a;break}if(!a.R){t=a;break}a=a.R}var c=Tr(n);if(Xc.insert(t,c),t||e){if(t===e)return Ir(t),e=Tr(t.site),Xc.insert(c,e),c.edge=e.edge=$r(t.site,c.site),Yr(t),Yr(e),void 0;if(!e)return c.edge=$r(t.site,c.site),void 0;Ir(t),Ir(e);var l=t.site,s=l.x,f=l.y,h=n.x-s,g=n.y-f,p=e.site,v=p.x-s,d=p.y-f,m=2*(h*d-g*v),y=h*h+g*g,x=v*v+d*d,M={x:(d*y-g*x)/m+s,y:(h*x-v*y)/m+f};Wr(e.edge,l,p,M),c.edge=$r(l,n,null,M),e.edge=$r(n,p,null,M),Yr(t),Yr(e)}}function Pr(n,t){var e=n.site,r=e.x,u=e.y,i=u-t;if(!i)return r;var o=n.P;if(!o)return-1/0;e=o.site;var a=e.x,c=e.y,l=c-t;if(!l)return a;var s=a-r,f=1/i-1/l,h=s/l;return f?(-h+Math.sqrt(h*h-2*f*(s*s/(-2*l)-c+l/2+u-i/2)))/f+r:(r+a)/2}function Ur(n,t){var e=n.N;if(e)return Pr(e,t);var r=n.site;return r.y===t?r.x:1/0}function jr(n){this.site=n,this.edges=[]}function Hr(n){for(var t,e,r,u,i,o,a,c,l,s,f=n[0][0],h=n[1][0],g=n[0][1],p=n[1][1],v=Vc,d=v.length;d--;)if(i=v[d],i&&i.prepare())for(a=i.edges,c=a.length,o=0;c>o;)s=a[o].end(),r=s.x,u=s.y,l=a[++o%c].start(),t=l.x,e=l.y,(ia(r-t)>Ea||ia(u-e)>Ea)&&(a.splice(o,0,new Jr(Br(i.site,s,ia(r-f)Ea?{x:f,y:ia(t-f)Ea?{x:ia(e-p)Ea?{x:h,y:ia(t-h)Ea?{x:ia(e-g)=-Aa)){var g=c*c+l*l,p=s*s+f*f,v=(f*g-l*p)/h,d=(c*p-s*g)/h,f=d+a,m=Jc.pop()||new Or;m.arc=n,m.site=u,m.x=v+o,m.y=f+Math.sqrt(v*v+d*d),m.cy=f,n.circle=m;for(var y=null,x=Bc._;x;)if(m.yd||d>=a)return;if(h>p){if(i){if(i.y>=l)return}else i={x:d,y:c};e={x:d,y:l}}else{if(i){if(i.yr||r>1)if(h>p){if(i){if(i.y>=l)return}else i={x:(c-u)/r,y:c};e={x:(l-u)/r,y:l}}else{if(i){if(i.yg){if(i){if(i.x>=a)return}else i={x:o,y:r*o+u};e={x:a,y:r*a+u}}else{if(i){if(i.xi&&(u=t.slice(i,u),a[o]?a[o]+=u:a[++o]=u),(e=e[0])===(r=r[0])?a[o]?a[o]+=r:a[++o]=r:(a[++o]=null,c.push({i:o,x:fu(e,r)})),i=Qc.lastIndex;return ir;++r)a[(e=c[r]).i]=e.x(n);return a.join("")})}function gu(n,t){for(var e,r=Vo.interpolators.length;--r>=0&&!(e=Vo.interpolators[r](n,t)););return e}function pu(n,t){var e,r=[],u=[],i=n.length,o=t.length,a=Math.min(n.length,t.length);for(e=0;a>e;++e)r.push(gu(n[e],t[e]));for(;i>e;++e)u[e]=n[e];for(;o>e;++e)u[e]=t[e];return function(n){for(e=0;a>e;++e)u[e]=r[e](n);return u}}function vu(n){return function(t){return 0>=t?0:t>=1?1:n(t)}}function du(n){return function(t){return 1-n(1-t)}}function mu(n){return function(t){return.5*(.5>t?n(2*t):2-n(2-2*t))}}function yu(n){return n*n}function xu(n){return n*n*n}function Mu(n){if(0>=n)return 0;if(n>=1)return 1;var t=n*n,e=t*n;return 4*(.5>n?e:3*(n-t)+e-.75)}function _u(n){return function(t){return Math.pow(t,n)}}function bu(n){return 1-Math.cos(n*ka)}function wu(n){return Math.pow(2,10*(n-1))}function Su(n){return 1-Math.sqrt(1-n*n)}function ku(n,t){var e;return arguments.length<2&&(t=.45),arguments.length?e=t/Sa*Math.asin(1/n):(n=1,e=t/4),function(r){return 1+n*Math.pow(2,-10*r)*Math.sin((r-e)*Sa/t)}}function Eu(n){return n||(n=1.70158),function(t){return t*t*((n+1)*t-n)}}function Au(n){return 1/2.75>n?7.5625*n*n:2/2.75>n?7.5625*(n-=1.5/2.75)*n+.75:2.5/2.75>n?7.5625*(n-=2.25/2.75)*n+.9375:7.5625*(n-=2.625/2.75)*n+.984375}function Cu(n,t){n=Vo.hcl(n),t=Vo.hcl(t);var e=n.h,r=n.c,u=n.l,i=t.h-e,o=t.c-r,a=t.l-u;return isNaN(o)&&(o=0,r=isNaN(r)?t.c:r),isNaN(i)?(i=0,e=isNaN(e)?t.h:e):i>180?i-=360:-180>i&&(i+=360),function(n){return ot(e+i*n,r+o*n,u+a*n)+""}}function Nu(n,t){n=Vo.hsl(n),t=Vo.hsl(t);var e=n.h,r=n.s,u=n.l,i=t.h-e,o=t.s-r,a=t.l-u;return isNaN(o)&&(o=0,r=isNaN(r)?t.s:r),isNaN(i)?(i=0,e=isNaN(e)?t.h:e):i>180?i-=360:-180>i&&(i+=360),function(n){return ut(e+i*n,r+o*n,u+a*n)+""}}function zu(n,t){n=Vo.lab(n),t=Vo.lab(t);var e=n.l,r=n.a,u=n.b,i=t.l-e,o=t.a-r,a=t.b-u;return function(n){return ct(e+i*n,r+o*n,u+a*n)+""}}function Lu(n,t){return t-=n,function(e){return Math.round(n+t*e)}}function Tu(n){var t=[n.a,n.b],e=[n.c,n.d],r=Ru(t),u=qu(t,e),i=Ru(Du(e,t,-u))||0;t[0]*e[1]180?s+=360:s-l>180&&(l+=360),u.push({i:r.push(r.pop()+"rotate(",null,")")-2,x:fu(l,s)})):s&&r.push(r.pop()+"rotate("+s+")"),f!=h?u.push({i:r.push(r.pop()+"skewX(",null,")")-2,x:fu(f,h)}):h&&r.push(r.pop()+"skewX("+h+")"),g[0]!=p[0]||g[1]!=p[1]?(e=r.push(r.pop()+"scale(",null,",",null,")"),u.push({i:e-4,x:fu(g[0],p[0])},{i:e-2,x:fu(g[1],p[1])})):(1!=p[0]||1!=p[1])&&r.push(r.pop()+"scale("+p+")"),e=u.length,function(n){for(var t,i=-1;++i=0;)e.push(u[r])}function Wu(n,t){for(var e=[n],r=[];null!=(n=e.pop());)if(r.push(n),(i=n.children)&&(u=i.length))for(var u,i,o=-1;++oe;++e)(t=n[e][1])>u&&(r=e,u=t);return r}function oi(n){return n.reduce(ai,0)}function ai(n,t){return n+t[1]}function ci(n,t){return li(n,Math.ceil(Math.log(t.length)/Math.LN2+1))}function li(n,t){for(var e=-1,r=+n[0],u=(n[1]-r)/t,i=[];++e<=t;)i[e]=u*e+r;return i}function si(n){return[Vo.min(n),Vo.max(n)]}function fi(n,t){return n.value-t.value}function hi(n,t){var e=n._pack_next;n._pack_next=t,t._pack_prev=n,t._pack_next=e,e._pack_prev=t}function gi(n,t){n._pack_next=t,t._pack_prev=n}function pi(n,t){var e=t.x-n.x,r=t.y-n.y,u=n.r+t.r;return.999*u*u>e*e+r*r}function vi(n){function t(n){s=Math.min(n.x-n.r,s),f=Math.max(n.x+n.r,f),h=Math.min(n.y-n.r,h),g=Math.max(n.y+n.r,g)}if((e=n.children)&&(l=e.length)){var e,r,u,i,o,a,c,l,s=1/0,f=-1/0,h=1/0,g=-1/0;if(e.forEach(di),r=e[0],r.x=-r.r,r.y=0,t(r),l>1&&(u=e[1],u.x=u.r,u.y=0,t(u),l>2))for(i=e[2],xi(r,u,i),t(i),hi(r,i),r._pack_prev=i,hi(i,u),u=r._pack_next,o=3;l>o;o++){xi(r,u,i=e[o]);var p=0,v=1,d=1;for(a=u._pack_next;a!==u;a=a._pack_next,v++)if(pi(a,i)){p=1;break}if(1==p)for(c=r._pack_prev;c!==a._pack_prev&&!pi(c,i);c=c._pack_prev,d++);p?(d>v||v==d&&u.ro;o++)i=e[o],i.x-=m,i.y-=y,x=Math.max(x,i.r+Math.sqrt(i.x*i.x+i.y*i.y));n.r=x,e.forEach(mi)}}function di(n){n._pack_next=n._pack_prev=n}function mi(n){delete n._pack_next,delete n._pack_prev}function yi(n,t,e,r){var u=n.children;if(n.x=t+=r*n.x,n.y=e+=r*n.y,n.r*=r,u)for(var i=-1,o=u.length;++i=0;)t=u[i],t.z+=e,t.m+=e,e+=t.s+(r+=t.c)}function ki(n,t,e){return n.a.parent===t.parent?n.a:e}function Ei(n){return 1+Vo.max(n,function(n){return n.y})}function Ai(n){return n.reduce(function(n,t){return n+t.x},0)/n.length}function Ci(n){var t=n.children;return t&&t.length?Ci(t[0]):n}function Ni(n){var t,e=n.children;return e&&(t=e.length)?Ni(e[t-1]):n}function zi(n){return{x:n.x,y:n.y,dx:n.dx,dy:n.dy}}function Li(n,t){var e=n.x+t[3],r=n.y+t[0],u=n.dx-t[1]-t[3],i=n.dy-t[0]-t[2];return 0>u&&(e+=u/2,u=0),0>i&&(r+=i/2,i=0),{x:e,y:r,dx:u,dy:i}}function Ti(n){var t=n[0],e=n[n.length-1];return e>t?[t,e]:[e,t]}function qi(n){return n.rangeExtent?n.rangeExtent():Ti(n.range())}function Ri(n,t,e,r){var u=e(n[0],n[1]),i=r(t[0],t[1]);return function(n){return i(u(n))}}function Di(n,t){var e,r=0,u=n.length-1,i=n[r],o=n[u];return i>o&&(e=r,r=u,u=e,e=i,i=o,o=e),n[r]=t.floor(i),n[u]=t.ceil(o),n}function Pi(n){return n?{floor:function(t){return Math.floor(t/n)*n},ceil:function(t){return Math.ceil(t/n)*n}}:sl}function Ui(n,t,e,r){var u=[],i=[],o=0,a=Math.min(n.length,t.length)-1;for(n[a]2?Ui:Ri,c=r?ju:Uu;return o=u(n,t,c,e),a=u(t,n,c,gu),i}function i(n){return o(n)}var o,a;return i.invert=function(n){return a(n)},i.domain=function(t){return arguments.length?(n=t.map(Number),u()):n},i.range=function(n){return arguments.length?(t=n,u()):t},i.rangeRound=function(n){return i.range(n).interpolate(Lu)},i.clamp=function(n){return arguments.length?(r=n,u()):r},i.interpolate=function(n){return arguments.length?(e=n,u()):e},i.ticks=function(t){return Yi(n,t)},i.tickFormat=function(t,e){return Ii(n,t,e)},i.nice=function(t){return Fi(n,t),u()},i.copy=function(){return ji(n,t,e,r)},u()}function Hi(n,t){return Vo.rebind(n,t,"range","rangeRound","interpolate","clamp")}function Fi(n,t){return Di(n,Pi(Oi(n,t)[2]))}function Oi(n,t){null==t&&(t=10);var e=Ti(n),r=e[1]-e[0],u=Math.pow(10,Math.floor(Math.log(r/t)/Math.LN10)),i=t/r*u;return.15>=i?u*=10:.35>=i?u*=5:.75>=i&&(u*=2),e[0]=Math.ceil(e[0]/u)*u,e[1]=Math.floor(e[1]/u)*u+.5*u,e[2]=u,e}function Yi(n,t){return Vo.range.apply(Vo,Oi(n,t))}function Ii(n,t,e){var r=Oi(n,t);if(e){var u=Ka.exec(e);if(u.shift(),"s"===u[8]){var i=Vo.formatPrefix(Math.max(ia(r[0]),ia(r[1])));return u[7]||(u[7]="."+Zi(i.scale(r[2]))),u[8]="f",e=Vo.format(u.join("")),function(n){return e(i.scale(n))+i.symbol}}u[7]||(u[7]="."+Vi(u[8],r)),e=u.join("")}else e=",."+Zi(r[2])+"f";return Vo.format(e)}function Zi(n){return-Math.floor(Math.log(n)/Math.LN10+.01)}function Vi(n,t){var e=Zi(t[2]);return n in fl?Math.abs(e-Zi(Math.max(ia(t[0]),ia(t[1]))))+ +("e"!==n):e-2*("%"===n)}function Xi(n,t,e,r){function u(n){return(e?Math.log(0>n?0:n):-Math.log(n>0?0:-n))/Math.log(t)}function i(n){return e?Math.pow(t,n):-Math.pow(t,-n)}function o(t){return n(u(t))}return o.invert=function(t){return i(n.invert(t))},o.domain=function(t){return arguments.length?(e=t[0]>=0,n.domain((r=t.map(Number)).map(u)),o):r},o.base=function(e){return arguments.length?(t=+e,n.domain(r.map(u)),o):t},o.nice=function(){var t=Di(r.map(u),e?Math:gl);return n.domain(t),r=t.map(i),o},o.ticks=function(){var n=Ti(r),o=[],a=n[0],c=n[1],l=Math.floor(u(a)),s=Math.ceil(u(c)),f=t%1?2:t;if(isFinite(s-l)){if(e){for(;s>l;l++)for(var h=1;f>h;h++)o.push(i(l)*h);o.push(i(l))}else for(o.push(i(l));l++0;h--)o.push(i(l)*h);for(l=0;o[l]c;s--);o=o.slice(l,s)}return o},o.tickFormat=function(n,t){if(!arguments.length)return hl;arguments.length<2?t=hl:"function"!=typeof t&&(t=Vo.format(t));var r,a=Math.max(.1,n/o.ticks().length),c=e?(r=1e-12,Math.ceil):(r=-1e-12,Math.floor);return function(n){return n/i(c(u(n)+r))<=a?t(n):""}},o.copy=function(){return Xi(n.copy(),t,e,r)},Hi(o,n)}function $i(n,t,e){function r(t){return n(u(t))}var u=Bi(t),i=Bi(1/t);return r.invert=function(t){return i(n.invert(t))},r.domain=function(t){return arguments.length?(n.domain((e=t.map(Number)).map(u)),r):e},r.ticks=function(n){return Yi(e,n)},r.tickFormat=function(n,t){return Ii(e,n,t)},r.nice=function(n){return r.domain(Fi(e,n))},r.exponent=function(o){return arguments.length?(u=Bi(t=o),i=Bi(1/t),n.domain(e.map(u)),r):t},r.copy=function(){return $i(n.copy(),t,e)},Hi(r,n)}function Bi(n){return function(t){return 0>t?-Math.pow(-t,n):Math.pow(t,n)}}function Wi(n,t){function e(e){return i[((u.get(e)||("range"===t.t?u.set(e,n.push(e)):0/0))-1)%i.length]}function r(t,e){return Vo.range(n.length).map(function(n){return t+e*n})}var u,i,a;return e.domain=function(r){if(!arguments.length)return n;n=[],u=new o;for(var i,a=-1,c=r.length;++an?[0/0,0/0]:[n>0?o[n-1]:e[0],nt?0/0:t/i+n,[t,t+1/i]},r.copy=function(){return Gi(n,t,e)},u()}function Ki(n,t){function e(e){return e>=e?t[Vo.bisect(n,e)]:void 0}return e.domain=function(t){return arguments.length?(n=t,e):n},e.range=function(n){return arguments.length?(t=n,e):t},e.invertExtent=function(e){return e=t.indexOf(e),[n[e-1],n[e]]},e.copy=function(){return Ki(n,t)},e}function Qi(n){function t(n){return+n}return t.invert=t,t.domain=t.range=function(e){return arguments.length?(n=e.map(t),t):n},t.ticks=function(t){return Yi(n,t)},t.tickFormat=function(t,e){return Ii(n,t,e)},t.copy=function(){return Qi(n)},t}function no(n){return n.innerRadius}function to(n){return n.outerRadius}function eo(n){return n.startAngle}function ro(n){return n.endAngle}function uo(n){function t(t){function o(){l.push("M",i(n(s),a))}for(var c,l=[],s=[],f=-1,h=t.length,g=bt(e),p=bt(r);++f1&&u.push("H",r[0]),u.join("")}function co(n){for(var t=0,e=n.length,r=n[0],u=[r[0],",",r[1]];++t1){a=t[1],i=n[c],c++,r+="C"+(u[0]+o[0])+","+(u[1]+o[1])+","+(i[0]-a[0])+","+(i[1]-a[1])+","+i[0]+","+i[1];for(var l=2;l9&&(u=3*t/Math.sqrt(u),o[a]=u*e,o[a+1]=u*r));for(a=-1;++a<=c;)u=(n[Math.min(c,a+1)][0]-n[Math.max(0,a-1)][0])/(6*(1+o[a]*o[a])),i.push([u||0,o[a]*u||0]);return i}function ko(n){return n.length<3?io(n):n[0]+go(n,So(n))}function Eo(n){for(var t,e,r,u=-1,i=n.length;++ue?l():(u.active=e,i.event&&i.event.start.call(n,s,t),i.tween.forEach(function(e,r){(r=r.call(n,s,t))&&v.push(r)}),Vo.timer(function(){return p.c=c(r||1)?Se:c,1},0,a),void 0)}function c(r){if(u.active!==e)return l();for(var o=r/g,a=f(o),c=v.length;c>0;)v[--c].call(n,a);return o>=1?(i.event&&i.event.end.call(n,s,t),l()):void 0 -}function l(){return--u.count?delete u[e]:delete n.__transition__,1}var s=n.__data__,f=i.ease,h=i.delay,g=i.duration,p=Wa,v=[];return p.t=h+a,r>=h?o(r-h):(p.c=o,void 0)},0,a)}}function jo(n,t){n.attr("transform",function(n){return"translate("+t(n)+",0)"})}function Ho(n,t){n.attr("transform",function(n){return"translate(0,"+t(n)+")"})}function Fo(n){return n.toISOString()}function Oo(n,t,e){function r(t){return n(t)}function u(n,e){var r=n[1]-n[0],u=r/e,i=Vo.bisect(jl,u);return i==jl.length?[t.year,Oi(n.map(function(n){return n/31536e6}),e)[2]]:i?t[u/jl[i-1]1?{floor:function(t){for(;e(t=n.floor(t));)t=Yo(t-1);return t},ceil:function(t){for(;e(t=n.ceil(t));)t=Yo(+t+1);return t}}:n))},r.ticks=function(n,t){var e=Ti(r.domain()),i=null==n?u(e,10):"number"==typeof n?u(e,n):!n.range&&[{range:n},t];return i&&(n=i[0],t=i[1]),n.range(e[0],Yo(+e[1]+1),1>t?1:t)},r.tickFormat=function(){return e},r.copy=function(){return Oo(n.copy(),t,e)},Hi(r,n)}function Yo(n){return new Date(n)}function Io(n){return JSON.parse(n.responseText)}function Zo(n){var t=Bo.createRange();return t.selectNode(Bo.body),t.createContextualFragment(n.responseText)}var Vo={version:"3.4.12"};Date.now||(Date.now=function(){return+new Date});var Xo=[].slice,$o=function(n){return Xo.call(n)},Bo=document,Wo=Bo.documentElement,Jo=window;try{$o(Wo.childNodes)[0].nodeType}catch(Go){$o=function(n){for(var t=n.length,e=new Array(t);t--;)e[t]=n[t];return e}}try{Bo.createElement("div").style.setProperty("opacity",0,"")}catch(Ko){var Qo=Jo.Element.prototype,na=Qo.setAttribute,ta=Qo.setAttributeNS,ea=Jo.CSSStyleDeclaration.prototype,ra=ea.setProperty;Qo.setAttribute=function(n,t){na.call(this,n,t+"")},Qo.setAttributeNS=function(n,t,e){ta.call(this,n,t,e+"")},ea.setProperty=function(n,t,e){ra.call(this,n,t+"",e)}}Vo.ascending=n,Vo.descending=function(n,t){return n>t?-1:t>n?1:t>=n?0:0/0},Vo.min=function(n,t){var e,r,u=-1,i=n.length;if(1===arguments.length){for(;++u=e);)e=void 0;for(;++ur&&(e=r)}else{for(;++u=e);)e=void 0;for(;++ur&&(e=r)}return e},Vo.max=function(n,t){var e,r,u=-1,i=n.length;if(1===arguments.length){for(;++u=e);)e=void 0;for(;++ue&&(e=r)}else{for(;++u=e);)e=void 0;for(;++ue&&(e=r)}return e},Vo.extent=function(n,t){var e,r,u,i=-1,o=n.length;if(1===arguments.length){for(;++i=e);)e=u=void 0;for(;++ir&&(e=r),r>u&&(u=r))}else{for(;++i=e);)e=void 0;for(;++ir&&(e=r),r>u&&(u=r))}return[e,u]},Vo.sum=function(n,t){var e,r=0,u=n.length,i=-1;if(1===arguments.length)for(;++i1&&(e=e.map(r)),e=e.filter(t),e.length?Vo.quantile(e.sort(n),.5):void 0};var ua=e(n);Vo.bisectLeft=ua.left,Vo.bisect=Vo.bisectRight=ua.right,Vo.bisector=function(t){return e(1===t.length?function(e,r){return n(t(e),r)}:t)},Vo.shuffle=function(n){for(var t,e,r=n.length;r;)e=0|Math.random()*r--,t=n[r],n[r]=n[e],n[e]=t;return n},Vo.permute=function(n,t){for(var e=t.length,r=new Array(e);e--;)r[e]=n[t[e]];return r},Vo.pairs=function(n){for(var t,e=0,r=n.length-1,u=n[0],i=new Array(0>r?0:r);r>e;)i[e]=[t=u,u=n[++e]];return i},Vo.zip=function(){if(!(u=arguments.length))return[];for(var n=-1,t=Vo.min(arguments,r),e=new Array(t);++n=0;)for(r=n[u],t=r.length;--t>=0;)e[--o]=r[t];return e};var ia=Math.abs;Vo.range=function(n,t,e){if(arguments.length<3&&(e=1,arguments.length<2&&(t=n,n=0)),1/0===(t-n)/e)throw new Error("infinite range");var r,i=[],o=u(ia(e)),a=-1;if(n*=o,t*=o,e*=o,0>e)for(;(r=n+e*++a)>t;)i.push(r/o);else for(;(r=n+e*++a)=i.length)return r?r.call(u,a):e?a.sort(e):a;for(var l,s,f,h,g=-1,p=a.length,v=i[c++],d=new o;++g=i.length)return n;var r=[],u=a[e++];return n.forEach(function(n,u){r.push({key:n,values:t(u,e)})}),u?r.sort(function(n,t){return u(n.key,t.key)}):r}var e,r,u={},i=[],a=[];return u.map=function(t,e){return n(e,t,0)},u.entries=function(e){return t(n(Vo.map,e,0),0)},u.key=function(n){return i.push(n),u},u.sortKeys=function(n){return a[i.length-1]=n,u},u.sortValues=function(n){return e=n,u},u.rollup=function(n){return r=n,u},u},Vo.set=function(n){var t=new h;if(n)for(var e=0,r=n.length;r>e;++e)t.add(n[e]);return t},i(h,{has:a,add:function(n){return this[oa+n]=!0,n},remove:function(n){return n=oa+n,n in this&&delete this[n]},values:l,size:s,empty:f,forEach:function(n){for(var t in this)t.charCodeAt(0)===aa&&n.call(this,t.slice(1))}}),Vo.behavior={},Vo.rebind=function(n,t){for(var e,r=1,u=arguments.length;++r=0&&(r=n.slice(e+1),n=n.slice(0,e)),n)return arguments.length<2?this[n].on(r):this[n].on(r,t);if(2===arguments.length){if(null==t)for(n in this)this.hasOwnProperty(n)&&this[n].on(r,null);return this}},Vo.event=null,Vo.requote=function(n){return n.replace(la,"\\$&")};var la=/[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g,sa={}.__proto__?function(n,t){n.__proto__=t}:function(n,t){for(var e in t)n[e]=t[e]},fa=function(n,t){return t.querySelector(n)},ha=function(n,t){return t.querySelectorAll(n)},ga=Wo.matches||Wo[p(Wo,"matchesSelector")],pa=function(n,t){return ga.call(n,t)};"function"==typeof Sizzle&&(fa=function(n,t){return Sizzle(n,t)[0]||null},ha=Sizzle,pa=Sizzle.matchesSelector),Vo.selection=function(){return ya};var va=Vo.selection.prototype=[];va.select=function(n){var t,e,r,u,i=[];n=b(n);for(var o=-1,a=this.length;++o=0&&(e=n.slice(0,t),n=n.slice(t+1)),da.hasOwnProperty(e)?{space:da[e],local:n}:n}},va.attr=function(n,t){if(arguments.length<2){if("string"==typeof n){var e=this.node();return n=Vo.ns.qualify(n),n.local?e.getAttributeNS(n.space,n.local):e.getAttribute(n)}for(t in n)this.each(S(t,n[t]));return this}return this.each(S(n,t))},va.classed=function(n,t){if(arguments.length<2){if("string"==typeof n){var e=this.node(),r=(n=A(n)).length,u=-1;if(t=e.classList){for(;++ur){if("string"!=typeof n){2>r&&(t="");for(e in n)this.each(z(e,n[e],t));return this}if(2>r)return Jo.getComputedStyle(this.node(),null).getPropertyValue(n);e=""}return this.each(z(n,t,e))},va.property=function(n,t){if(arguments.length<2){if("string"==typeof n)return this.node()[n];for(t in n)this.each(L(t,n[t]));return this}return this.each(L(n,t))},va.text=function(n){return arguments.length?this.each("function"==typeof n?function(){var t=n.apply(this,arguments);this.textContent=null==t?"":t}:null==n?function(){this.textContent=""}:function(){this.textContent=n}):this.node().textContent},va.html=function(n){return arguments.length?this.each("function"==typeof n?function(){var t=n.apply(this,arguments);this.innerHTML=null==t?"":t}:null==n?function(){this.innerHTML=""}:function(){this.innerHTML=n}):this.node().innerHTML},va.append=function(n){return n=T(n),this.select(function(){return this.appendChild(n.apply(this,arguments))})},va.insert=function(n,t){return n=T(n),t=b(t),this.select(function(){return this.insertBefore(n.apply(this,arguments),t.apply(this,arguments)||null)})},va.remove=function(){return this.each(function(){var n=this.parentNode;n&&n.removeChild(this)})},va.data=function(n,t){function e(n,e){var r,u,i,a=n.length,f=e.length,h=Math.min(a,f),g=new Array(f),p=new Array(f),v=new Array(a);if(t){var d,m=new o,y=new o,x=[];for(r=-1;++rr;++r)p[r]=q(e[r]);for(;a>r;++r)v[r]=n[r]}p.update=g,p.parentNode=g.parentNode=v.parentNode=n.parentNode,c.push(p),l.push(g),s.push(v)}var r,u,i=-1,a=this.length;if(!arguments.length){for(n=new Array(a=(r=this[0]).length);++ii;i++){u.push(t=[]),t.parentNode=(e=this[i]).parentNode;for(var a=0,c=e.length;c>a;a++)(r=e[a])&&n.call(r,r.__data__,a,i)&&t.push(r)}return _(u)},va.order=function(){for(var n=-1,t=this.length;++n=0;)(e=r[u])&&(i&&i!==e.nextSibling&&i.parentNode.insertBefore(e,i),i=e);return this},va.sort=function(n){n=D.apply(this,arguments);for(var t=-1,e=this.length;++tn;n++)for(var e=this[n],r=0,u=e.length;u>r;r++){var i=e[r];if(i)return i}return null},va.size=function(){var n=0;return P(this,function(){++n}),n};var ma=[];Vo.selection.enter=U,Vo.selection.enter.prototype=ma,ma.append=va.append,ma.empty=va.empty,ma.node=va.node,ma.call=va.call,ma.size=va.size,ma.select=function(n){for(var t,e,r,u,i,o=[],a=-1,c=this.length;++ar){if("string"!=typeof n){2>r&&(t=!1);for(e in n)this.each(F(e,n[e],t));return this}if(2>r)return(r=this.node()["__on"+n])&&r._;e=!1}return this.each(F(n,t,e))};var xa=Vo.map({mouseenter:"mouseover",mouseleave:"mouseout"});xa.forEach(function(n){"on"+n in Bo&&xa.remove(n)});var Ma="onselectstart"in Bo?null:p(Wo.style,"userSelect"),_a=0;Vo.mouse=function(n){return Z(n,x())};var ba=/WebKit/.test(Jo.navigator.userAgent)?-1:0;Vo.touch=function(n,t,e){if(arguments.length<3&&(e=t,t=x().changedTouches),t)for(var r,u=0,i=t.length;i>u;++u)if((r=t[u]).identifier===e)return Z(n,r)},Vo.behavior.drag=function(){function n(){this.on("mousedown.drag",u).on("touchstart.drag",i)}function t(n,t,u,i,o){return function(){function a(){var n,e,r=t(h,v);r&&(n=r[0]-x[0],e=r[1]-x[1],p|=n|e,x=r,g({type:"drag",x:r[0]+l[0],y:r[1]+l[1],dx:n,dy:e}))}function c(){t(h,v)&&(m.on(i+d,null).on(o+d,null),y(p&&Vo.event.target===f),g({type:"dragend"}))}var l,s=this,f=Vo.event.target,h=s.parentNode,g=e.of(s,arguments),p=0,v=n(),d=".drag"+(null==v?"":"-"+v),m=Vo.select(u()).on(i+d,a).on(o+d,c),y=I(),x=t(h,v);r?(l=r.apply(s,arguments),l=[l.x-x[0],l.y-x[1]]):l=[0,0],g({type:"dragstart"})}}var e=M(n,"drag","dragstart","dragend"),r=null,u=t(v,Vo.mouse,$,"mousemove","mouseup"),i=t(V,Vo.touch,X,"touchmove","touchend");return n.origin=function(t){return arguments.length?(r=t,n):r},Vo.rebind(n,e,"on")},Vo.touches=function(n,t){return arguments.length<2&&(t=x().touches),t?$o(t).map(function(t){var e=Z(n,t);return e.identifier=t.identifier,e}):[]};var wa=Math.PI,Sa=2*wa,ka=wa/2,Ea=1e-6,Aa=Ea*Ea,Ca=wa/180,Na=180/wa,za=Math.SQRT2,La=2,Ta=4;Vo.interpolateZoom=function(n,t){function e(n){var t=n*y;if(m){var e=Q(v),o=i/(La*h)*(e*nt(za*t+v)-K(v));return[r+o*l,u+o*s,i*e/Q(za*t+v)]}return[r+n*l,u+n*s,i*Math.exp(za*t)]}var r=n[0],u=n[1],i=n[2],o=t[0],a=t[1],c=t[2],l=o-r,s=a-u,f=l*l+s*s,h=Math.sqrt(f),g=(c*c-i*i+Ta*f)/(2*i*La*h),p=(c*c-i*i-Ta*f)/(2*c*La*h),v=Math.log(Math.sqrt(g*g+1)-g),d=Math.log(Math.sqrt(p*p+1)-p),m=d-v,y=(m||Math.log(c/i))/za;return e.duration=1e3*y,e},Vo.behavior.zoom=function(){function n(n){n.on(A,l).on(Da+".zoom",f).on("dblclick.zoom",h).on(z,s)}function t(n){return[(n[0]-S.x)/S.k,(n[1]-S.y)/S.k]}function e(n){return[n[0]*S.k+S.x,n[1]*S.k+S.y]}function r(n){S.k=Math.max(E[0],Math.min(E[1],n))}function u(n,t){t=e(t),S.x+=n[0]-t[0],S.y+=n[1]-t[1]}function i(){_&&_.domain(x.range().map(function(n){return(n-S.x)/S.k}).map(x.invert)),w&&w.domain(b.range().map(function(n){return(n-S.y)/S.k}).map(b.invert))}function o(n){n({type:"zoomstart"})}function a(n){i(),n({type:"zoom",scale:S.k,translate:[S.x,S.y]})}function c(n){n({type:"zoomend"})}function l(){function n(){s=1,u(Vo.mouse(r),h),a(l)}function e(){f.on(C,null).on(N,null),g(s&&Vo.event.target===i),c(l)}var r=this,i=Vo.event.target,l=L.of(r,arguments),s=0,f=Vo.select(Jo).on(C,n).on(N,e),h=t(Vo.mouse(r)),g=I();H.call(r),o(l)}function s(){function n(){var n=Vo.touches(g);return h=S.k,n.forEach(function(n){n.identifier in v&&(v[n.identifier]=t(n))}),n}function e(){var t=Vo.event.target;Vo.select(t).on(M,i).on(_,f),b.push(t);for(var e=Vo.event.changedTouches,o=0,c=e.length;c>o;++o)v[e[o].identifier]=null;var l=n(),s=Date.now();if(1===l.length){if(500>s-m){var h=l[0],g=v[h.identifier];r(2*S.k),u(h,g),y(),a(p)}m=s}else if(l.length>1){var h=l[0],x=l[1],w=h[0]-x[0],k=h[1]-x[1];d=w*w+k*k}}function i(){for(var n,t,e,i,o=Vo.touches(g),c=0,l=o.length;l>c;++c,i=null)if(e=o[c],i=v[e.identifier]){if(t)break;n=e,t=i}if(i){var s=(s=e[0]-n[0])*s+(s=e[1]-n[1])*s,f=d&&Math.sqrt(s/d);n=[(n[0]+e[0])/2,(n[1]+e[1])/2],t=[(t[0]+i[0])/2,(t[1]+i[1])/2],r(f*h)}m=null,u(n,t),a(p)}function f(){if(Vo.event.touches.length){for(var t=Vo.event.changedTouches,e=0,r=t.length;r>e;++e)delete v[t[e].identifier];for(var u in v)return void n()}Vo.selectAll(b).on(x,null),w.on(A,l).on(z,s),k(),c(p)}var h,g=this,p=L.of(g,arguments),v={},d=0,x=".zoom-"+Vo.event.changedTouches[0].identifier,M="touchmove"+x,_="touchend"+x,b=[],w=Vo.select(g),k=I();H.call(g),e(),o(p),w.on(A,null).on(z,e)}function f(){var n=L.of(this,arguments);d?clearTimeout(d):(g=t(p=v||Vo.mouse(this)),H.call(this),o(n)),d=setTimeout(function(){d=null,c(n)},50),y(),r(Math.pow(2,.002*qa())*S.k),u(p,g),a(n)}function h(){var n=L.of(this,arguments),e=Vo.mouse(this),i=t(e),l=Math.log(S.k)/Math.LN2;o(n),r(Math.pow(2,Vo.event.shiftKey?Math.ceil(l)-1:Math.floor(l)+1)),u(e,i),a(n),c(n)}var g,p,v,d,m,x,_,b,w,S={x:0,y:0,k:1},k=[960,500],E=Ra,A="mousedown.zoom",C="mousemove.zoom",N="mouseup.zoom",z="touchstart.zoom",L=M(n,"zoomstart","zoom","zoomend");return n.event=function(n){n.each(function(){var n=L.of(this,arguments),t=S;kl?Vo.select(this).transition().each("start.zoom",function(){S=this.__chart__||{x:0,y:0,k:1},o(n)}).tween("zoom:zoom",function(){var e=k[0],r=k[1],u=e/2,i=r/2,o=Vo.interpolateZoom([(u-S.x)/S.k,(i-S.y)/S.k,e/S.k],[(u-t.x)/t.k,(i-t.y)/t.k,e/t.k]);return function(t){var r=o(t),c=e/r[2];this.__chart__=S={x:u-r[0]*c,y:i-r[1]*c,k:c},a(n)}}).each("end.zoom",function(){c(n)}):(this.__chart__=S,o(n),a(n),c(n))})},n.translate=function(t){return arguments.length?(S={x:+t[0],y:+t[1],k:S.k},i(),n):[S.x,S.y]},n.scale=function(t){return arguments.length?(S={x:S.x,y:S.y,k:+t},i(),n):S.k},n.scaleExtent=function(t){return arguments.length?(E=null==t?Ra:[+t[0],+t[1]],n):E},n.center=function(t){return arguments.length?(v=t&&[+t[0],+t[1]],n):v},n.size=function(t){return arguments.length?(k=t&&[+t[0],+t[1]],n):k},n.x=function(t){return arguments.length?(_=t,x=t.copy(),S={x:0,y:0,k:1},n):_},n.y=function(t){return arguments.length?(w=t,b=t.copy(),S={x:0,y:0,k:1},n):w},Vo.rebind(n,L,"on")};var qa,Ra=[0,1/0],Da="onwheel"in Bo?(qa=function(){return-Vo.event.deltaY*(Vo.event.deltaMode?120:1)},"wheel"):"onmousewheel"in Bo?(qa=function(){return Vo.event.wheelDelta},"mousewheel"):(qa=function(){return-Vo.event.detail},"MozMousePixelScroll");Vo.color=et,et.prototype.toString=function(){return this.rgb()+""},Vo.hsl=rt;var Pa=rt.prototype=new et;Pa.brighter=function(n){return n=Math.pow(.7,arguments.length?n:1),new rt(this.h,this.s,this.l/n)},Pa.darker=function(n){return n=Math.pow(.7,arguments.length?n:1),new rt(this.h,this.s,n*this.l)},Pa.rgb=function(){return ut(this.h,this.s,this.l)},Vo.hcl=it;var Ua=it.prototype=new et;Ua.brighter=function(n){return new it(this.h,this.c,Math.min(100,this.l+ja*(arguments.length?n:1)))},Ua.darker=function(n){return new it(this.h,this.c,Math.max(0,this.l-ja*(arguments.length?n:1)))},Ua.rgb=function(){return ot(this.h,this.c,this.l).rgb()},Vo.lab=at;var ja=18,Ha=.95047,Fa=1,Oa=1.08883,Ya=at.prototype=new et;Ya.brighter=function(n){return new at(Math.min(100,this.l+ja*(arguments.length?n:1)),this.a,this.b)},Ya.darker=function(n){return new at(Math.max(0,this.l-ja*(arguments.length?n:1)),this.a,this.b)},Ya.rgb=function(){return ct(this.l,this.a,this.b)},Vo.rgb=gt;var Ia=gt.prototype=new et;Ia.brighter=function(n){n=Math.pow(.7,arguments.length?n:1);var t=this.r,e=this.g,r=this.b,u=30;return t||e||r?(t&&u>t&&(t=u),e&&u>e&&(e=u),r&&u>r&&(r=u),new gt(Math.min(255,t/n),Math.min(255,e/n),Math.min(255,r/n))):new gt(u,u,u)},Ia.darker=function(n){return n=Math.pow(.7,arguments.length?n:1),new gt(n*this.r,n*this.g,n*this.b)},Ia.hsl=function(){return yt(this.r,this.g,this.b)},Ia.toString=function(){return"#"+dt(this.r)+dt(this.g)+dt(this.b)};var Za=Vo.map({aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074});Za.forEach(function(n,t){Za.set(n,pt(t))}),Vo.functor=bt,Vo.xhr=St(wt),Vo.dsv=function(n,t){function e(n,e,i){arguments.length<3&&(i=e,e=null);var o=kt(n,t,null==e?r:u(e),i);return o.row=function(n){return arguments.length?o.response(null==(e=n)?r:u(n)):e},o}function r(n){return e.parse(n.responseText)}function u(n){return function(t){return e.parse(t.responseText,n)}}function i(t){return t.map(o).join(n)}function o(n){return a.test(n)?'"'+n.replace(/\"/g,'""')+'"':n}var a=new RegExp('["'+n+"\n]"),c=n.charCodeAt(0);return e.parse=function(n,t){var r;return e.parseRows(n,function(n,e){if(r)return r(n,e-1);var u=new Function("d","return {"+n.map(function(n,t){return JSON.stringify(n)+": d["+t+"]"}).join(",")+"}");r=t?function(n,e){return t(u(n),e)}:u})},e.parseRows=function(n,t){function e(){if(s>=l)return o;if(u)return u=!1,i;var t=s;if(34===n.charCodeAt(t)){for(var e=t;e++s;){var r=n.charCodeAt(s++),a=1;if(10===r)u=!0;else if(13===r)u=!0,10===n.charCodeAt(s)&&(++s,++a);else if(r!==c)continue;return n.slice(t,s-a)}return n.slice(t)}for(var r,u,i={},o={},a=[],l=n.length,s=0,f=0;(r=e())!==o;){for(var h=[];r!==i&&r!==o;)h.push(r),r=e();(!t||(h=t(h,f++)))&&a.push(h)}return a},e.format=function(t){if(Array.isArray(t[0]))return e.formatRows(t);var r=new h,u=[];return t.forEach(function(n){for(var t in n)r.has(t)||u.push(r.add(t))}),[u.map(o).join(n)].concat(t.map(function(t){return u.map(function(n){return o(t[n])}).join(n)})).join("\n")},e.formatRows=function(n){return n.map(i).join("\n")},e},Vo.csv=Vo.dsv(",","text/csv"),Vo.tsv=Vo.dsv(" ","text/tab-separated-values");var Va,Xa,$a,Ba,Wa,Ja=Jo[p(Jo,"requestAnimationFrame")]||function(n){setTimeout(n,17)};Vo.timer=function(n,t,e){var r=arguments.length;2>r&&(t=0),3>r&&(e=Date.now());var u=e+t,i={c:n,t:u,f:!1,n:null};Xa?Xa.n=i:Va=i,Xa=i,$a||(Ba=clearTimeout(Ba),$a=1,Ja(Ct))},Vo.timer.flush=function(){Nt(),zt()},Vo.round=function(n,t){return t?Math.round(n*(t=Math.pow(10,t)))/t:Math.round(n)};var Ga=["y","z","a","f","p","n","\xb5","m","","k","M","G","T","P","E","Z","Y"].map(Tt);Vo.formatPrefix=function(n,t){var e=0;return n&&(0>n&&(n*=-1),t&&(n=Vo.round(n,Lt(n,t))),e=1+Math.floor(1e-12+Math.log(n)/Math.LN10),e=Math.max(-24,Math.min(24,3*Math.floor((e-1)/3)))),Ga[8+e/3]};var Ka=/(?:([^{])?([<>=^]))?([+\- ])?([$#])?(0)?(\d+)?(,)?(\.-?\d+)?([a-z%])?/i,Qa=Vo.map({b:function(n){return n.toString(2)},c:function(n){return String.fromCharCode(n)},o:function(n){return n.toString(8)},x:function(n){return n.toString(16)},X:function(n){return n.toString(16).toUpperCase()},g:function(n,t){return n.toPrecision(t)},e:function(n,t){return n.toExponential(t)},f:function(n,t){return n.toFixed(t)},r:function(n,t){return(n=Vo.round(n,Lt(n,t))).toFixed(Math.max(0,Math.min(20,Lt(n*(1+1e-15),t))))}}),nc=Vo.time={},tc=Date;Dt.prototype={getDate:function(){return this._.getUTCDate()},getDay:function(){return this._.getUTCDay()},getFullYear:function(){return this._.getUTCFullYear()},getHours:function(){return this._.getUTCHours()},getMilliseconds:function(){return this._.getUTCMilliseconds()},getMinutes:function(){return this._.getUTCMinutes()},getMonth:function(){return this._.getUTCMonth()},getSeconds:function(){return this._.getUTCSeconds()},getTime:function(){return this._.getTime()},getTimezoneOffset:function(){return 0},valueOf:function(){return this._.valueOf()},setDate:function(){ec.setUTCDate.apply(this._,arguments)},setDay:function(){ec.setUTCDay.apply(this._,arguments)},setFullYear:function(){ec.setUTCFullYear.apply(this._,arguments)},setHours:function(){ec.setUTCHours.apply(this._,arguments)},setMilliseconds:function(){ec.setUTCMilliseconds.apply(this._,arguments)},setMinutes:function(){ec.setUTCMinutes.apply(this._,arguments)},setMonth:function(){ec.setUTCMonth.apply(this._,arguments)},setSeconds:function(){ec.setUTCSeconds.apply(this._,arguments)},setTime:function(){ec.setTime.apply(this._,arguments)}};var ec=Date.prototype;nc.year=Pt(function(n){return n=nc.day(n),n.setMonth(0,1),n},function(n,t){n.setFullYear(n.getFullYear()+t)},function(n){return n.getFullYear()}),nc.years=nc.year.range,nc.years.utc=nc.year.utc.range,nc.day=Pt(function(n){var t=new tc(2e3,0);return t.setFullYear(n.getFullYear(),n.getMonth(),n.getDate()),t},function(n,t){n.setDate(n.getDate()+t)},function(n){return n.getDate()-1}),nc.days=nc.day.range,nc.days.utc=nc.day.utc.range,nc.dayOfYear=function(n){var t=nc.year(n);return Math.floor((n-t-6e4*(n.getTimezoneOffset()-t.getTimezoneOffset()))/864e5)},["sunday","monday","tuesday","wednesday","thursday","friday","saturday"].forEach(function(n,t){t=7-t;var e=nc[n]=Pt(function(n){return(n=nc.day(n)).setDate(n.getDate()-(n.getDay()+t)%7),n},function(n,t){n.setDate(n.getDate()+7*Math.floor(t))},function(n){var e=nc.year(n).getDay();return Math.floor((nc.dayOfYear(n)+(e+t)%7)/7)-(e!==t)});nc[n+"s"]=e.range,nc[n+"s"].utc=e.utc.range,nc[n+"OfYear"]=function(n){var e=nc.year(n).getDay();return Math.floor((nc.dayOfYear(n)+(e+t)%7)/7)}}),nc.week=nc.sunday,nc.weeks=nc.sunday.range,nc.weeks.utc=nc.sunday.utc.range,nc.weekOfYear=nc.sundayOfYear;var rc={"-":"",_:" ",0:"0"},uc=/^\s*\d+/,ic=/^%/;Vo.locale=function(n){return{numberFormat:qt(n),timeFormat:jt(n)}};var oc=Vo.locale({decimal:".",thousands:",",grouping:[3],currency:["$",""],dateTime:"%a %b %e %X %Y",date:"%m/%d/%Y",time:"%H:%M:%S",periods:["AM","PM"],days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],shortDays:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],shortMonths:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]});Vo.format=oc.numberFormat,Vo.geo={},ie.prototype={s:0,t:0,add:function(n){oe(n,this.t,ac),oe(ac.s,this.s,this),this.s?this.t+=ac.t:this.s=ac.t},reset:function(){this.s=this.t=0},valueOf:function(){return this.s}};var ac=new ie;Vo.geo.stream=function(n,t){n&&cc.hasOwnProperty(n.type)?cc[n.type](n,t):ae(n,t)};var cc={Feature:function(n,t){ae(n.geometry,t)},FeatureCollection:function(n,t){for(var e=n.features,r=-1,u=e.length;++rn?4*wa+n:n,hc.lineStart=hc.lineEnd=hc.point=v}};Vo.geo.bounds=function(){function n(n,t){x.push(M=[s=n,h=n]),f>t&&(f=t),t>g&&(g=t)}function t(t,e){var r=fe([t*Ca,e*Ca]);if(m){var u=ge(m,r),i=[u[1],-u[0],0],o=ge(i,u);de(o),o=me(o);var c=t-p,l=c>0?1:-1,v=o[0]*Na*l,d=ia(c)>180;if(d^(v>l*p&&l*t>v)){var y=o[1]*Na;y>g&&(g=y)}else if(v=(v+360)%360-180,d^(v>l*p&&l*t>v)){var y=-o[1]*Na;f>y&&(f=y)}else f>e&&(f=e),e>g&&(g=e);d?p>t?a(s,t)>a(s,h)&&(h=t):a(t,h)>a(s,h)&&(s=t):h>=s?(s>t&&(s=t),t>h&&(h=t)):t>p?a(s,t)>a(s,h)&&(h=t):a(t,h)>a(s,h)&&(s=t)}else n(t,e);m=r,p=t}function e(){_.point=t}function r(){M[0]=s,M[1]=h,_.point=n,m=null}function u(n,e){if(m){var r=n-p;y+=ia(r)>180?r+(r>0?360:-360):r}else v=n,d=e;hc.point(n,e),t(n,e)}function i(){hc.lineStart()}function o(){u(v,d),hc.lineEnd(),ia(y)>Ea&&(s=-(h=180)),M[0]=s,M[1]=h,m=null}function a(n,t){return(t-=n)<0?t+360:t}function c(n,t){return n[0]-t[0]}function l(n,t){return t[0]<=t[1]?t[0]<=n&&n<=t[1]:nfc?(s=-(h=180),f=-(g=90)):y>Ea?g=90:-Ea>y&&(f=-90),M[0]=s,M[1]=h}};return function(n){g=h=-(s=f=1/0),x=[],Vo.geo.stream(n,_);var t=x.length;if(t){x.sort(c);for(var e,r=1,u=x[0],i=[u];t>r;++r)e=x[r],l(e[0],u)||l(e[1],u)?(a(u[0],e[1])>a(u[0],u[1])&&(u[1]=e[1]),a(e[0],u[1])>a(u[0],u[1])&&(u[0]=e[0])):i.push(u=e);for(var o,e,p=-1/0,t=i.length-1,r=0,u=i[t];t>=r;u=e,++r)e=i[r],(o=a(u[1],e[0]))>p&&(p=o,s=e[0],h=u[1]) -}return x=M=null,1/0===s||1/0===f?[[0/0,0/0],[0/0,0/0]]:[[s,f],[h,g]]}}(),Vo.geo.centroid=function(n){gc=pc=vc=dc=mc=yc=xc=Mc=_c=bc=wc=0,Vo.geo.stream(n,Sc);var t=_c,e=bc,r=wc,u=t*t+e*e+r*r;return Aa>u&&(t=yc,e=xc,r=Mc,Ea>pc&&(t=vc,e=dc,r=mc),u=t*t+e*e+r*r,Aa>u)?[0/0,0/0]:[Math.atan2(e,t)*Na,G(r/Math.sqrt(u))*Na]};var gc,pc,vc,dc,mc,yc,xc,Mc,_c,bc,wc,Sc={sphere:v,point:xe,lineStart:_e,lineEnd:be,polygonStart:function(){Sc.lineStart=we},polygonEnd:function(){Sc.lineStart=_e}},kc=Ce(Se,Te,Re,[-wa,-wa/2]),Ec=1e9;Vo.geo.clipExtent=function(){var n,t,e,r,u,i,o={stream:function(n){return u&&(u.valid=!1),u=i(n),u.valid=!0,u},extent:function(a){return arguments.length?(i=je(n=+a[0][0],t=+a[0][1],e=+a[1][0],r=+a[1][1]),u&&(u.valid=!1,u=null),o):[[n,t],[e,r]]}};return o.extent([[0,0],[960,500]])},(Vo.geo.conicEqualArea=function(){return Fe(Oe)}).raw=Oe,Vo.geo.albers=function(){return Vo.geo.conicEqualArea().rotate([96,0]).center([-.6,38.7]).parallels([29.5,45.5]).scale(1070)},Vo.geo.albersUsa=function(){function n(n){var i=n[0],o=n[1];return t=null,e(i,o),t||(r(i,o),t)||u(i,o),t}var t,e,r,u,i=Vo.geo.albers(),o=Vo.geo.conicEqualArea().rotate([154,0]).center([-2,58.5]).parallels([55,65]),a=Vo.geo.conicEqualArea().rotate([157,0]).center([-3,19.9]).parallels([8,18]),c={point:function(n,e){t=[n,e]}};return n.invert=function(n){var t=i.scale(),e=i.translate(),r=(n[0]-e[0])/t,u=(n[1]-e[1])/t;return(u>=.12&&.234>u&&r>=-.425&&-.214>r?o:u>=.166&&.234>u&&r>=-.214&&-.115>r?a:i).invert(n)},n.stream=function(n){var t=i.stream(n),e=o.stream(n),r=a.stream(n);return{point:function(n,u){t.point(n,u),e.point(n,u),r.point(n,u)},sphere:function(){t.sphere(),e.sphere(),r.sphere()},lineStart:function(){t.lineStart(),e.lineStart(),r.lineStart()},lineEnd:function(){t.lineEnd(),e.lineEnd(),r.lineEnd()},polygonStart:function(){t.polygonStart(),e.polygonStart(),r.polygonStart()},polygonEnd:function(){t.polygonEnd(),e.polygonEnd(),r.polygonEnd()}}},n.precision=function(t){return arguments.length?(i.precision(t),o.precision(t),a.precision(t),n):i.precision()},n.scale=function(t){return arguments.length?(i.scale(t),o.scale(.35*t),a.scale(t),n.translate(i.translate())):i.scale()},n.translate=function(t){if(!arguments.length)return i.translate();var l=i.scale(),s=+t[0],f=+t[1];return e=i.translate(t).clipExtent([[s-.455*l,f-.238*l],[s+.455*l,f+.238*l]]).stream(c).point,r=o.translate([s-.307*l,f+.201*l]).clipExtent([[s-.425*l+Ea,f+.12*l+Ea],[s-.214*l-Ea,f+.234*l-Ea]]).stream(c).point,u=a.translate([s-.205*l,f+.212*l]).clipExtent([[s-.214*l+Ea,f+.166*l+Ea],[s-.115*l-Ea,f+.234*l-Ea]]).stream(c).point,n},n.scale(1070)};var Ac,Cc,Nc,zc,Lc,Tc,qc={point:v,lineStart:v,lineEnd:v,polygonStart:function(){Cc=0,qc.lineStart=Ye},polygonEnd:function(){qc.lineStart=qc.lineEnd=qc.point=v,Ac+=ia(Cc/2)}},Rc={point:Ie,lineStart:v,lineEnd:v,polygonStart:v,polygonEnd:v},Dc={point:Xe,lineStart:$e,lineEnd:Be,polygonStart:function(){Dc.lineStart=We},polygonEnd:function(){Dc.point=Xe,Dc.lineStart=$e,Dc.lineEnd=Be}};Vo.geo.path=function(){function n(n){return n&&("function"==typeof a&&i.pointRadius(+a.apply(this,arguments)),o&&o.valid||(o=u(i)),Vo.geo.stream(n,o)),i.result()}function t(){return o=null,n}var e,r,u,i,o,a=4.5;return n.area=function(n){return Ac=0,Vo.geo.stream(n,u(qc)),Ac},n.centroid=function(n){return vc=dc=mc=yc=xc=Mc=_c=bc=wc=0,Vo.geo.stream(n,u(Dc)),wc?[_c/wc,bc/wc]:Mc?[yc/Mc,xc/Mc]:mc?[vc/mc,dc/mc]:[0/0,0/0]},n.bounds=function(n){return Lc=Tc=-(Nc=zc=1/0),Vo.geo.stream(n,u(Rc)),[[Nc,zc],[Lc,Tc]]},n.projection=function(n){return arguments.length?(u=(e=n)?n.stream||Ke(n):wt,t()):e},n.context=function(n){return arguments.length?(i=null==(r=n)?new Ze:new Je(n),"function"!=typeof a&&i.pointRadius(a),t()):r},n.pointRadius=function(t){return arguments.length?(a="function"==typeof t?t:(i.pointRadius(+t),+t),n):a},n.projection(Vo.geo.albersUsa()).context(null)},Vo.geo.transform=function(n){return{stream:function(t){var e=new Qe(t);for(var r in n)e[r]=n[r];return e}}},Qe.prototype={point:function(n,t){this.stream.point(n,t)},sphere:function(){this.stream.sphere()},lineStart:function(){this.stream.lineStart()},lineEnd:function(){this.stream.lineEnd()},polygonStart:function(){this.stream.polygonStart()},polygonEnd:function(){this.stream.polygonEnd()}},Vo.geo.projection=tr,Vo.geo.projectionMutator=er,(Vo.geo.equirectangular=function(){return tr(ur)}).raw=ur.invert=ur,Vo.geo.rotation=function(n){function t(t){return t=n(t[0]*Ca,t[1]*Ca),t[0]*=Na,t[1]*=Na,t}return n=or(n[0]%360*Ca,n[1]*Ca,n.length>2?n[2]*Ca:0),t.invert=function(t){return t=n.invert(t[0]*Ca,t[1]*Ca),t[0]*=Na,t[1]*=Na,t},t},ir.invert=ur,Vo.geo.circle=function(){function n(){var n="function"==typeof r?r.apply(this,arguments):r,t=or(-n[0]*Ca,-n[1]*Ca,0).invert,u=[];return e(null,null,1,{point:function(n,e){u.push(n=t(n,e)),n[0]*=Na,n[1]*=Na}}),{type:"Polygon",coordinates:[u]}}var t,e,r=[0,0],u=6;return n.origin=function(t){return arguments.length?(r=t,n):r},n.angle=function(r){return arguments.length?(e=sr((t=+r)*Ca,u*Ca),n):t},n.precision=function(r){return arguments.length?(e=sr(t*Ca,(u=+r)*Ca),n):u},n.angle(90)},Vo.geo.distance=function(n,t){var e,r=(t[0]-n[0])*Ca,u=n[1]*Ca,i=t[1]*Ca,o=Math.sin(r),a=Math.cos(r),c=Math.sin(u),l=Math.cos(u),s=Math.sin(i),f=Math.cos(i);return Math.atan2(Math.sqrt((e=f*o)*e+(e=l*s-c*f*a)*e),c*s+l*f*a)},Vo.geo.graticule=function(){function n(){return{type:"MultiLineString",coordinates:t()}}function t(){return Vo.range(Math.ceil(i/d)*d,u,d).map(h).concat(Vo.range(Math.ceil(l/m)*m,c,m).map(g)).concat(Vo.range(Math.ceil(r/p)*p,e,p).filter(function(n){return ia(n%d)>Ea}).map(s)).concat(Vo.range(Math.ceil(a/v)*v,o,v).filter(function(n){return ia(n%m)>Ea}).map(f))}var e,r,u,i,o,a,c,l,s,f,h,g,p=10,v=p,d=90,m=360,y=2.5;return n.lines=function(){return t().map(function(n){return{type:"LineString",coordinates:n}})},n.outline=function(){return{type:"Polygon",coordinates:[h(i).concat(g(c).slice(1),h(u).reverse().slice(1),g(l).reverse().slice(1))]}},n.extent=function(t){return arguments.length?n.majorExtent(t).minorExtent(t):n.minorExtent()},n.majorExtent=function(t){return arguments.length?(i=+t[0][0],u=+t[1][0],l=+t[0][1],c=+t[1][1],i>u&&(t=i,i=u,u=t),l>c&&(t=l,l=c,c=t),n.precision(y)):[[i,l],[u,c]]},n.minorExtent=function(t){return arguments.length?(r=+t[0][0],e=+t[1][0],a=+t[0][1],o=+t[1][1],r>e&&(t=r,r=e,e=t),a>o&&(t=a,a=o,o=t),n.precision(y)):[[r,a],[e,o]]},n.step=function(t){return arguments.length?n.majorStep(t).minorStep(t):n.minorStep()},n.majorStep=function(t){return arguments.length?(d=+t[0],m=+t[1],n):[d,m]},n.minorStep=function(t){return arguments.length?(p=+t[0],v=+t[1],n):[p,v]},n.precision=function(t){return arguments.length?(y=+t,s=hr(a,o,90),f=gr(r,e,y),h=hr(l,c,90),g=gr(i,u,y),n):y},n.majorExtent([[-180,-90+Ea],[180,90-Ea]]).minorExtent([[-180,-80-Ea],[180,80+Ea]])},Vo.geo.greatArc=function(){function n(){return{type:"LineString",coordinates:[t||r.apply(this,arguments),e||u.apply(this,arguments)]}}var t,e,r=pr,u=vr;return n.distance=function(){return Vo.geo.distance(t||r.apply(this,arguments),e||u.apply(this,arguments))},n.source=function(e){return arguments.length?(r=e,t="function"==typeof e?null:e,n):r},n.target=function(t){return arguments.length?(u=t,e="function"==typeof t?null:t,n):u},n.precision=function(){return arguments.length?n:0},n},Vo.geo.interpolate=function(n,t){return dr(n[0]*Ca,n[1]*Ca,t[0]*Ca,t[1]*Ca)},Vo.geo.length=function(n){return Pc=0,Vo.geo.stream(n,Uc),Pc};var Pc,Uc={sphere:v,point:v,lineStart:mr,lineEnd:v,polygonStart:v,polygonEnd:v},jc=yr(function(n){return Math.sqrt(2/(1+n))},function(n){return 2*Math.asin(n/2)});(Vo.geo.azimuthalEqualArea=function(){return tr(jc)}).raw=jc;var Hc=yr(function(n){var t=Math.acos(n);return t&&t/Math.sin(t)},wt);(Vo.geo.azimuthalEquidistant=function(){return tr(Hc)}).raw=Hc,(Vo.geo.conicConformal=function(){return Fe(xr)}).raw=xr,(Vo.geo.conicEquidistant=function(){return Fe(Mr)}).raw=Mr;var Fc=yr(function(n){return 1/n},Math.atan);(Vo.geo.gnomonic=function(){return tr(Fc)}).raw=Fc,_r.invert=function(n,t){return[n,2*Math.atan(Math.exp(t))-ka]},(Vo.geo.mercator=function(){return br(_r)}).raw=_r;var Oc=yr(function(){return 1},Math.asin);(Vo.geo.orthographic=function(){return tr(Oc)}).raw=Oc;var Yc=yr(function(n){return 1/(1+n)},function(n){return 2*Math.atan(n)});(Vo.geo.stereographic=function(){return tr(Yc)}).raw=Yc,wr.invert=function(n,t){return[-t,2*Math.atan(Math.exp(n))-ka]},(Vo.geo.transverseMercator=function(){var n=br(wr),t=n.center,e=n.rotate;return n.center=function(n){return n?t([-n[1],n[0]]):(n=t(),[n[1],-n[0]])},n.rotate=function(n){return n?e([n[0],n[1],n.length>2?n[2]+90:90]):(n=e(),[n[0],n[1],n[2]-90])},e([0,0,90])}).raw=wr,Vo.geom={},Vo.geom.hull=function(n){function t(n){if(n.length<3)return[];var t,u=bt(e),i=bt(r),o=n.length,a=[],c=[];for(t=0;o>t;t++)a.push([+u.call(this,n[t],t),+i.call(this,n[t],t),t]);for(a.sort(Ar),t=0;o>t;t++)c.push([a[t][0],-a[t][1]]);var l=Er(a),s=Er(c),f=s[0]===l[0],h=s[s.length-1]===l[l.length-1],g=[];for(t=l.length-1;t>=0;--t)g.push(n[a[l[t]][2]]);for(t=+f;t=r&&l.x<=i&&l.y>=u&&l.y<=o?[[r,o],[i,o],[i,u],[r,u]]:[];s.point=n[a]}),t}function e(n){return n.map(function(n,t){return{x:Math.round(i(n,t)/Ea)*Ea,y:Math.round(o(n,t)/Ea)*Ea,i:t}})}var r=Sr,u=kr,i=r,o=u,a=Gc;return n?t(n):(t.links=function(n){return eu(e(n)).edges.filter(function(n){return n.l&&n.r}).map(function(t){return{source:n[t.l.i],target:n[t.r.i]}})},t.triangles=function(n){var t=[];return eu(e(n)).cells.forEach(function(e,r){for(var u,i,o=e.site,a=e.edges.sort(Fr),c=-1,l=a.length,s=a[l-1].edge,f=s.l===o?s.r:s.l;++c=l,h=r>=s,g=(h<<1)+f;n.leaf=!1,n=n.nodes[g]||(n.nodes[g]=au()),f?u=l:a=l,h?o=s:c=s,i(n,t,e,r,u,o,a,c)}var s,f,h,g,p,v,d,m,y,x=bt(a),M=bt(c);if(null!=t)v=t,d=e,m=r,y=u;else if(m=y=-(v=d=1/0),f=[],h=[],p=n.length,o)for(g=0;p>g;++g)s=n[g],s.xm&&(m=s.x),s.y>y&&(y=s.y),f.push(s.x),h.push(s.y);else for(g=0;p>g;++g){var _=+x(s=n[g],g),b=+M(s,g);v>_&&(v=_),d>b&&(d=b),_>m&&(m=_),b>y&&(y=b),f.push(_),h.push(b)}var w=m-v,S=y-d;w>S?y=d+w:m=v+S;var k=au();if(k.add=function(n){i(k,n,+x(n,++g),+M(n,g),v,d,m,y)},k.visit=function(n){cu(n,k,v,d,m,y)},g=-1,null==t){for(;++g=0?n.slice(0,t):n,r=t>=0?n.slice(t+1):"in";return e=tl.get(e)||nl,r=el.get(r)||wt,vu(r(e.apply(null,Xo.call(arguments,1))))},Vo.interpolateHcl=Cu,Vo.interpolateHsl=Nu,Vo.interpolateLab=zu,Vo.interpolateRound=Lu,Vo.transform=function(n){var t=Bo.createElementNS(Vo.ns.prefix.svg,"g");return(Vo.transform=function(n){if(null!=n){t.setAttribute("transform",n);var e=t.transform.baseVal.consolidate()}return new Tu(e?e.matrix:rl)})(n)},Tu.prototype.toString=function(){return"translate("+this.translate+")rotate("+this.rotate+")skewX("+this.skew+")scale("+this.scale+")"};var rl={a:1,b:0,c:0,d:1,e:0,f:0};Vo.interpolateTransform=Pu,Vo.layout={},Vo.layout.bundle=function(){return function(n){for(var t=[],e=-1,r=n.length;++ea*a/d){if(p>c){var l=t.charge/c;n.px-=i*l,n.py-=o*l}return!0}if(t.point&&c&&p>c){var l=t.pointCharge/c;n.px-=i*l,n.py-=o*l}}return!t.charge}}function t(n){n.px=Vo.event.x,n.py=Vo.event.y,a.resume()}var e,r,u,i,o,a={},c=Vo.dispatch("start","tick","end"),l=[1,1],s=.9,f=ul,h=il,g=-30,p=ol,v=.1,d=.64,m=[],y=[];return a.tick=function(){if((r*=.99)<.005)return c.end({type:"end",alpha:r=0}),!0;var t,e,a,f,h,p,d,x,M,_=m.length,b=y.length;for(e=0;b>e;++e)a=y[e],f=a.source,h=a.target,x=h.x-f.x,M=h.y-f.y,(p=x*x+M*M)&&(p=r*i[e]*((p=Math.sqrt(p))-u[e])/p,x*=p,M*=p,h.x-=x*(d=f.weight/(h.weight+f.weight)),h.y-=M*d,f.x+=x*(d=1-d),f.y+=M*d);if((d=r*v)&&(x=l[0]/2,M=l[1]/2,e=-1,d))for(;++e<_;)a=m[e],a.x+=(x-a.x)*d,a.y+=(M-a.y)*d;if(g)for(Xu(t=Vo.geom.quadtree(m),r,o),e=-1;++e<_;)(a=m[e]).fixed||t.visit(n(a));for(e=-1;++e<_;)a=m[e],a.fixed?(a.x=a.px,a.y=a.py):(a.x-=(a.px-(a.px=a.x))*s,a.y-=(a.py-(a.py=a.y))*s);c.tick({type:"tick",alpha:r})},a.nodes=function(n){return arguments.length?(m=n,a):m},a.links=function(n){return arguments.length?(y=n,a):y},a.size=function(n){return arguments.length?(l=n,a):l},a.linkDistance=function(n){return arguments.length?(f="function"==typeof n?n:+n,a):f},a.distance=a.linkDistance,a.linkStrength=function(n){return arguments.length?(h="function"==typeof n?n:+n,a):h},a.friction=function(n){return arguments.length?(s=+n,a):s},a.charge=function(n){return arguments.length?(g="function"==typeof n?n:+n,a):g},a.chargeDistance=function(n){return arguments.length?(p=n*n,a):Math.sqrt(p)},a.gravity=function(n){return arguments.length?(v=+n,a):v},a.theta=function(n){return arguments.length?(d=n*n,a):Math.sqrt(d)},a.alpha=function(n){return arguments.length?(n=+n,r?r=n>0?n:0:n>0&&(c.start({type:"start",alpha:r=n}),Vo.timer(a.tick)),a):r},a.start=function(){function n(n,r){if(!e){for(e=new Array(c),a=0;c>a;++a)e[a]=[];for(a=0;l>a;++a){var u=y[a];e[u.source.index].push(u.target),e[u.target.index].push(u.source)}}for(var i,o=e[t],a=-1,l=o.length;++at;++t)(r=m[t]).index=t,r.weight=0;for(t=0;s>t;++t)r=y[t],"number"==typeof r.source&&(r.source=m[r.source]),"number"==typeof r.target&&(r.target=m[r.target]),++r.source.weight,++r.target.weight;for(t=0;c>t;++t)r=m[t],isNaN(r.x)&&(r.x=n("x",p)),isNaN(r.y)&&(r.y=n("y",v)),isNaN(r.px)&&(r.px=r.x),isNaN(r.py)&&(r.py=r.y);if(u=[],"function"==typeof f)for(t=0;s>t;++t)u[t]=+f.call(this,y[t],t);else for(t=0;s>t;++t)u[t]=f;if(i=[],"function"==typeof h)for(t=0;s>t;++t)i[t]=+h.call(this,y[t],t);else for(t=0;s>t;++t)i[t]=h;if(o=[],"function"==typeof g)for(t=0;c>t;++t)o[t]=+g.call(this,m[t],t);else for(t=0;c>t;++t)o[t]=g;return a.resume()},a.resume=function(){return a.alpha(.1)},a.stop=function(){return a.alpha(0)},a.drag=function(){return e||(e=Vo.behavior.drag().origin(wt).on("dragstart.force",Yu).on("drag.force",t).on("dragend.force",Iu)),arguments.length?(this.on("mouseover.force",Zu).on("mouseout.force",Vu).call(e),void 0):e},Vo.rebind(a,c,"on")};var ul=20,il=1,ol=1/0;Vo.layout.hierarchy=function(){function n(u){var i,o=[u],a=[];for(u.depth=0;null!=(i=o.pop());)if(a.push(i),(l=e.call(n,i,i.depth))&&(c=l.length)){for(var c,l,s;--c>=0;)o.push(s=l[c]),s.parent=i,s.depth=i.depth+1;r&&(i.value=0),i.children=l}else r&&(i.value=+r.call(n,i,i.depth)||0),delete i.children;return Wu(u,function(n){var e,u;t&&(e=n.children)&&e.sort(t),r&&(u=n.parent)&&(u.value+=n.value)}),a}var t=Ku,e=Ju,r=Gu;return n.sort=function(e){return arguments.length?(t=e,n):t},n.children=function(t){return arguments.length?(e=t,n):e},n.value=function(t){return arguments.length?(r=t,n):r},n.revalue=function(t){return r&&(Bu(t,function(n){n.children&&(n.value=0)}),Wu(t,function(t){var e;t.children||(t.value=+r.call(n,t,t.depth)||0),(e=t.parent)&&(e.value+=t.value)})),t},n},Vo.layout.partition=function(){function n(t,e,r,u){var i=t.children;if(t.x=e,t.y=t.depth*u,t.dx=r,t.dy=u,i&&(o=i.length)){var o,a,c,l=-1;for(r=t.value?r/t.value:0;++lg;++g)for(u.call(n,l[0][g],p=v[g],s[0][g][1]),h=1;d>h;++h)u.call(n,l[h][g],p+=s[h-1][g][1],s[h][g][1]);return a}var t=wt,e=ri,r=ui,u=ei,i=ni,o=ti;return n.values=function(e){return arguments.length?(t=e,n):t},n.order=function(t){return arguments.length?(e="function"==typeof t?t:cl.get(t)||ri,n):e},n.offset=function(t){return arguments.length?(r="function"==typeof t?t:ll.get(t)||ui,n):r},n.x=function(t){return arguments.length?(i=t,n):i},n.y=function(t){return arguments.length?(o=t,n):o},n.out=function(t){return arguments.length?(u=t,n):u},n};var cl=Vo.map({"inside-out":function(n){var t,e,r=n.length,u=n.map(ii),i=n.map(oi),o=Vo.range(r).sort(function(n,t){return u[n]-u[t]}),a=0,c=0,l=[],s=[];for(t=0;r>t;++t)e=o[t],c>a?(a+=i[e],l.push(e)):(c+=i[e],s.push(e));return s.reverse().concat(l)},reverse:function(n){return Vo.range(n.length).reverse()},"default":ri}),ll=Vo.map({silhouette:function(n){var t,e,r,u=n.length,i=n[0].length,o=[],a=0,c=[];for(e=0;i>e;++e){for(t=0,r=0;u>t;t++)r+=n[t][e][1];r>a&&(a=r),o.push(r)}for(e=0;i>e;++e)c[e]=(a-o[e])/2;return c},wiggle:function(n){var t,e,r,u,i,o,a,c,l,s=n.length,f=n[0],h=f.length,g=[];for(g[0]=c=l=0,e=1;h>e;++e){for(t=0,u=0;s>t;++t)u+=n[t][e][1];for(t=0,i=0,a=f[e][0]-f[e-1][0];s>t;++t){for(r=0,o=(n[t][e][1]-n[t][e-1][1])/(2*a);t>r;++r)o+=(n[r][e][1]-n[r][e-1][1])/a;i+=o*n[t][e][1]}g[e]=c-=u?i/u*a:0,l>c&&(l=c)}for(e=0;h>e;++e)g[e]-=l;return g},expand:function(n){var t,e,r,u=n.length,i=n[0].length,o=1/u,a=[];for(e=0;i>e;++e){for(t=0,r=0;u>t;t++)r+=n[t][e][1];if(r)for(t=0;u>t;t++)n[t][e][1]/=r;else for(t=0;u>t;t++)n[t][e][1]=o}for(e=0;i>e;++e)a[e]=0;return a},zero:ui});Vo.layout.histogram=function(){function n(n,i){for(var o,a,c=[],l=n.map(e,this),s=r.call(this,l,i),f=u.call(this,s,l,i),i=-1,h=l.length,g=f.length-1,p=t?1:1/h;++i0)for(i=-1;++i=s[0]&&a<=s[1]&&(o=c[Vo.bisect(f,a,1,g)-1],o.y+=p,o.push(n[i]));return c}var t=!0,e=Number,r=si,u=ci;return n.value=function(t){return arguments.length?(e=t,n):e},n.range=function(t){return arguments.length?(r=bt(t),n):r},n.bins=function(t){return arguments.length?(u="number"==typeof t?function(n){return li(n,t)}:bt(t),n):u},n.frequency=function(e){return arguments.length?(t=!!e,n):t},n},Vo.layout.pack=function(){function n(n,i){var o=e.call(this,n,i),a=o[0],c=u[0],l=u[1],s=null==t?Math.sqrt:"function"==typeof t?t:function(){return t};if(a.x=a.y=0,Wu(a,function(n){n.r=+s(n.value)}),Wu(a,vi),r){var f=r*(t?1:Math.max(2*a.r/c,2*a.r/l))/2;Wu(a,function(n){n.r+=f}),Wu(a,vi),Wu(a,function(n){n.r-=f})}return yi(a,c/2,l/2,t?1:1/Math.max(2*a.r/c,2*a.r/l)),o}var t,e=Vo.layout.hierarchy().sort(fi),r=0,u=[1,1];return n.size=function(t){return arguments.length?(u=t,n):u},n.radius=function(e){return arguments.length?(t=null==e||"function"==typeof e?e:+e,n):t},n.padding=function(t){return arguments.length?(r=+t,n):r},$u(n,e)},Vo.layout.tree=function(){function n(n,u){var s=o.call(this,n,u),f=s[0],h=t(f);if(Wu(h,e),h.parent.m=-h.z,Bu(h,r),l)Bu(f,i);else{var g=f,p=f,v=f;Bu(f,function(n){n.xp.x&&(p=n),n.depth>v.depth&&(v=n)});var d=a(g,p)/2-g.x,m=c[0]/(p.x+a(p,g)/2+d),y=c[1]/(v.depth||1);Bu(f,function(n){n.x=(n.x+d)*m,n.y=n.depth*y})}return s}function t(n){for(var t,e={A:null,children:[n]},r=[e];null!=(t=r.pop());)for(var u,i=t.children,o=0,a=i.length;a>o;++o)r.push((i[o]=u={_:i[o],parent:t,children:(u=i[o].children)&&u.slice()||[],A:null,a:null,z:0,m:0,c:0,s:0,t:null,i:o}).a=u);return e.children[0]}function e(n){var t=n.children,e=n.parent.children,r=n.i?e[n.i-1]:null;if(t.length){Si(n);var i=(t[0].z+t[t.length-1].z)/2;r?(n.z=r.z+a(n._,r._),n.m=n.z-i):n.z=i}else r&&(n.z=r.z+a(n._,r._));n.parent.A=u(n,r,n.parent.A||e[0])}function r(n){n._.x=n.z+n.parent.m,n.m+=n.parent.m}function u(n,t,e){if(t){for(var r,u=n,i=n,o=t,c=u.parent.children[0],l=u.m,s=i.m,f=o.m,h=c.m;o=bi(o),u=_i(u),o&&u;)c=_i(c),i=bi(i),i.a=n,r=o.z+f-u.z-l+a(o._,u._),r>0&&(wi(ki(o,n,e),n,r),l+=r,s+=r),f+=o.m,l+=u.m,h+=c.m,s+=i.m;o&&!bi(i)&&(i.t=o,i.m+=f-s),u&&!_i(c)&&(c.t=u,c.m+=l-h,e=n)}return e}function i(n){n.x*=c[0],n.y=n.depth*c[1]}var o=Vo.layout.hierarchy().sort(null).value(null),a=Mi,c=[1,1],l=null;return n.separation=function(t){return arguments.length?(a=t,n):a},n.size=function(t){return arguments.length?(l=null==(c=t)?i:null,n):l?null:c},n.nodeSize=function(t){return arguments.length?(l=null==(c=t)?null:i,n):l?c:null},$u(n,o)},Vo.layout.cluster=function(){function n(n,i){var o,a=t.call(this,n,i),c=a[0],l=0;Wu(c,function(n){var t=n.children;t&&t.length?(n.x=Ai(t),n.y=Ei(t)):(n.x=o?l+=e(n,o):0,n.y=0,o=n)});var s=Ci(c),f=Ni(c),h=s.x-e(s,f)/2,g=f.x+e(f,s)/2;return Wu(c,u?function(n){n.x=(n.x-c.x)*r[0],n.y=(c.y-n.y)*r[1]}:function(n){n.x=(n.x-h)/(g-h)*r[0],n.y=(1-(c.y?n.y/c.y:1))*r[1]}),a}var t=Vo.layout.hierarchy().sort(null).value(null),e=Mi,r=[1,1],u=!1;return n.separation=function(t){return arguments.length?(e=t,n):e},n.size=function(t){return arguments.length?(u=null==(r=t),n):u?null:r},n.nodeSize=function(t){return arguments.length?(u=null!=(r=t),n):u?r:null},$u(n,t)},Vo.layout.treemap=function(){function n(n,t){for(var e,r,u=-1,i=n.length;++ut?0:t),e.area=isNaN(r)||0>=r?0:r}function t(e){var i=e.children;if(i&&i.length){var o,a,c,l=f(e),s=[],h=i.slice(),p=1/0,v="slice"===g?l.dx:"dice"===g?l.dy:"slice-dice"===g?1&e.depth?l.dy:l.dx:Math.min(l.dx,l.dy);for(n(h,l.dx*l.dy/e.value),s.area=0;(c=h.length)>0;)s.push(o=h[c-1]),s.area+=o.area,"squarify"!==g||(a=r(s,v))<=p?(h.pop(),p=a):(s.area-=s.pop().area,u(s,v,l,!1),v=Math.min(l.dx,l.dy),s.length=s.area=0,p=1/0);s.length&&(u(s,v,l,!0),s.length=s.area=0),i.forEach(t)}}function e(t){var r=t.children;if(r&&r.length){var i,o=f(t),a=r.slice(),c=[];for(n(a,o.dx*o.dy/t.value),c.area=0;i=a.pop();)c.push(i),c.area+=i.area,null!=i.z&&(u(c,i.z?o.dx:o.dy,o,!a.length),c.length=c.area=0);r.forEach(e)}}function r(n,t){for(var e,r=n.area,u=0,i=1/0,o=-1,a=n.length;++oe&&(i=e),e>u&&(u=e));return r*=r,t*=t,r?Math.max(t*u*p/r,r/(t*i*p)):1/0}function u(n,t,e,r){var u,i=-1,o=n.length,a=e.x,l=e.y,s=t?c(n.area/t):0;if(t==e.dx){for((r||s>e.dy)&&(s=e.dy);++ie.dx)&&(s=e.dx);++ie&&(t=1),1>e&&(n=0),function(){var e,r,u;do e=2*Math.random()-1,r=2*Math.random()-1,u=e*e+r*r;while(!u||u>1);return n+t*e*Math.sqrt(-2*Math.log(u)/u)}},logNormal:function(){var n=Vo.random.normal.apply(Vo,arguments);return function(){return Math.exp(n())}},bates:function(n){var t=Vo.random.irwinHall(n);return function(){return t()/n}},irwinHall:function(n){return function(){for(var t=0,e=0;n>e;e++)t+=Math.random();return t}}},Vo.scale={};var sl={floor:wt,ceil:wt};Vo.scale.linear=function(){return ji([0,1],[0,1],gu,!1)};var fl={s:1,g:1,p:1,r:1,e:1};Vo.scale.log=function(){return Xi(Vo.scale.linear().domain([0,1]),10,!0,[1,10])};var hl=Vo.format(".0e"),gl={floor:function(n){return-Math.ceil(-n)},ceil:function(n){return-Math.floor(-n)}};Vo.scale.pow=function(){return $i(Vo.scale.linear(),1,[0,1])},Vo.scale.sqrt=function(){return Vo.scale.pow().exponent(.5)},Vo.scale.ordinal=function(){return Wi([],{t:"range",a:[[]]})},Vo.scale.category10=function(){return Vo.scale.ordinal().range(pl)},Vo.scale.category20=function(){return Vo.scale.ordinal().range(vl)},Vo.scale.category20b=function(){return Vo.scale.ordinal().range(dl)},Vo.scale.category20c=function(){return Vo.scale.ordinal().range(ml)};var pl=[2062260,16744206,2924588,14034728,9725885,9197131,14907330,8355711,12369186,1556175].map(vt),vl=[2062260,11454440,16744206,16759672,2924588,10018698,14034728,16750742,9725885,12955861,9197131,12885140,14907330,16234194,8355711,13092807,12369186,14408589,1556175,10410725].map(vt),dl=[3750777,5395619,7040719,10264286,6519097,9216594,11915115,13556636,9202993,12426809,15186514,15190932,8666169,11356490,14049643,15177372,8077683,10834324,13528509,14589654].map(vt),ml=[3244733,7057110,10406625,13032431,15095053,16616764,16625259,16634018,3253076,7652470,10607003,13101504,7695281,10394312,12369372,14342891,6513507,9868950,12434877,14277081].map(vt);Vo.scale.quantile=function(){return Ji([],[])},Vo.scale.quantize=function(){return Gi(0,1,[0,1])},Vo.scale.threshold=function(){return Ki([.5],[0,1])},Vo.scale.identity=function(){return Qi([0,1])},Vo.svg={},Vo.svg.arc=function(){function n(){var n=t.apply(this,arguments),i=e.apply(this,arguments),o=r.apply(this,arguments)+yl,a=u.apply(this,arguments)+yl,c=(o>a&&(c=o,o=a,a=c),a-o),l=wa>c?"0":"1",s=Math.cos(o),f=Math.sin(o),h=Math.cos(a),g=Math.sin(a); -return c>=xl?n?"M0,"+i+"A"+i+","+i+" 0 1,1 0,"+-i+"A"+i+","+i+" 0 1,1 0,"+i+"M0,"+n+"A"+n+","+n+" 0 1,0 0,"+-n+"A"+n+","+n+" 0 1,0 0,"+n+"Z":"M0,"+i+"A"+i+","+i+" 0 1,1 0,"+-i+"A"+i+","+i+" 0 1,1 0,"+i+"Z":n?"M"+i*s+","+i*f+"A"+i+","+i+" 0 "+l+",1 "+i*h+","+i*g+"L"+n*h+","+n*g+"A"+n+","+n+" 0 "+l+",0 "+n*s+","+n*f+"Z":"M"+i*s+","+i*f+"A"+i+","+i+" 0 "+l+",1 "+i*h+","+i*g+"L0,0"+"Z"}var t=no,e=to,r=eo,u=ro;return n.innerRadius=function(e){return arguments.length?(t=bt(e),n):t},n.outerRadius=function(t){return arguments.length?(e=bt(t),n):e},n.startAngle=function(t){return arguments.length?(r=bt(t),n):r},n.endAngle=function(t){return arguments.length?(u=bt(t),n):u},n.centroid=function(){var n=(t.apply(this,arguments)+e.apply(this,arguments))/2,i=(r.apply(this,arguments)+u.apply(this,arguments))/2+yl;return[Math.cos(i)*n,Math.sin(i)*n]},n};var yl=-ka,xl=Sa-Ea;Vo.svg.line=function(){return uo(wt)};var Ml=Vo.map({linear:io,"linear-closed":oo,step:ao,"step-before":co,"step-after":lo,basis:vo,"basis-open":mo,"basis-closed":yo,bundle:xo,cardinal:ho,"cardinal-open":so,"cardinal-closed":fo,monotone:ko});Ml.forEach(function(n,t){t.key=n,t.closed=/-closed$/.test(n)});var _l=[0,2/3,1/3,0],bl=[0,1/3,2/3,0],wl=[0,1/6,2/3,1/6];Vo.svg.line.radial=function(){var n=uo(Eo);return n.radius=n.x,delete n.x,n.angle=n.y,delete n.y,n},co.reverse=lo,lo.reverse=co,Vo.svg.area=function(){return Ao(wt)},Vo.svg.area.radial=function(){var n=Ao(Eo);return n.radius=n.x,delete n.x,n.innerRadius=n.x0,delete n.x0,n.outerRadius=n.x1,delete n.x1,n.angle=n.y,delete n.y,n.startAngle=n.y0,delete n.y0,n.endAngle=n.y1,delete n.y1,n},Vo.svg.chord=function(){function n(n,a){var c=t(this,i,n,a),l=t(this,o,n,a);return"M"+c.p0+r(c.r,c.p1,c.a1-c.a0)+(e(c,l)?u(c.r,c.p1,c.r,c.p0):u(c.r,c.p1,l.r,l.p0)+r(l.r,l.p1,l.a1-l.a0)+u(l.r,l.p1,c.r,c.p0))+"Z"}function t(n,t,e,r){var u=t.call(n,e,r),i=a.call(n,u,r),o=c.call(n,u,r)+yl,s=l.call(n,u,r)+yl;return{r:i,a0:o,a1:s,p0:[i*Math.cos(o),i*Math.sin(o)],p1:[i*Math.cos(s),i*Math.sin(s)]}}function e(n,t){return n.a0==t.a0&&n.a1==t.a1}function r(n,t,e){return"A"+n+","+n+" 0 "+ +(e>wa)+",1 "+t}function u(n,t,e,r){return"Q 0,0 "+r}var i=pr,o=vr,a=Co,c=eo,l=ro;return n.radius=function(t){return arguments.length?(a=bt(t),n):a},n.source=function(t){return arguments.length?(i=bt(t),n):i},n.target=function(t){return arguments.length?(o=bt(t),n):o},n.startAngle=function(t){return arguments.length?(c=bt(t),n):c},n.endAngle=function(t){return arguments.length?(l=bt(t),n):l},n},Vo.svg.diagonal=function(){function n(n,u){var i=t.call(this,n,u),o=e.call(this,n,u),a=(i.y+o.y)/2,c=[i,{x:i.x,y:a},{x:o.x,y:a},o];return c=c.map(r),"M"+c[0]+"C"+c[1]+" "+c[2]+" "+c[3]}var t=pr,e=vr,r=No;return n.source=function(e){return arguments.length?(t=bt(e),n):t},n.target=function(t){return arguments.length?(e=bt(t),n):e},n.projection=function(t){return arguments.length?(r=t,n):r},n},Vo.svg.diagonal.radial=function(){var n=Vo.svg.diagonal(),t=No,e=n.projection;return n.projection=function(n){return arguments.length?e(zo(t=n)):t},n},Vo.svg.symbol=function(){function n(n,r){return(Sl.get(t.call(this,n,r))||qo)(e.call(this,n,r))}var t=To,e=Lo;return n.type=function(e){return arguments.length?(t=bt(e),n):t},n.size=function(t){return arguments.length?(e=bt(t),n):e},n};var Sl=Vo.map({circle:qo,cross:function(n){var t=Math.sqrt(n/5)/2;return"M"+-3*t+","+-t+"H"+-t+"V"+-3*t+"H"+t+"V"+-t+"H"+3*t+"V"+t+"H"+t+"V"+3*t+"H"+-t+"V"+t+"H"+-3*t+"Z"},diamond:function(n){var t=Math.sqrt(n/(2*Cl)),e=t*Cl;return"M0,"+-t+"L"+e+",0"+" 0,"+t+" "+-e+",0"+"Z"},square:function(n){var t=Math.sqrt(n)/2;return"M"+-t+","+-t+"L"+t+","+-t+" "+t+","+t+" "+-t+","+t+"Z"},"triangle-down":function(n){var t=Math.sqrt(n/Al),e=t*Al/2;return"M0,"+e+"L"+t+","+-e+" "+-t+","+-e+"Z"},"triangle-up":function(n){var t=Math.sqrt(n/Al),e=t*Al/2;return"M0,"+-e+"L"+t+","+e+" "+-t+","+e+"Z"}});Vo.svg.symbolTypes=Sl.keys();var kl,El,Al=Math.sqrt(3),Cl=Math.tan(30*Ca),Nl=[],zl=0;Nl.call=va.call,Nl.empty=va.empty,Nl.node=va.node,Nl.size=va.size,Vo.transition=function(n){return arguments.length?kl?n.transition():n:ya.transition()},Vo.transition.prototype=Nl,Nl.select=function(n){var t,e,r,u=this.id,i=[];n=b(n);for(var o=-1,a=this.length;++oi;i++){u.push(t=[]);for(var e=this[i],a=0,c=e.length;c>a;a++)(r=e[a])&&n.call(r,r.__data__,a,i)&&t.push(r)}return Ro(u,this.id)},Nl.tween=function(n,t){var e=this.id;return arguments.length<2?this.node().__transition__[e].tween.get(n):P(this,null==t?function(t){t.__transition__[e].tween.remove(n)}:function(r){r.__transition__[e].tween.set(n,t)})},Nl.attr=function(n,t){function e(){this.removeAttribute(a)}function r(){this.removeAttributeNS(a.space,a.local)}function u(n){return null==n?e:(n+="",function(){var t,e=this.getAttribute(a);return e!==n&&(t=o(e,n),function(n){this.setAttribute(a,t(n))})})}function i(n){return null==n?r:(n+="",function(){var t,e=this.getAttributeNS(a.space,a.local);return e!==n&&(t=o(e,n),function(n){this.setAttributeNS(a.space,a.local,t(n))})})}if(arguments.length<2){for(t in n)this.attr(t,n[t]);return this}var o="transform"==n?Pu:gu,a=Vo.ns.qualify(n);return Do(this,"attr."+n,t,a.local?i:u)},Nl.attrTween=function(n,t){function e(n,e){var r=t.call(this,n,e,this.getAttribute(u));return r&&function(n){this.setAttribute(u,r(n))}}function r(n,e){var r=t.call(this,n,e,this.getAttributeNS(u.space,u.local));return r&&function(n){this.setAttributeNS(u.space,u.local,r(n))}}var u=Vo.ns.qualify(n);return this.tween("attr."+n,u.local?r:e)},Nl.style=function(n,t,e){function r(){this.style.removeProperty(n)}function u(t){return null==t?r:(t+="",function(){var r,u=Jo.getComputedStyle(this,null).getPropertyValue(n);return u!==t&&(r=gu(u,t),function(t){this.style.setProperty(n,r(t),e)})})}var i=arguments.length;if(3>i){if("string"!=typeof n){2>i&&(t="");for(e in n)this.style(e,n[e],t);return this}e=""}return Do(this,"style."+n,t,u)},Nl.styleTween=function(n,t,e){function r(r,u){var i=t.call(this,r,u,Jo.getComputedStyle(this,null).getPropertyValue(n));return i&&function(t){this.style.setProperty(n,i(t),e)}}return arguments.length<3&&(e=""),this.tween("style."+n,r)},Nl.text=function(n){return Do(this,"text",n,Po)},Nl.remove=function(){return this.each("end.transition",function(){var n;this.__transition__.count<2&&(n=this.parentNode)&&n.removeChild(this)})},Nl.ease=function(n){var t=this.id;return arguments.length<1?this.node().__transition__[t].ease:("function"!=typeof n&&(n=Vo.ease.apply(Vo,arguments)),P(this,function(e){e.__transition__[t].ease=n}))},Nl.delay=function(n){var t=this.id;return arguments.length<1?this.node().__transition__[t].delay:P(this,"function"==typeof n?function(e,r,u){e.__transition__[t].delay=+n.call(e,e.__data__,r,u)}:(n=+n,function(e){e.__transition__[t].delay=n}))},Nl.duration=function(n){var t=this.id;return arguments.length<1?this.node().__transition__[t].duration:P(this,"function"==typeof n?function(e,r,u){e.__transition__[t].duration=Math.max(1,n.call(e,e.__data__,r,u))}:(n=Math.max(1,n),function(e){e.__transition__[t].duration=n}))},Nl.each=function(n,t){var e=this.id;if(arguments.length<2){var r=El,u=kl;kl=e,P(this,function(t,r,u){El=t.__transition__[e],n.call(t,t.__data__,r,u)}),El=r,kl=u}else P(this,function(r){var u=r.__transition__[e];(u.event||(u.event=Vo.dispatch("start","end"))).on(n,t)});return this},Nl.transition=function(){for(var n,t,e,r,u=this.id,i=++zl,o=[],a=0,c=this.length;c>a;a++){o.push(n=[]);for(var t=this[a],l=0,s=t.length;s>l;l++)(e=t[l])&&(r=Object.create(e.__transition__[u]),r.delay+=r.duration,Uo(e,l,i,r)),n.push(e)}return Ro(o,i)},Vo.svg.axis=function(){function n(n){n.each(function(){var n,l=Vo.select(this),s=this.__chart__||e,f=this.__chart__=e.copy(),h=null==c?f.ticks?f.ticks.apply(f,a):f.domain():c,g=null==t?f.tickFormat?f.tickFormat.apply(f,a):wt:t,p=l.selectAll(".tick").data(h,f),v=p.enter().insert("g",".domain").attr("class","tick").style("opacity",Ea),d=Vo.transition(p.exit()).style("opacity",Ea).remove(),m=Vo.transition(p.order()).style("opacity",1),y=qi(f),x=l.selectAll(".domain").data([0]),M=(x.enter().append("path").attr("class","domain"),Vo.transition(x));v.append("line"),v.append("text");var _=v.select("line"),b=m.select("line"),w=p.select("text").text(g),S=v.select("text"),k=m.select("text");switch(r){case"bottom":n=jo,_.attr("y2",u),S.attr("y",Math.max(u,0)+o),b.attr("x2",0).attr("y2",u),k.attr("x",0).attr("y",Math.max(u,0)+o),w.attr("dy",".71em").style("text-anchor","middle"),M.attr("d","M"+y[0]+","+i+"V0H"+y[1]+"V"+i);break;case"top":n=jo,_.attr("y2",-u),S.attr("y",-(Math.max(u,0)+o)),b.attr("x2",0).attr("y2",-u),k.attr("x",0).attr("y",-(Math.max(u,0)+o)),w.attr("dy","0em").style("text-anchor","middle"),M.attr("d","M"+y[0]+","+-i+"V0H"+y[1]+"V"+-i);break;case"left":n=Ho,_.attr("x2",-u),S.attr("x",-(Math.max(u,0)+o)),b.attr("x2",-u).attr("y2",0),k.attr("x",-(Math.max(u,0)+o)).attr("y",0),w.attr("dy",".32em").style("text-anchor","end"),M.attr("d","M"+-i+","+y[0]+"H0V"+y[1]+"H"+-i);break;case"right":n=Ho,_.attr("x2",u),S.attr("x",Math.max(u,0)+o),b.attr("x2",u).attr("y2",0),k.attr("x",Math.max(u,0)+o).attr("y",0),w.attr("dy",".32em").style("text-anchor","start"),M.attr("d","M"+i+","+y[0]+"H0V"+y[1]+"H"+i)}if(f.rangeBand){var E=f,A=E.rangeBand()/2;s=f=function(n){return E(n)+A}}else s.rangeBand?s=f:d.call(n,f);v.call(n,s),m.call(n,f)})}var t,e=Vo.scale.linear(),r=Ll,u=6,i=6,o=3,a=[10],c=null;return n.scale=function(t){return arguments.length?(e=t,n):e},n.orient=function(t){return arguments.length?(r=t in Tl?t+"":Ll,n):r},n.ticks=function(){return arguments.length?(a=arguments,n):a},n.tickValues=function(t){return arguments.length?(c=t,n):c},n.tickFormat=function(e){return arguments.length?(t=e,n):t},n.tickSize=function(t){var e=arguments.length;return e?(u=+t,i=+arguments[e-1],n):u},n.innerTickSize=function(t){return arguments.length?(u=+t,n):u},n.outerTickSize=function(t){return arguments.length?(i=+t,n):i},n.tickPadding=function(t){return arguments.length?(o=+t,n):o},n.tickSubdivide=function(){return arguments.length&&n},n};var Ll="bottom",Tl={top:1,right:1,bottom:1,left:1};Vo.svg.brush=function(){function n(i){i.each(function(){var i=Vo.select(this).style("pointer-events","all").style("-webkit-tap-highlight-color","rgba(0,0,0,0)").on("mousedown.brush",u).on("touchstart.brush",u),o=i.selectAll(".background").data([0]);o.enter().append("rect").attr("class","background").style("visibility","hidden").style("cursor","crosshair"),i.selectAll(".extent").data([0]).enter().append("rect").attr("class","extent").style("cursor","move");var a=i.selectAll(".resize").data(p,wt);a.exit().remove(),a.enter().append("g").attr("class",function(n){return"resize "+n}).style("cursor",function(n){return ql[n]}).append("rect").attr("x",function(n){return/[ew]$/.test(n)?-3:null}).attr("y",function(n){return/^[ns]/.test(n)?-3:null}).attr("width",6).attr("height",6).style("visibility","hidden"),a.style("display",n.empty()?"none":null);var s,f=Vo.transition(i),h=Vo.transition(o);c&&(s=qi(c),h.attr("x",s[0]).attr("width",s[1]-s[0]),e(f)),l&&(s=qi(l),h.attr("y",s[0]).attr("height",s[1]-s[0]),r(f)),t(f)})}function t(n){n.selectAll(".resize").attr("transform",function(n){return"translate("+s[+/e$/.test(n)]+","+f[+/^s/.test(n)]+")"})}function e(n){n.select(".extent").attr("x",s[0]),n.selectAll(".extent,.n>rect,.s>rect").attr("width",s[1]-s[0])}function r(n){n.select(".extent").attr("y",f[0]),n.selectAll(".extent,.e>rect,.w>rect").attr("height",f[1]-f[0])}function u(){function u(){32==Vo.event.keyCode&&(C||(x=null,z[0]-=s[1],z[1]-=f[1],C=2),y())}function p(){32==Vo.event.keyCode&&2==C&&(z[0]+=s[1],z[1]+=f[1],C=0,y())}function v(){var n=Vo.mouse(_),u=!1;M&&(n[0]+=M[0],n[1]+=M[1]),C||(Vo.event.altKey?(x||(x=[(s[0]+s[1])/2,(f[0]+f[1])/2]),z[0]=s[+(n[0]p?(u=r,r=p):u=p),v[0]!=r||v[1]!=u?(e?o=null:i=null,v[0]=r,v[1]=u,!0):void 0}function m(){v(),S.style("pointer-events","all").selectAll(".resize").style("display",n.empty()?"none":null),Vo.select("body").style("cursor",null),L.on("mousemove.brush",null).on("mouseup.brush",null).on("touchmove.brush",null).on("touchend.brush",null).on("keydown.brush",null).on("keyup.brush",null),N(),w({type:"brushend"})}var x,M,_=this,b=Vo.select(Vo.event.target),w=a.of(_,arguments),S=Vo.select(_),k=b.datum(),E=!/^(n|s)$/.test(k)&&c,A=!/^(e|w)$/.test(k)&&l,C=b.classed("extent"),N=I(),z=Vo.mouse(_),L=Vo.select(Jo).on("keydown.brush",u).on("keyup.brush",p);if(Vo.event.changedTouches?L.on("touchmove.brush",v).on("touchend.brush",m):L.on("mousemove.brush",v).on("mouseup.brush",m),S.interrupt().selectAll("*").interrupt(),C)z[0]=s[0]-z[0],z[1]=f[0]-z[1];else if(k){var T=+/w$/.test(k),q=+/^n/.test(k);M=[s[1-T]-z[0],f[1-q]-z[1]],z[0]=s[T],z[1]=f[q]}else Vo.event.altKey&&(x=z.slice());S.style("pointer-events","none").selectAll(".resize").style("display",null),Vo.select("body").style("cursor",b.style("cursor")),w({type:"brushstart"}),v()}var i,o,a=M(n,"brushstart","brush","brushend"),c=null,l=null,s=[0,0],f=[0,0],h=!0,g=!0,p=Rl[0];return n.event=function(n){n.each(function(){var n=a.of(this,arguments),t={x:s,y:f,i:i,j:o},e=this.__chart__||t;this.__chart__=t,kl?Vo.select(this).transition().each("start.brush",function(){i=e.i,o=e.j,s=e.x,f=e.y,n({type:"brushstart"})}).tween("brush:brush",function(){var e=pu(s,t.x),r=pu(f,t.y);return i=o=null,function(u){s=t.x=e(u),f=t.y=r(u),n({type:"brush",mode:"resize"})}}).each("end.brush",function(){i=t.i,o=t.j,n({type:"brush",mode:"resize"}),n({type:"brushend"})}):(n({type:"brushstart"}),n({type:"brush",mode:"resize"}),n({type:"brushend"}))})},n.x=function(t){return arguments.length?(c=t,p=Rl[!c<<1|!l],n):c},n.y=function(t){return arguments.length?(l=t,p=Rl[!c<<1|!l],n):l},n.clamp=function(t){return arguments.length?(c&&l?(h=!!t[0],g=!!t[1]):c?h=!!t:l&&(g=!!t),n):c&&l?[h,g]:c?h:l?g:null},n.extent=function(t){var e,r,u,a,h;return arguments.length?(c&&(e=t[0],r=t[1],l&&(e=e[0],r=r[0]),i=[e,r],c.invert&&(e=c(e),r=c(r)),e>r&&(h=e,e=r,r=h),(e!=s[0]||r!=s[1])&&(s=[e,r])),l&&(u=t[0],a=t[1],c&&(u=u[1],a=a[1]),o=[u,a],l.invert&&(u=l(u),a=l(a)),u>a&&(h=u,u=a,a=h),(u!=f[0]||a!=f[1])&&(f=[u,a])),n):(c&&(i?(e=i[0],r=i[1]):(e=s[0],r=s[1],c.invert&&(e=c.invert(e),r=c.invert(r)),e>r&&(h=e,e=r,r=h))),l&&(o?(u=o[0],a=o[1]):(u=f[0],a=f[1],l.invert&&(u=l.invert(u),a=l.invert(a)),u>a&&(h=u,u=a,a=h))),c&&l?[[e,u],[r,a]]:c?[e,r]:l&&[u,a])},n.clear=function(){return n.empty()||(s=[0,0],f=[0,0],i=o=null),n},n.empty=function(){return!!c&&s[0]==s[1]||!!l&&f[0]==f[1]},Vo.rebind(n,a,"on")};var ql={n:"ns-resize",e:"ew-resize",s:"ns-resize",w:"ew-resize",nw:"nwse-resize",ne:"nesw-resize",se:"nwse-resize",sw:"nesw-resize"},Rl=[["n","e","s","w","nw","ne","se","sw"],["e","w"],["n","s"],[]],Dl=nc.format=oc.timeFormat,Pl=Dl.utc,Ul=Pl("%Y-%m-%dT%H:%M:%S.%LZ");Dl.iso=Date.prototype.toISOString&&+new Date("2000-01-01T00:00:00.000Z")?Fo:Ul,Fo.parse=function(n){var t=new Date(n);return isNaN(t)?null:t},Fo.toString=Ul.toString,nc.second=Pt(function(n){return new tc(1e3*Math.floor(n/1e3))},function(n,t){n.setTime(n.getTime()+1e3*Math.floor(t))},function(n){return n.getSeconds()}),nc.seconds=nc.second.range,nc.seconds.utc=nc.second.utc.range,nc.minute=Pt(function(n){return new tc(6e4*Math.floor(n/6e4))},function(n,t){n.setTime(n.getTime()+6e4*Math.floor(t))},function(n){return n.getMinutes()}),nc.minutes=nc.minute.range,nc.minutes.utc=nc.minute.utc.range,nc.hour=Pt(function(n){var t=n.getTimezoneOffset()/60;return new tc(36e5*(Math.floor(n/36e5-t)+t))},function(n,t){n.setTime(n.getTime()+36e5*Math.floor(t))},function(n){return n.getHours()}),nc.hours=nc.hour.range,nc.hours.utc=nc.hour.utc.range,nc.month=Pt(function(n){return n=nc.day(n),n.setDate(1),n},function(n,t){n.setMonth(n.getMonth()+t)},function(n){return n.getMonth()}),nc.months=nc.month.range,nc.months.utc=nc.month.utc.range;var jl=[1e3,5e3,15e3,3e4,6e4,3e5,9e5,18e5,36e5,108e5,216e5,432e5,864e5,1728e5,6048e5,2592e6,7776e6,31536e6],Hl=[[nc.second,1],[nc.second,5],[nc.second,15],[nc.second,30],[nc.minute,1],[nc.minute,5],[nc.minute,15],[nc.minute,30],[nc.hour,1],[nc.hour,3],[nc.hour,6],[nc.hour,12],[nc.day,1],[nc.day,2],[nc.week,1],[nc.month,1],[nc.month,3],[nc.year,1]],Fl=Dl.multi([[".%L",function(n){return n.getMilliseconds()}],[":%S",function(n){return n.getSeconds()}],["%I:%M",function(n){return n.getMinutes()}],["%I %p",function(n){return n.getHours()}],["%a %d",function(n){return n.getDay()&&1!=n.getDate()}],["%b %d",function(n){return 1!=n.getDate()}],["%B",function(n){return n.getMonth()}],["%Y",Se]]),Ol={range:function(n,t,e){return Vo.range(Math.ceil(n/e)*e,+t,e).map(Yo)},floor:wt,ceil:wt};Hl.year=nc.year,nc.scale=function(){return Oo(Vo.scale.linear(),Hl,Fl)};var Yl=Hl.map(function(n){return[n[0].utc,n[1]]}),Il=Pl.multi([[".%L",function(n){return n.getUTCMilliseconds()}],[":%S",function(n){return n.getUTCSeconds()}],["%I:%M",function(n){return n.getUTCMinutes()}],["%I %p",function(n){return n.getUTCHours()}],["%a %d",function(n){return n.getUTCDay()&&1!=n.getUTCDate()}],["%b %d",function(n){return 1!=n.getUTCDate()}],["%B",function(n){return n.getUTCMonth()}],["%Y",Se]]);Yl.year=nc.year.utc,nc.scale.utc=function(){return Oo(Vo.scale.linear(),Yl,Il)},Vo.text=St(function(n){return n.responseText}),Vo.json=function(n,t){return kt(n,"application/json",Io,t)},Vo.html=function(n,t){return kt(n,"text/html",Zo,t)},Vo.xml=St(function(n){return n.responseXML}),"function"==typeof define&&define.amd?define(Vo):"object"==typeof module&&module.exports&&(module.exports=Vo),this.d3=Vo}(); \ No newline at end of file diff --git a/BuildTools/CommonDistFiles/web_plugins/geoda.js b/BuildTools/CommonDistFiles/web_plugins/geoda.js deleted file mode 100644 index d10fbc704..000000000 --- a/BuildTools/CommonDistFiles/web_plugins/geoda.js +++ /dev/null @@ -1,338 +0,0 @@ -///////////////////////////////////////////////////////////// -// Note: the following code is documented with JSDoc tags. // -///////////////////////////////////////////////////////////// - -/** gda is the namespace for the GeoDa/Javascript API. -* For example, to access the curr_sel object, type gda.curr_sel -* @namespace -*/ -var gda = gda || {}; - -/** Current selection hashtable. Ex, if observation 3 and 30 - * are currently selected, gda.curr_sel should be: - * { 3: true, 30: true }. - * This allows us to quickly detect membership in curr_sel. - * Ex, to test if observation 4 is selected, can write: - * gda.curr_sel[4] !== undefined; This call is very fast - * to execute. Much faster than (4 in gda.curr_sel) or - * gda.curr_sel.hasOwnProperty(4); Emperical testing has - * shown these last two lookups to be 50x slower. - * @member {Object} - * @type {Object.} - */ -gda.curr_sel = {}; - -/////////////////////////////////// -// BEGIN: GeoDa JS API Section // -/////////////////////////////////// - -// Will store mapping from callback ids to callback functions -gda.callback_map = {}; - -/** - * Get a unique callback id. - * @memberof gda - * @function getCallbackId - * @returns {string} Unique callback identifier string. - */ -(function () { - var cb_id = 100; // capture as private variable. - gda.getCallbackId = function () { return "resp_cb_id_" + cb_id++; }; -} ()); - -/** -* High level definition of a gda Request JSON object -* @typedef {Object} RequestObject -* @property {string} interface - One of "project", "table" -* @property {string} operation - Ex promptVarSettings -*/ - -/** -* @typedef {Object} VariableSettingsRequestObject -* @property {string} interface - Must be set to project -* @property {string} operation - Must be "promptVarSettings" -* @property {string} arity - One of uni/bi/tri/quadvariate -* @property {boolean} [show_weights=false] - Get a weights matrix -* @property {string} [var1_title="First Variable (X)"] - first variable title -* @property {string} [var2_title="Second Variable (Y)"] - second variable title -* @property {string} [var3_title="Third Variable (Z)"] - third variable title -* @property {string} [var4_title="Fourth Variable"] - fourth variable title -*/ - -/** -* This callback type is called 'requestCallback' -* @callback requestCallback -* @param {Object} response_obj -*/ - -/** -* reqs: an array of request objects -* @param {RequestObject[]} reqs -* @param {requestCallback} callback -*/ -gda.makeRequests = function (reqs, callback) { - var a = {}; - a.action = "request"; - a.callback_id = gda.getCallbackId(); - a.requests = reqs; - gda.callback_map[a.callback_id] = callback; - document.title = JSON.stringify(a); -}; - -/** responses_obj */ -gda.response = function (responses_obj) { - // find callback in callback map. - // if callback not found, then assume request was canceled. - // Otherwise, execute function associated with callback_id - - var cb_id = responses_obj.callback_id; - if (!cb_id) return; - if (!gda.callback_map[cb_id]) return; - gda.callback_map[cb_id](responses_obj.responses); - delete gda.callback_map[cb_id]; -}; - -/** - o is a JSON object with the following format: - {"observable": "HighlightState", - "event": "delta", - "newly_highlighted": [3,2,32,4], - "newly_unhighlighted": [23, 6, 7] - } - */ -gda.update = function (o) { - gda.logMsg("In gda.update"); - - //gda.logMsg(JSON.stringify(o), "update_para"); - - if (o.observable === "HighlightState" && gda.updateHS) { - gda.updateHS(o); - } - if (o.observable === "TimeState" && gda.updateTmS) { - gda.updateTmS(o); - } - if (o.observable === "WeightsManState" && gda.updateWS) { - gda.updateWS(o); - } -}; - -/** This is an example function that needs to be - defined by the programmer */ -gda.readyToInit = function () { - // To immediately closes the web view: - // document.title = JSON.stringify({action: "close"}); - - /* - var requests = []; - // Variable Settings Request Object - var vs_o = { - interface: "project", - operation: "promptVarSettings", - arity: "bivariate", - show_weights: false, - title: "Custom D3/JS Scatterplot Variables", - var1_title: "x-axis", - var2_title: "y-axis" - }; - requests.push(vs_o); - - gda.makeRequests(requests, - function (resp_array) { - // resp_array is the response array. - // We only expect one response object - // in this case. - var o = resp_array[0]; - var initObj = { - var1_title: o.var1.name, - var1_data: o.var1.data[0], - var1_title: o.var2.name, - var2_data: o.var2.data[0], - selected: o.selected - }; - gda.initFromDataset(initObj); - gda.logMsg("received VS response", "vs_para") }); - */ -} - -/////////////////////////////////// -// END: GeoDa JS API Section // -/////////////////////////////////// - - -// Example utility function to get the current window size on resize. -// To have this function called when the browser window is resize, -// can write or -// document.body.onresize = gda.updateWindow; -gda.updateWindow = function () { - var w = window; - var d = document; - var e = d.documentElement; - var g = d.getElementsByTagName('body')[0]; - var x = w.innerWidth || e.clientWidth || g.clientWidth; - var y = w.innerHeight || e.clientHeight || g.clientHeight; - gda.logMsg("window size: (" + x + ", " + y + ")", "win_sz_para"); - //var svg = d3.select("body").select("svg"); - //svg.attr("width", x).attr("height", y); -} - -gda.getWindowSize = function () { - var w = window; - var d = document; - var e = d.documentElement; - var g = d.getElementsByTagName('body')[0]; - var x = w.innerWidth || e.clientWidth || g.clientWidth; - var y = w.innerHeight || e.clientHeight || g.clientHeight; - //gda.logMsg("window size: (" + x + ", " + y + ")", "win_sz_para"); - return {width: x, height: y}; -} - -// Utility function to add a log -// message to . If no id -// given, then default "log_para" -// is used. Otherwise will replace -// paragraph with id if it exists. -gda.logMsg = function (msg, id) { - if (!id) id = "log_para"; - var p = document.getElementById(id); - if (!p) { - p = document.createElement("p"); - p.id = id; - document.body.appendChild(p); - } - p.innerHTML = msg; -} - -// Utility function to add a log -// message to . If no id -// given, then default "log_para" -// is used. Similar to gda.logMsg, -// but appends to to existing -// paragraph rather than overwriting. -gda.appendMsg = function (msg, id) { - if (!id) id = "log_para"; - var p = document.getElementById(id); - if (!p) { - p = document.createElement("p"); - p.id = id; - document.body.appendChild(p); - } - p.innerHTML += "
    " + msg; -} - - -/** This is an example that needs to be redefined to -do actual highlight/unhighlights. */ -gda.updateHS = function (o) { - gda.logMsg("In gda.updateHS"); - - if (o.event === "unhighlight_all") { - - } else if (o.event === "invert") { - - } else if (o.event === "delta") { - - } -} - -/** Example function that needs to be redefined. -@abstract -*/ -gda.updateTmS = function (o) { - gda.logMsg("In gda.updateTmS"); - gda.logMsg("time id: " + o.curr_time + ", time name: " + o.curr_time_str, "time_para"); -}; - -/** Example function that needs to be redefined */ -gda.updateWS = function (o) { - gda.logMsg("In gda.updateWS"); - gda.logMsg("weights event: " + o.event); -}; - -// Merges object A into object B -gda.merge_obj_into_obj = function (A, B) { - for (var key in A) { - B[key] = A[key]; - } -}; - -// Merges array A into object B -gda.merge_array_into_obj = function (A, B) { - for (var i=0, sz=A.length; i - - - - D3 Demo: Scatterplot - - - - - - - - - - - - - diff --git a/BuildTools/CommonDistFiles/web_plugins/loess.js b/BuildTools/CommonDistFiles/web_plugins/loess.js deleted file mode 100644 index 5d93c61e8..000000000 --- a/BuildTools/CommonDistFiles/web_plugins/loess.js +++ /dev/null @@ -1,205 +0,0 @@ -// Based on org.apache.commons.math.analysis.interpolation.LoessInterpolator -// from http://commons.apache.org/math/ - -function science_stats_loessFiniteReal(values) { - var n = values.length, i = -1; - - while (++i < n) if (!isFinite(values[i])) return false; - - return true; -} - -function science_stats_loessStrictlyIncreasing(xval) { - var n = xval.length, - i = 0; - - while (++i < n) if (xval[i - 1] >= xval[i]) return false; - - return true; -} - -// Compute the tricube weight function. -// http://en.wikipedia.org/wiki/Local_regression#Weight_function -function science_stats_loessTricube(x) { - return (x = 1 - x * x * x) * x * x; -} - -// Given an index interval into xval that embraces a certain number of -// points closest to xval[i-1], update the interval so that it embraces -// the same number of points closest to xval[i], ignoring zero weights. -function science_stats_loessUpdateBandwidthInterval( -xval, weights, i, bandwidthInterval) { - - var left = bandwidthInterval[0], - right = bandwidthInterval[1]; - - // The right edge should be adjusted if the next point to the right - // is closer to xval[i] than the leftmost point of the current interval - var nextRight = science_stats_loessNextNonzero(weights, right); - if ((nextRight < xval.length) && (xval[nextRight] - xval[i]) < (xval[i] - xval[left])) { - var nextLeft = science_stats_loessNextNonzero(weights, left); - bandwidthInterval[0] = nextLeft; - bandwidthInterval[1] = nextRight; - } -} - -function science_stats_loessNextNonzero(weights, i) { - var j = i + 1; - while (j < weights.length && weights[j] === 0) j++; - return j; -} - - -science.stats.loess = function() { - var bandwidth = .3, - robustnessIters = 2, - accuracy = 1e-12; - - function smooth(xval, yval, weights) { - var n = xval.length; - var i; - - if (n !== yval.length) throw {error: "Mismatched array lengths"}; - if (n == 0) throw {error: "At least one point required."}; - - if (arguments.length < 3) { - weights = []; - i = -1; while (++i < n) weights[i] = 1; - } - - science_stats_loessFiniteReal(xval); - science_stats_loessFiniteReal(yval); - science_stats_loessFiniteReal(weights); - science_stats_loessStrictlyIncreasing(xval); - - if (n == 1) return [yval[0]]; - if (n == 2) return [yval[0], yval[1]]; - - var bandwidthInPoints = Math.floor(bandwidth * n); - - if (bandwidthInPoints < 2) throw {error: "Bandwidth too small."}; - - var res = [], - residuals = [], - robustnessWeights = []; - - // Do an initial fit and 'robustnessIters' robustness iterations. - // This is equivalent to doing 'robustnessIters+1' robustness iterations - // starting with all robustness weights set to 1. - i = -1; while (++i < n) { - res[i] = 0; - residuals[i] = 0; - robustnessWeights[i] = 1; - } - - var iter = -1; - while (++iter <= robustnessIters) { - var bandwidthInterval = [0, bandwidthInPoints - 1]; - // At each x, compute a local weighted linear regression - var x; - i = -1; - while (++i < n) { - x = xval[i]; - - // Find out the interval of source points on which - // a regression is to be made. - if (i > 0) { - science_stats_loessUpdateBandwidthInterval(xval, weights, i, bandwidthInterval); - } - - var ileft = bandwidthInterval[0], - iright = bandwidthInterval[1]; - - // Compute the point of the bandwidth interval that is - // farthest from x - var edge = (xval[i] - xval[ileft]) > (xval[iright] - xval[i]) ? ileft : iright; - - // Compute a least-squares linear fit weighted by - // the product of robustness weights and the tricube - // weight function. - // See http://en.wikipedia.org/wiki/Linear_regression - // (section "Univariate linear case") - // and http://en.wikipedia.org/wiki/Weighted_least_squares - // (section "Weighted least squares") - var sumWeights = 0, - sumX = 0, - sumXSquared = 0, - sumY = 0, - sumXY = 0, - denom = Math.abs(1 / (xval[edge] - x)); - - for (var k = ileft; k <= iright; ++k) { - var xk = xval[k], - yk = yval[k], - dist = k < i ? x - xk : xk - x, - w = science_stats_loessTricube(dist * denom) * robustnessWeights[k] * weights[k], - xkw = xk * w; - sumWeights += w; - sumX += xkw; - sumXSquared += xk * xkw; - sumY += yk * w; - sumXY += yk * xkw; - } - - var meanX = sumX / sumWeights, - meanY = sumY / sumWeights, - meanXY = sumXY / sumWeights, - meanXSquared = sumXSquared / sumWeights; - - var beta = (Math.sqrt(Math.abs(meanXSquared - meanX * meanX)) < accuracy) - ? 0 : ((meanXY - meanX * meanY) / (meanXSquared - meanX * meanX)); - - var alpha = meanY - beta * meanX; - - res[i] = beta * x + alpha; - residuals[i] = Math.abs(yval[i] - res[i]); - } - - // No need to recompute the robustness weights at the last - // iteration, they won't be needed anymore - if (iter === robustnessIters) { - break; - } - - // Recompute the robustness weights. - - // Find the median residual. - var sortedResiduals = residuals.slice(); - sortedResiduals.sort(); - var medianResidual = sortedResiduals[Math.floor(n / 2)]; - - if (Math.abs(medianResidual) < accuracy) - break; - - var arg, - w; - i = -1; while (++i < n) { - arg = residuals[i] / (6 * medianResidual); - robustnessWeights[i] = (arg >= 1) ? 0 : ((w = 1 - arg * arg) * w); - } - } - - return res; - } - - smooth.bandwidth = function(x) { - if (!arguments.length) return x; - bandwidth = x; - return smooth; - }; - - smooth.robustnessIterations = function(x) { - if (!arguments.length) return x; - robustnessIters = x; - return smooth; - }; - - smooth.accuracy = function(x) { - if (!arguments.length) return x; - accuracy = x; - return smooth; - }; - - return smooth; -}; - diff --git a/BuildTools/CommonDistFiles/web_plugins/loess_curve.html b/BuildTools/CommonDistFiles/web_plugins/loess_curve.html deleted file mode 100644 index 854359f92..000000000 --- a/BuildTools/CommonDistFiles/web_plugins/loess_curve.html +++ /dev/null @@ -1,648 +0,0 @@ - - - - - D3 Demo: Scatterplot - - - - - - - - - - - - - - diff --git a/BuildTools/CommonDistFiles/web_plugins/samples.sqlite b/BuildTools/CommonDistFiles/web_plugins/samples.sqlite index d95805526..a2bbf2c6d 100644 Binary files a/BuildTools/CommonDistFiles/web_plugins/samples.sqlite and b/BuildTools/CommonDistFiles/web_plugins/samples.sqlite differ diff --git a/BuildTools/CommonDistFiles/web_plugins/scatter_mat.html b/BuildTools/CommonDistFiles/web_plugins/scatter_mat.html deleted file mode 100644 index 7ea041adb..000000000 --- a/BuildTools/CommonDistFiles/web_plugins/scatter_mat.html +++ /dev/null @@ -1,346 +0,0 @@ - - - - - D3 Demo: Scatterplot - - - - - - - - - -

    Scatter Plot Matrix

    - - - diff --git a/BuildTools/CommonDistFiles/web_plugins/scatterplot_example5.html b/BuildTools/CommonDistFiles/web_plugins/scatterplot_example5.html deleted file mode 100644 index 758378a30..000000000 --- a/BuildTools/CommonDistFiles/web_plugins/scatterplot_example5.html +++ /dev/null @@ -1,502 +0,0 @@ - - - - - D3 Demo: Axes - - - - - - - - -

    version 3.14

    - - - diff --git a/BuildTools/CommonDistFiles/web_plugins/scatterplot_example6.html b/BuildTools/CommonDistFiles/web_plugins/scatterplot_example6.html deleted file mode 100644 index 7bbaaa7d4..000000000 --- a/BuildTools/CommonDistFiles/web_plugins/scatterplot_example6.html +++ /dev/null @@ -1,578 +0,0 @@ - - - - - D3 Demo: Scatterplot - - - - - - - - - - - - diff --git a/BuildTools/CommonDistFiles/web_plugins/switch-off.png b/BuildTools/CommonDistFiles/web_plugins/switch-off.png new file mode 100644 index 000000000..6dfe12483 Binary files /dev/null and b/BuildTools/CommonDistFiles/web_plugins/switch-off.png differ diff --git a/BuildTools/CommonDistFiles/web_plugins/switch-on.png b/BuildTools/CommonDistFiles/web_plugins/switch-on.png new file mode 100644 index 000000000..58f160889 Binary files /dev/null and b/BuildTools/CommonDistFiles/web_plugins/switch-on.png differ diff --git a/BuildTools/centos/GNUmakefile b/BuildTools/centos/GNUmakefile index 2b4f4e8fc..00b7a15ba 100644 --- a/BuildTools/centos/GNUmakefile +++ b/BuildTools/centos/GNUmakefile @@ -10,7 +10,7 @@ default: compile-geoda app: build-geoda-mac -compile-geoda: geoda-target algorithms-target dataviewer-target dialogtools-target explore-target libgdiam-target regression-target shapeoperations-target resource-target varcalc-target +compile-geoda: geoda-target knn-target algorithms-target dataviewer-target dialogtools-target explore-target libgdiam-target regression-target shapeoperations-target resource-target varcalc-target conf = `./libraries/bin/wx-config --libs` @@ -20,6 +20,9 @@ test1: resource-target: (cd $(GeoDa_ROOT)/rc; $(MAKE) xrc; $(MAKE)) +knn-target: + (cd $(GeoDa_ROOT)/kNN; $(MAKE)) + algorithms-target: (cd $(GeoDa_ROOT)/Algorithms; $(MAKE)) diff --git a/BuildTools/centos/build64_v6.sh b/BuildTools/centos/build64_v6.sh new file mode 100755 index 000000000..305a062c7 --- /dev/null +++ b/BuildTools/centos/build64_v6.sh @@ -0,0 +1,718 @@ +!/bin/bash +############################################################################# +# ./build.sh +# ./build.sh [CPU] +# ./build.sh 8 (with debug) +# ./build.sh [CPU] [NODEBUG, true=1 false=0(default)] +# ./build.sh 8 1 (no debug) +############################################################################# +CPUS=4 +NODEBUG=1 +if [[ $CPUS == "" ]] ; then + CPUS=8 +fi +if [[ $NODEBUG == "" ]] ; then + NODEBUG=0 +else + if ! [[ $NODEBUG -eq 1 ]] ; then + NODEBUG=0 + fi +fi + +if ! type "g++" > /dev/null; then + echo "You need to install g++ to run this script." + sudo yum install gcc-c++ +fi + +if ! type "cmake" > /dev/null; then + echo "You need to install cmake to run this script." + sudo yum install cmake +fi + +if ! type "curl" > /dev/null; then + echo "You need to install curl to run this script." + sudo yum install curl +fi + +read -p "Do you want to install pre-requisites (e.g. libreadline, zlib, libexpat, libcurl ...)?[y/n]" -n 1 -r +echo +if [[ $REPLY =~ ^[Yy]$ ]]; then + sudo yum install readline-devel zlib-devel expat-devel curl-devel autoreconf libtool openssl-devel libidn-devel openldap-devel mesa-libGL-devel mesa-libGLU-devel gtk3 freeglut-devel webkitgtk3-devel +fi + +unset ORACLE_HOME +export GEODA_HOME=$PWD +PREFIX=$GEODA_HOME/libraries +DOWNLOAD_HOME=$GEODA_HOME/temp +echo $PREFIX + +MAKER="make -j $CPUS" +export CFLAGS="-m64" +export CXXFLAGS="-m64" +#export LDFLAGS="-m64 -L/usr/lib/x86_64-linux-gnu" + +if ! [ -d $DOWNLOAD_HOME ]; then + mkdir $DOWNLOAD_HOME +fi + +if ! [ -d $PREFIX ]; then + mkdir $PREFIX +fi + +######################################################################### +# install library function +######################################################################### +install_library() +{ + LIB_NAME=$1 + LIB_URL=$2 + LIB_CHECKER=$3 + LIB_FILENAME=$(basename "$LIB_URL") + CONFIGURE_FLAGS=$4 + echo "" + echo "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%" + echo "% Building: $LIB_FILENAME" + echo "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%" + echo $LIB_FILENAME + + cd $DOWNLOAD_HOME + + if ! [ -f "$LIB_FILENAME" ] ; then + echo "$LIB_FILENAME not found. Downloading..." + curl -O $LIB_URL + else + echo "$LIB_FILENAME found. Download skipped." + fi + + if ! [ -d "$LIB_NAME" ] ; then + echo "Directory $LIB_NAME not found. Expanding..." + tar -xf $LIB_FILENAME + else + echo "Directory $LIB_NAME found. File expansion skipped." + fi + + if ! [ -f "$PREFIX/lib/$LIB_CHECKER" ] ; then + cd $LIB_NAME + chmod +x configure + ./configure CFLAGS="-m64" CXXFLAGS="-m64" LDFLAGS="-m64 -L/usr/lib64" --prefix=$PREFIX $CONFIGURE_FLAGS + #./configure --prefix=$PREFIX + $MAKER + make install + fi + if ! [ -f "$PREFIX/lib/$LIB_CHECKER" ] ; then + echo "Error! Exit" + exit + fi +} +######################################################################### +# install libiConv +######################################################################### +echo "" +echo "%%%%%%%%%%%%%%%%%%%%%%" +echo "% Building: libiConv %" +echo "%%%%%%%%%%%%%%%%%%%%%%" +{ + LIB_NAME="libiconv-1.13" + LIB_URL="http://ftp.gnu.org/pub/gnu/libiconv/libiconv-1.13.tar.gz" + LIB_CHECKER="libiconv.so" + LIB_FILENAME="libiconv-1.13.tar.gz" + echo $LIB_FILENAME + + cd $DOWNLOAD_HOME + if ! [ -d "$LIB_NAME" ] ; then + curl -O $LIB_URL + tar -xf $LIB_FILENAME + fi + + if ! [ -f "$PREFIX/lib/$LIB_CHECKER" ] ; then + cd $LIB_NAME + chmod +x configure + ./configure --enable-static --prefix=$PREFIX + $MAKER + make install + fi + if ! [ -f "$PREFIX/lib/$LIB_CHECKER" ] ; then + echo "Error! Exit" + exit + fi +} + +######################################################################### +# install c-ares -- for cURL, prevent crash on Mac oSx with threads +######################################################################### +install_library c-ares-1.10.0 https://s3.us-east-2.amazonaws.com/geodabuild/c-ares-1.10.0.tar.gz libcares.a + + +######################################################################### +# install cURL +######################################################################### + +LIB_NAME=curl-7.46.0 +LIB_CHECKER=libcurl.a +LIB_URL=https://s3.us-east-2.amazonaws.com/geodabuild/curl-7.46.0.zip +LIB_FILENAME=curl-7.46.0.zip +echo $LIB_NAME + +cd $DOWNLOAD_HOME + +if ! [ -d "$LIB_NAME" ] ; then + curl -O $LIB_URL + unzip $LIB_FILENAME +fi + +if ! [ -d "$LIB_NAME" ]; then + tar -xf $LIB_FILENAME +fi + +if ! [ -f "$PREFIX/lib/$LIB_CHECKER" ] ; then + cd $LIB_NAME + ./configure --enable-ares=$PREFIX CC="$GDA_CC" CFLAGS="$GDA_CFLAGS" CXX="$GDA_CXX" CXXFLAGS="$GDA_CXXFLAGS" LDFLAGS="$GDA_LDFLAGS" --prefix=$PREFIX --without-librtmp + $MAKER + make install +fi + +if ! [ -f "$PREFIX/lib/$LIB_CHECKER" ] ; then + echo "Error! Exit" + exit +fi + +######################################################################### +# install Xerces +######################################################################### +echo "" +echo "%%%%%%%%%%%%%%%%%%%%" +echo "% Building: Xerces %" +echo "%%%%%%%%%%%%%%%%%%%%" +{ + LIB_NAME="xerces-c-3.1.1" + LIB_URL="https://s3.us-east-2.amazonaws.com/geodabuild/xerces-c-3.1.1.tar.gz" + LIB_CHECKER="libxerces-c.a" + LIB_FILENAME=$(basename "$LIB_URL" ".tar") + echo $LIB_FILENAME + + cd $DOWNLOAD_HOME + if ! [ -d "$LIB_NAME" ] ; then + curl -O $LIB_URL + tar -xf $LIB_FILENAME + fi + + if ! [ -f "$PREFIX/lib/$LIB_CHECKER" ] ; then + cd $LIB_NAME + chmod +x configure + ./configure --prefix=$PREFIX + chmod +x config/pretty-make + $MAKER + make install + fi + + if ! [ -f "$PREFIX/lib/$LIB_CHECKER" ] ; then + echo "Error! Exit" + exit + fi +} + +######################################################################### +# install GEOS +######################################################################### +install_library geos-3.3.8 https://s3.us-east-2.amazonaws.com/geodabuild/geos-3.3.8.tar.bz2 libgeos.a + +######################################################################### +# install PROJ.4 +######################################################################### +install_library proj-4.8.0 https://s3.us-east-2.amazonaws.com/geodabuild/proj-4.8.0.tar.gz libproj.a + +######################################################################### +# install FreeXL +######################################################################### +install_library freexl-1.0.0f https://s3.us-east-2.amazonaws.com/geodabuild/freexl-1.0.0f.tar.gz libfreexl.a + +######################################################################### +# install SQLite +######################################################################### +install_library sqlite-autoconf-3071602 https://s3.us-east-2.amazonaws.com/geodabuild/sqlite-autoconf-3071602.tar.gz libsqlite3.a + +######################################################################### +# install PostgreSQL +######################################################################### +# libreadline, zlib +echo "install libreadline, zlib" +install_library postgresql-9.2.4 https://s3.us-east-2.amazonaws.com/geodabuild/postgresql-9.2.4.tar.bz2 libpq.a + +######################################################################### +# install libjpeg +######################################################################### +install_library jpeg-8 https://s3.us-east-2.amazonaws.com/geodabuild/jpegsrc.v8.tar.gz libjpeg.a + +######################################################################### +# install libkml requires 1.3 +######################################################################### +echo "" +echo "%%%%%%%%%%%%%%%%%%%%" +echo "% Building: libkml %" +echo "%%%%%%%%%%%%%%%%%%%%" +# libexpat,libcurl4-gnutls-dev +#install_library libkml-1.2.0 https://libkml.googlecode.com/files/libkml-1.2.0.tar.gz libkmlbase.a +{ + LIB_NAME="libkml" + LIB_CHECKER="libkmlbase.a" + LIB_URL=https://s3.us-east-2.amazonaws.com/geodabuild/libkml-r680.tar.gz + LIB_FILENAME=libkml-r680.tar.gz + echo $LIB_NAME + + cd $DOWNLOAD_HOME + if ! [ -d "$LIB_NAME" ] ; then + curl -O $LIB_URL + fi + + if ! [ -d "$LIB_NAME" ]; then + tar -xf $LIB_FILENAME + fi + + if ! [ -f "$PREFIX/lib/$LIB_CHECKER" ] ; then + cp -rf ../dep/"$LIB_NAME" . + cd $LIB_NAME + ./autogen.sh + chmod +x configure + ./configure CXXFLAGS="-Wno-long-long" --prefix=$PREFIX + sed -i.old "/gtest-death-test.Plo/d" third_party/Makefile + sed -i.old "/gtest-filepath.Plo/d" third_party/Makefile + sed -i.old "/gtest-port.Plo/d" third_party/Makefile + sed -i.old "/gtest-test-part.Plo/d" third_party/Makefile + sed -i.old "/gtest-typed-test.Plo/d" third_party/Makefile + sed -i.old "/gtest-test.Plo/d" third_party/Makefile + sed -i.old "/gtest.Plo/d" third_party/Makefile + sed -i.old "/gtest_main.Plo/d" third_party/Makefile + sed -i.old "/UriCommon.Plo/d" third_party/Makefile + sed -i.old "/UriCompare.Plo/d" third_party/Makefile + sed -i.old "/UriEscape.Plo/d" third_party/Makefile + sed -i.old "/UriFile.Plo/d" third_party/Makefile + sed -i.old "/UriIp4.Plo/d" third_party/Makefile + sed -i.old "/UriIp4Base.Plo/d" third_party/Makefile + sed -i.old "/UriNormalize.Plo/d" third_party/Makefile + sed -i.old "/UriNormalizeBase.Plo/d" third_party/Makefile + sed -i.old "/UriParse.Plo/d" third_party/Makefile + sed -i.old "/UriParseBase.Plo/d" third_party/Makefile + sed -i.old "/UriQuery.Plo/d" third_party/Makefile + sed -i.old "/UriRecompose.Plo/d" third_party/Makefile + sed -i.old "/UriResolve.Plo/d" third_party/Makefile + sed -i.old "/UriShorten.Plo/d" third_party/Makefile + sed -i.old "/ioapi.Plo/d" third_party/Makefile + sed -i.old "/iomem_simple.Plo/d" third_party/Makefile + sed -i.old "/zip.Plo/d" third_party/Makefile + #$MAKER + sed -i.old "s/examples//g" Makefile + make third_party + make src + make testdata + make install + fi + + if ! [ -f "$PREFIX/lib/$LIB_CHECKER" ] ; then + echo "Error! Exit" + exit + fi +} + +######################################################################### +# install SpatiaLite +######################################################################### +echo "" +echo "%%%%%%%%%%%%%%%%%%%%%%%%" +echo "% Building: Spatialite %" +echo "%%%%%%%%%%%%%%%%%%%%%%%%" +{ + LIB_NAME=libspatialite-4.0.0 + LIB_URL=https://s3.us-east-2.amazonaws.com/geodabuild/libspatialite-4.0.0.tar.gz + LIB_FILENAME=$(basename "$LIB_URL" ".tar") + LIB_CHECKER=libspatialite.a + echo $LIB_FILENAME + + cd $DOWNLOAD_HOME + if ! [ -d "$LIB_NAME" ] ; then + curl -O $LIB_URL + tar -xf $LIB_FILENAME + fi + + if ! [ -f "$PREFIX/lib/$LIB_CHECKER" ] ; then + cd $LIB_NAME + chmod +x configure + echo $PREFIX + ./configure CFLAGS="-I$PREFIX/include" CXXFLAGS="-I$PREFIX/include" LDFLAGS="-L$PREFIX/lib" --prefix=$PREFIX --enable-geos --enable-iconv --enable-proj --with-geosconfig=$PREFIX/bin/geos-config + $MAKER + make install + fi + + if ! [ -f "$PREFIX/lib/$LIB_CHECKER" ] ; then + echo "Error! Exit" + exit + fi +} +######################################################################### +# MySQL +######################################################################### +#cmake, curse +echo "" +echo "%%%%%%%%%%%%%%%%%%%" +echo "% Building: MySQL %" +echo "%%%%%%%%%%%%%%%%%%%" +{ + LIB_NAME=mysql-5.6.14 + LIB_URL=https://s3.us-east-2.amazonaws.com/geodabuild/mysql-5.6.14.tar.gz + LIB_CHECKER=libmysqlclient.a + + echo $LIB_NAME + cd $DOWNLOAD_HOME + if ! [ -d "$LIB_NAME" ] ; then + curl -O $LIB_URL + tar -xf $LIB_NAME.tar.gz + #cp $GEODA_HOME/dep/mysql/my_default.h $GEODA_HOME/temp/mysql-5.6.14/include/my_default.h + fi + + if ! [ -f "$GEODA_HOME/temp/mysql-5.6.14/bld/libmysql/$LIB_CHECKER" ] ; then + echo "HERE" + cd $LIB_NAME + mkdir -p bld + cd bld + cmake -DCURSES_LIBRARY=/usr/lib/libncurses.so -DCURSES_INCLUDE_PATH=/usr/include .. + chmod +x bld/extra/comp_err + chmod +x bld/sql/gen_lex_hash + chmod +x storage/perfschema/gen_pfs_lex_token + $MAKER + fi + + if ! [ -f "$GEODA_HOME/temp/$LIB_NAME/bld/libmysql/$LIB_CHECKER" ] ; then + echo "Error! Exit" + exit + fi +} + +######################################################################### +# Eigen3 +######################################################################### +LIB_NAME=eigen3 +LIB_URL=https://s3.us-east-2.amazonaws.com/geodabuild/eigen3.zip +LIB_CHECKER=Dense +LIB_FILENAME=$LIB_NAME.zip +echo $LIB_FILENAME +cd $DOWNLOAD_HOME + +if ! [ -f "$LIB_FILENAME" ] ; then + curl -O $LIB_URL +fi + +if ! [ -d "$LIB_NAME" ]; then + unzip $LIB_FILENAME +fi + +cd $DOWNLOAD_HOME/$LIB_NAME +if ! [ -f "$PREFIX/include/eigen3/Eigen/$LIB_CHECKER" ] ; then + mkdir bld + cd bld + cmake .. -DCMAKE_INSTALL_PREFIX=$PREFIX + make install +fi + +if ! [ -f "$PREFIX/include/eigen3/Eigen/$LIB_CHECKER" ] ; then + echo "Error! Exit" + exit +fi +######################################################################### +# install boost library +######################################################################### +echo "" +echo "%%%%%%%%%%%%%%%%%%%%%%%%" +echo "% Building: Boost 1.57 %" +echo "%%%%%%%%%%%%%%%%%%%%%%%%" +{ + LIB_NAME=boost_1_57_0 + LIB_URL=https://s3.us-east-2.amazonaws.com/geodabuild/boost_1_57_0.tar.gz + LIB_FILENAME=boost_1_57_0.tar.gz + LIB_CHECKER=libboost_thread.a + echo $LIB_FILENAME + + cd $DOWNLOAD_HOME + if ! [ -f "$LIB_FILENAME" ]; then + echo "$LIB_FILENAME not found. Downloading..." + curl -O $LIB_URL + else + echo "$LIB_FILENAME found. Skipping download." + fi + + if ! [ -d "$LIB_NAME" ]; then + echo "Directory $LIB_NAME not found. Expanding archive." + tar -xf $LIB_FILENAME + else + echo "Directory $LIB_NAME found. Skipping expansion." + fi + + if ! [ -f "$GEODA_HOME/temp/$LIB_NAME/stage/lib/$LIB_CHECKER" ] ; then + echo "$LIB_CHECKER not found. Building Boost..." + cd $PREFIX/include + rm boost + ln -s $DOWNLOAD_HOME/boost_1_57_0 boost + cd $DOWNLOAD_HOME/boost_1_57_0 + chmod +x bootstrap.sh + #chmod +x tools/build/v2/engine/build.sh + ./bootstrap.sh + chmod +x b2 + ./b2 --with-thread --with-date_time --with-chrono --with-system link=static,shared threading=multi stage + fi + + if ! [ -f "$GEODA_HOME/temp/$LIB_NAME/stage/lib/$LIB_CHECKER" ] ; then + echo "Error: Target library $LIB_CHECKER not found. Exiting build." + exit + fi +} + +######################################################################### +# install JSON Spirit +######################################################################### +echo "" +echo "%%%%%%%%%%%%%%%%%%%%%%%%%" +echo "% Building: JSON Spirit %" +echo "%%%%%%%%%%%%%%%%%%%%%%%%%" +LIB_NAME="json_spirit_v4.08" +LIB_URL="https://s3.us-east-2.amazonaws.com/geodabuild/json_spirit_v4.08.zip" +LIB_CHECKER="libjson_spirit.a" +LIB_FILENAME="json_spirit_v4.08.zip" +echo $LIB_FILENAME + + +cd $DOWNLOAD_HOME + +if ! [ -d "$LIB_NAME" ]; then + curl -O https://s3.us-east-2.amazonaws.com/geodabuild/json_spirit_v4.08.zip + unzip $LIB_FILENAME +fi + +cd $DOWNLOAD_HOME/$LIB_NAME + +if ! [ -f "$PREFIX/lib/$LIB_CHECKER" ] ; then + cp $GEODA_HOME/dep/json_spirit/CMakeLists.txt . + mkdir bld + cd bld + CC=$GDA_CC CXX=$GDA_CXX CFLAGS=$GDA_CFLAGS CXXFLAGS=$GDA_CXXFLAGS LDFLAGS=$GDA_LDFLAGS cmake .. + make + rm -rf "$PREFIX/include/json_spirit" + rm -f "$PREFIX/lib/$LIB_CHECKER" + mkdir "$PREFIX/include/json_spirit" + echo "Copying JSON Sprit includes..." + cp -R "../json_spirit" "$PREFIX/include/." + echo "Copying libjson_spirit.a" + cp json_spirit/libjson_spirit.a "$PREFIX/lib/." +fi + +if ! [ -f "$PREFIX/lib/$LIB_CHECKER" ] ; then + echo "Error! Exit" + exit +fi + +######################################################################### +# install CLAPACK +######################################################################### +echo "" +echo "%%%%%%%%%%%%%%%%%%%%%%%%%%%" +echo "% Building: CLAPACK 3.2.1 %" +echo "%%%%%%%%%%%%%%%%%%%%%%%%%%%" +{ + CLAPACK_NAME="CLAPACK-3.2.1" + LIB_CHECKER="libf2c.a" + echo $CLAPACK_NAME + + cd $DOWNLOAD_HOME + if ! [ -d "$CLAPACK_NAME" ]; then + curl -O https://s3.us-east-2.amazonaws.com/geodabuild/clapack.tgz + tar -xvf clapack.tgz + fi + + cp -rf $GEODA_HOME/dep/$CLAPACK_NAME . + cd $CLAPACK_NAME + if ! [ -f "libf2c.a" ] || ! [ -f "blas.a" ] || ! [ -f "lapack.a" ]; then + cp make.inc.example make.inc + $MAKER f2clib + cp F2CLIBS/libf2c.a . + $MAKER blaslib + cd INSTALL + $MAKER + cd .. + cd SRC + $MAKER + cd .. + $MAKER + mv -f blas_LINUX.a blas.a + mv -f lapack_LINUX.a lapack.a + mv -f tmglib_LINUX.a tmglib.a + cd .. + fi + + if ! [ -f "$GEODA_HOME/temp/$CLAPACK_NAME/$LIB_CHECKER" ] ; then + echo "Error! Exit" + exit + fi +} + +######################################################################### +# install json-c +######################################################################### +echo "" +echo "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%" +echo "% Building: json-c " +echo "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%" +{ + + LIB_NAME=json-c + LIB_CHECKER=libjson-c.a + + if ! [ -d "$LIB_NAME" ] ; then + git clone https://github.com/json-c/json-c.git + fi + + + if ! [ -f "$PREFIX/lib/$LIB_CHECKER" ] ; then + cd $LIB_NAME + sh autogen.sh + ./configure --prefix=$PREFIX + make + make install + fi + + #if ! [ -f "$PREFIX/lib/$LIB_CHECKER" ] ; then + #echo "Error! Exit" + #exit + #fi +} + +######################################################################### +# install GDAL/OGR +######################################################################### +echo "" +echo "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%" +echo "% Building: Custom GDAL/OGR 1.9.2 %" +echo "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%" +{ + LIB_NAME=gdal + LIB_URL=https://codeload.github.com/lixun910/gdal/zip/GeoDa17Merge + LIB_FILENAME=GeoDa17Merge + LIB_CHECKER=libgdal.a + echo $LIB_FILENAME + + cd $DOWNLOAD_HOME + if ! [ -d "$LIB_NAME" ] ; then + #curl -k -O $LIB_URL + #unzip $LIB_FILENAME + git clone https://github.com/lixun910/gdal.git gdal-GeoDa17Merge + mv gdal-GeoDa17Merge/gdal gdal + fi + + if ! [ -f "$PREFIX/lib/$LIB_CHECKER" ] ; then + cd $LIB_NAME + chmod +x configure + chmod +x install-sh + ./configure + cp -rf $GEODA_HOME/dep/gdal-1.9.2/* . + cp GDALmake64.opt GDALmake.opt + #make clean + $MAKER + touch .libs/libgdal.lai + make install + #cd ogr/ogrsf_frmts/oci + #make plugin + #mv ogr_OCI.so ogr_OCI.dylib + #install_name_tool -change "/scratch/plebld/208/network/lib/libnnz10.dylib" "/Users/xun/Downloads/Oracle_10204Client_MAC_X86/ohome/lib/libnnz10.dylib" ogr_OCI.so + fi + if ! [ -f "$PREFIX/lib/$LIB_CHECKER" ] ; then + echo "Error! Exit" + exit + fi +} + +######################################################################### +# install wxWidgets library +######################################################################### +echo "" +echo "%%%%%%%%%%%%%%%%%%%%%%%%%%%%" +echo "% Building wxWidgets 3.0.2 %" +echo "%%%%%%%%%%%%%%%%%%%%%%%%%%%%" +# sudo apt-get install libgtk2.0-dev libglu1-mesa-dev libgl1-mesa-dev +{ + LIB_NAME=wxWidgets-3.1.0 + LIB_URL="https://s3.us-east-2.amazonaws.com/geodabuild/wxWidgets-3.1.0.tar.bz2" + + LIB_FILENAME=$(basename "$LIB_URL" ".tar") + LIB_CHECKER=wx-config + echo $LIB_FILENAME + + cd $DOWNLOAD_HOME + if ! [ -f "$LIB_FILENAME" ] ; then + curl -k -o $LIB_FILENAME $LIB_URL + fi + + if ! [ -d "$LIB_NAME" ]; then + tar -xf $LIB_FILENAME + fi + + if ! [ -f "$PREFIX/bin/$LIB_CHECKER" ] ; then + cd $LIB_NAME + cp -rf $GEODA_HOME/dep/$LIB_NAME/* . + chmod +x configure + chmod +x src/stc/gen_iface.py + ./configure --with-gtk=3 --enable-ascii --disable-monolithic --with-opengl --enable-postscript --without-libtiff --disable-debug --enable-webview --prefix=$PREFIX + #make clean + $MAKER + make install + cd .. + fi + + if ! [ -f "$PREFIX/bin/$LIB_CHECKER" ] ; then + echo "Error! Exit" + exit + fi +} + +######################################################################### +# Eigen3 +######################################################################### +LIB_NAME=eigen3 +LIB_URL=https://s3.us-east-2.amazonaws.com/geodabuild/eigen3.zip +LIB_CHECKER=Dense +LIB_FILENAME=$LIB_NAME.zip +echo $LIB_FILENAME +cd $DOWNLOAD_HOME + +if ! [ -f "$LIB_FILENAME" ] ; then + curl -O $LIB_URL +fi + +if ! [ -d "$LIB_NAME" ]; then + unzip $LIB_FILENAME +fi + +cd $DOWNLOAD_HOME/$LIB_NAME +if ! [ -f "$PREFIX/include/eigen3/Eigen/$LIB_CHECKER" ] ; then + mkdir bld + cd bld + cmake .. -DCMAKE_INSTALL_PREFIX=$PREFIX + make install +fi + +if ! [ -f "$PREFIX/include/eigen3/Eigen/$LIB_CHECKER" ] ; then + echo "Error! Exit" + exit +fi +######################################################################### +# build GeoDa +######################################################################### +echo "" +echo "%%%%%%%%%%%%%%%%%%%" +echo "% Building: GeoDa %" +echo "%%%%%%%%%%%%%%%%%%%" +{ + cd $GEODA_HOME + cp ../../GeoDamake.centos6.opt ../../GeoDamake.opt + mkdir ../../o + make clean + $MAKER + make app + #cp plugins/x64/*.so build/plugins/ + cp ../CommonDistFiles/web_plugins/no_map.png build/web_plugins/no_map.png +} diff --git a/BuildTools/centos/create_rpm.sh b/BuildTools/centos/create_rpm.sh index 8c1e26ff4..67ab9877b 100755 --- a/BuildTools/centos/create_rpm.sh +++ b/BuildTools/centos/create_rpm.sh @@ -6,10 +6,10 @@ rm -rf rpm/ cp -rf rpm_template/ rpm/ mkdir rpm/SOURCES cp -rf build/ rpm/SOURCES/ -mv rpm/SOURCES/build rpm/SOURCES/GeoDa-1.8 -rm -r rpm/SOURCES/GeoDa-1.8/web_plugins/d3 +mv rpm/SOURCES/build rpm/SOURCES/GeoDa-1.10 +rm -r rpm/SOURCES/GeoDa-1.10/web_plugins/d3 cd rpm/SOURCES/ -tar czf geoda.tar.gz GeoDa-1.8/ +tar czf geoda.tar.gz GeoDa-1.10/ cd .. rpmbuild -ba SPECS/GeoDa.spec mv RPMS/x86_64/*.rpm ../ diff --git a/BuildTools/centos/readme.txt b/BuildTools/centos/readme.txt index 46ed720b2..9d1fca8bf 100644 --- a/BuildTools/centos/readme.txt +++ b/BuildTools/centos/readme.txt @@ -9,7 +9,7 @@ compiling libraries and GeoDa, and finally packaging the program for distribution and installation. *************************************************** -*** Building GeoDa for 64-bit CentOS 6 or later *** +*** Building GeoDa for 64-bit CentOS 7 *************************************************** NOTE: This is just basic placeholder for now! Not currently complete. @@ -29,3 +29,29 @@ Build machine assumptions: 5. Package GeoDa for distribution / installation. +*************************************************** +*** Building GeoDa for 64-bit CentOS 6 +*************************************************** + +1. wxwidgets 3.1 works with GTK2, which is only avaiable on CentOS6 + +2. webkitgtk is version 1.0 on CentOS6. Install: yum install webkitgtk-devel + +3. yum install readline-devel, autoreconf, gtk2-devel + +4. +cp libraries/lib/libwx_gtk2u_xrc-3.1.so.0.0.0 build/plugins/libwx_gtk2u_xrc-3.1.so.0 +cp libraries/lib/libwx_gtk2u_stc-3.1.so.0.0.0 build/plugins/libwx_gtk2u_stc-3.1.so.0 +cp libraries/lib/libwx_gtk2u_richtext-3.1.so.0.0.0 build/plugins/libwx_gtk2u_richtext-3.1.so.0 +cp libraries/lib/libwx_gtk2u_ribbon-3.1.so.0.0.0 build/plugins/libwx_gtk2u_ribbon-3.1.so.0 +cp libraries/lib/libwx_gtk2u_propgrid-3.1.so.0.0.0 build/plugins/libwx_gtk2u_propgrid-3.1.so.0 +cp libraries/lib/libwx_gtk2u_aui-3.1.so.0.0.0 build/plugins/libwx_gtk2u_aui-3.1.so.0 +cp libraries/lib/libwx_gtk2u_gl-3.1.so.0.0.0 build/plugins/libwx_gtk2u_gl-3.1.so.0 +cp libraries/lib/libwx_gtk2u_html-3.1.so.0.0.0 build/plugins/libwx_gtk2u_html-3.1.so.0 +cp libraries/lib/libwx_gtk2u_webview-3.1.so.0.0.0 build/plugins/libwx_gtk2u_webview-3.1.so.0 +cp libraries/lib/libwx_gtk2u_qa-3.1.so.0.0.0 build/plugins/libwx_gtk2u_qa-3.1.so.0 +cp libraries/lib/libwx_gtk2u_adv-3.1.so.0.0.0 build/plugins/libwx_gtk2u_adv-3.1.so.0 +cp libraries/lib/libwx_gtk2u_core-3.1.so.0.0.0 build/plugins/libwx_gtk2u_core-3.1.so.0 +cp libraries/lib/libwx_baseu_xml-3.1.so.0.0.0 build/plugins/libwx_baseu_xml-3.1.so.0 +cp libraries/lib/libwx_baseu_net-3.1.so.0.0.0 build/plugins/libwx_baseu_net-3.1.so.0 +cp libraries/lib/libwx_baseu-3.1.so.0.0.0 build/plugins/libwx_baseu-3.1.so.0 diff --git a/BuildTools/centos/rpm_template/SPECS/GeoDa.spec b/BuildTools/centos/rpm_template/SPECS/GeoDa.spec index 91cc5a54b..56e8a204a 100644 --- a/BuildTools/centos/rpm_template/SPECS/GeoDa.spec +++ b/BuildTools/centos/rpm_template/SPECS/GeoDa.spec @@ -1,5 +1,5 @@ Name: GeoDa -Version: 1.8 +Version: 1.10 Release: 1%{?dist} Summary: An Introduction to Spatial Data Analysis diff --git a/BuildTools/macosx/GNUmakefile b/BuildTools/macosx/GNUmakefile index c8babda75..16ca8e31b 100644 --- a/BuildTools/macosx/GNUmakefile +++ b/BuildTools/macosx/GNUmakefile @@ -11,8 +11,8 @@ default: compile-geoda app: build-geoda-mac -compile-geoda: algorithms-target dataviewer-target dialogtools-target \ - explore-target libgdiam-target regression-target \ +compile-geoda: ogl-target io-target algorithms-target dataviewer-target dialogtools-target \ + knn-target explore-target libgdiam-target regression-target \ shapeoperations-target resource-target varcalc-target \ geoda-target @@ -22,6 +22,15 @@ test: resource-target: (cd $(GeoDa_ROOT)/rc; $(MAKE) xrc; $(MAKE)) +ogl-target: + (cd $(GeoDa_ROOT)/ogl; $(MAKE)) + +knn-target: + (cd $(GeoDa_ROOT)/kNN; $(MAKE)) + +io-target: + (cd $(GeoDa_ROOT)/io; $(MAKE)) + algorithms-target: (cd $(GeoDa_ROOT)/Algorithms; $(MAKE)) @@ -62,6 +71,8 @@ build-geoda-mac: mkdir -p build/GeoDa.app/Contents/Resources/plugins cp $(GeoDa_ROOT)/BuildTools/CommonDistFiles/web_plugins/*.* build/GeoDa.app/Contents/Resources/ cp $(GeoDa_ROOT)/BuildTools/CommonDistFiles/cache.sqlite build/GeoDa.app/Contents/MacOS + cp $(GeoDa_ROOT)/Algorithms/lisa_kernel.cl build/GeoDa.app/Contents/MacOS + cp -rf $(GeoDa_ROOT)/internationalization/lang build/GeoDa.app/Contents/MacOS $(LD) $(LDFLAGS) $(GeoDa_OBJ) $(LIBS) -o build/GeoDa.app/Contents/MacOS/GeoDa cp run.sh build/GeoDa.app/Contents/MacOS/run.sh cp GeoDa-GDAL-Info.plist build/GeoDa.app/Contents/Info.plist diff --git a/BuildTools/macosx/GeoDa-C++11.xcodeproj/project.pbxproj b/BuildTools/macosx/GeoDa-C++11.xcodeproj/project.pbxproj index 0f0534b9c..cd9f28943 100644 --- a/BuildTools/macosx/GeoDa-C++11.xcodeproj/project.pbxproj +++ b/BuildTools/macosx/GeoDa-C++11.xcodeproj/project.pbxproj @@ -1504,6 +1504,7 @@ "-L/usr/lib", "-liconv", "-L./libraries/lib", + ./libraries/include/boost/stage/lib/libboost_date_time.a, ./libraries/include/boost/stage/lib/libboost_system.a, ./libraries/include/boost/stage/lib/libboost_thread.a, "-framework", @@ -1591,6 +1592,7 @@ "-L/usr/lib", "-liconv", "-L./libraries/lib", + ./libraries/include/boost/stage/lib/libboost_date_time.a, ./libraries/include/boost/stage/lib/libboost_system.a, ./libraries/include/boost/stage/lib/libboost_thread.a, "-framework", diff --git a/BuildTools/macosx/GeoDa-leopard.xcodeproj/project.pbxproj b/BuildTools/macosx/GeoDa-leopard.xcodeproj/project.pbxproj index a0e1fe6a3..161ad0b73 100644 --- a/BuildTools/macosx/GeoDa-leopard.xcodeproj/project.pbxproj +++ b/BuildTools/macosx/GeoDa-leopard.xcodeproj/project.pbxproj @@ -15,6 +15,18 @@ A14CB4651C866E110082B436 /* AdjustYAxisDlg.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A14CB4611C866E110082B436 /* AdjustYAxisDlg.cpp */; }; A14CB4661C866E110082B436 /* BasemapConfDlg.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A14CB4631C866E110082B436 /* BasemapConfDlg.cpp */; }; A14CB46E1C86705B0082B436 /* PublishDlg.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A14CB46C1C86705B0082B436 /* PublishDlg.cpp */; }; + A1546D241F5B52D2002FC3DF /* cluster.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A1546D181F5B52D2002FC3DF /* cluster.cpp */; }; + A1546D251F5B52D2002FC3DF /* maxp.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A1546D1A1F5B52D2002FC3DF /* maxp.cpp */; }; + A1546D271F5B52D2002FC3DF /* pca.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A1546D1E1F5B52D2002FC3DF /* pca.cpp */; }; + A1546D281F5B52D2002FC3DF /* redcap.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A1546D201F5B52D2002FC3DF /* redcap.cpp */; }; + A1546D291F5B52D2002FC3DF /* spectral.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A1546D221F5B52D2002FC3DF /* spectral.cpp */; }; + A1546D381F5B53A7002FC3DF /* AbstractClusterDlg.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A1546D2A1F5B53A7002FC3DF /* AbstractClusterDlg.cpp */; }; + A1546D391F5B53A7002FC3DF /* HClusterDlg.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A1546D2C1F5B53A7002FC3DF /* HClusterDlg.cpp */; }; + A1546D3A1F5B53A7002FC3DF /* KMeansDlg.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A1546D2E1F5B53A7002FC3DF /* KMeansDlg.cpp */; }; + A1546D3B1F5B53A7002FC3DF /* MaxpDlg.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A1546D301F5B53A7002FC3DF /* MaxpDlg.cpp */; }; + A1546D3C1F5B53A7002FC3DF /* MDSDlg.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A1546D321F5B53A7002FC3DF /* MDSDlg.cpp */; }; + A1546D3D1F5B53A7002FC3DF /* RedcapDlg.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A1546D341F5B53A7002FC3DF /* RedcapDlg.cpp */; }; + A1546D3E1F5B53A7002FC3DF /* SpectralClusteringDlg.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A1546D361F5B53A7002FC3DF /* SpectralClusteringDlg.cpp */; }; A15609181E52442C009F4178 /* ReportBugDlg.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A15609161E52442C009F4178 /* ReportBugDlg.cpp */; }; A156091B1E524445009F4178 /* ConditionalClusterMapView.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A15609191E524445009F4178 /* ConditionalClusterMapView.cpp */; }; A16BA470183D626200D3B7DA /* DatasourceDlg.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A16BA46E183D626200D3B7DA /* DatasourceDlg.cpp */; }; @@ -241,6 +253,30 @@ A14CB4641C866E110082B436 /* BasemapConfDlg.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = BasemapConfDlg.h; sourceTree = ""; }; A14CB46C1C86705B0082B436 /* PublishDlg.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = PublishDlg.cpp; sourceTree = ""; }; A14CB46D1C86705B0082B436 /* PublishDlg.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PublishDlg.h; sourceTree = ""; }; + A1546D181F5B52D2002FC3DF /* cluster.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = cluster.cpp; path = Algorithms/cluster.cpp; sourceTree = ""; }; + A1546D191F5B52D2002FC3DF /* cluster.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = cluster.h; path = Algorithms/cluster.h; sourceTree = ""; }; + A1546D1A1F5B52D2002FC3DF /* maxp.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = maxp.cpp; path = Algorithms/maxp.cpp; sourceTree = ""; }; + A1546D1B1F5B52D2002FC3DF /* maxp.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = maxp.h; path = Algorithms/maxp.h; sourceTree = ""; }; + A1546D1E1F5B52D2002FC3DF /* pca.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = pca.cpp; path = Algorithms/pca.cpp; sourceTree = ""; }; + A1546D1F1F5B52D2002FC3DF /* pca.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = pca.h; path = Algorithms/pca.h; sourceTree = ""; }; + A1546D201F5B52D2002FC3DF /* redcap.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = redcap.cpp; path = Algorithms/redcap.cpp; sourceTree = ""; }; + A1546D211F5B52D2002FC3DF /* redcap.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = redcap.h; path = Algorithms/redcap.h; sourceTree = ""; }; + A1546D221F5B52D2002FC3DF /* spectral.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = spectral.cpp; path = Algorithms/spectral.cpp; sourceTree = ""; }; + A1546D231F5B52D2002FC3DF /* spectral.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = spectral.h; path = Algorithms/spectral.h; sourceTree = ""; }; + A1546D2A1F5B53A7002FC3DF /* AbstractClusterDlg.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = AbstractClusterDlg.cpp; sourceTree = ""; }; + A1546D2B1F5B53A7002FC3DF /* AbstractClusterDlg.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AbstractClusterDlg.h; sourceTree = ""; }; + A1546D2C1F5B53A7002FC3DF /* HClusterDlg.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = HClusterDlg.cpp; sourceTree = ""; }; + A1546D2D1F5B53A7002FC3DF /* HClusterDlg.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HClusterDlg.h; sourceTree = ""; }; + A1546D2E1F5B53A7002FC3DF /* KMeansDlg.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = KMeansDlg.cpp; sourceTree = ""; }; + A1546D2F1F5B53A7002FC3DF /* KMeansDlg.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = KMeansDlg.h; sourceTree = ""; }; + A1546D301F5B53A7002FC3DF /* MaxpDlg.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = MaxpDlg.cpp; sourceTree = ""; }; + A1546D311F5B53A7002FC3DF /* MaxpDlg.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MaxpDlg.h; sourceTree = ""; }; + A1546D321F5B53A7002FC3DF /* MDSDlg.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = MDSDlg.cpp; sourceTree = ""; }; + A1546D331F5B53A7002FC3DF /* MDSDlg.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MDSDlg.h; sourceTree = ""; }; + A1546D341F5B53A7002FC3DF /* RedcapDlg.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = RedcapDlg.cpp; sourceTree = ""; }; + A1546D351F5B53A7002FC3DF /* RedcapDlg.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RedcapDlg.h; sourceTree = ""; }; + A1546D361F5B53A7002FC3DF /* SpectralClusteringDlg.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = SpectralClusteringDlg.cpp; sourceTree = ""; }; + A1546D371F5B53A7002FC3DF /* SpectralClusteringDlg.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SpectralClusteringDlg.h; sourceTree = ""; }; A15609161E52442C009F4178 /* ReportBugDlg.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ReportBugDlg.cpp; sourceTree = ""; }; A15609171E52442C009F4178 /* ReportBugDlg.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ReportBugDlg.h; sourceTree = ""; }; A15609191E524445009F4178 /* ConditionalClusterMapView.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ConditionalClusterMapView.cpp; sourceTree = ""; }; @@ -657,6 +693,23 @@ /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ + A1546D171F5B52B0002FC3DF /* Algorithms */ = { + isa = PBXGroup; + children = ( + A1546D181F5B52D2002FC3DF /* cluster.cpp */, + A1546D191F5B52D2002FC3DF /* cluster.h */, + A1546D1A1F5B52D2002FC3DF /* maxp.cpp */, + A1546D1B1F5B52D2002FC3DF /* maxp.h */, + A1546D1E1F5B52D2002FC3DF /* pca.cpp */, + A1546D1F1F5B52D2002FC3DF /* pca.h */, + A1546D201F5B52D2002FC3DF /* redcap.cpp */, + A1546D211F5B52D2002FC3DF /* redcap.h */, + A1546D221F5B52D2002FC3DF /* spectral.cpp */, + A1546D231F5B52D2002FC3DF /* spectral.h */, + ); + name = Algorithms; + sourceTree = ""; + }; DD7686D41A9FF446009EFC6D /* libgdiam */ = { isa = PBXGroup; children = ( @@ -669,6 +722,7 @@ DD7974650F1D1B0700496A84 /* ../../ */ = { isa = PBXGroup; children = ( + A1546D171F5B52B0002FC3DF /* Algorithms */, A1B04ADC1B1921710045AA6F /* basemap_cache */, DD972054150A6EE4000206F4 /* CmdLineUtils */, DDDFB96D134B6B73005EF636 /* DataViewer */, @@ -755,6 +809,20 @@ DD7974FE0F1D296F00496A84 /* DialogTools */ = { isa = PBXGroup; children = ( + A1546D2A1F5B53A7002FC3DF /* AbstractClusterDlg.cpp */, + A1546D2B1F5B53A7002FC3DF /* AbstractClusterDlg.h */, + A1546D2C1F5B53A7002FC3DF /* HClusterDlg.cpp */, + A1546D2D1F5B53A7002FC3DF /* HClusterDlg.h */, + A1546D2E1F5B53A7002FC3DF /* KMeansDlg.cpp */, + A1546D2F1F5B53A7002FC3DF /* KMeansDlg.h */, + A1546D301F5B53A7002FC3DF /* MaxpDlg.cpp */, + A1546D311F5B53A7002FC3DF /* MaxpDlg.h */, + A1546D321F5B53A7002FC3DF /* MDSDlg.cpp */, + A1546D331F5B53A7002FC3DF /* MDSDlg.h */, + A1546D341F5B53A7002FC3DF /* RedcapDlg.cpp */, + A1546D351F5B53A7002FC3DF /* RedcapDlg.h */, + A1546D361F5B53A7002FC3DF /* SpectralClusteringDlg.cpp */, + A1546D371F5B53A7002FC3DF /* SpectralClusteringDlg.h */, A15609161E52442C009F4178 /* ReportBugDlg.cpp */, A15609171E52442C009F4178 /* ReportBugDlg.h */, A16D406C1CD4233A0025C64C /* AutoUpdateDlg.cpp */, @@ -1429,6 +1497,18 @@ A14CB46E1C86705B0082B436 /* PublishDlg.cpp in Sources */, A16D406E1CD4233A0025C64C /* AutoUpdateDlg.cpp in Sources */, A1D766D91D7A2196002365D6 /* CsvFieldConfDlg.cpp in Sources */, + A1546D241F5B52D2002FC3DF /* cluster.cpp in Sources */, + A1546D251F5B52D2002FC3DF /* maxp.cpp in Sources */, + A1546D271F5B52D2002FC3DF /* pca.cpp in Sources */, + A1546D281F5B52D2002FC3DF /* redcap.cpp in Sources */, + A1546D291F5B52D2002FC3DF /* spectral.cpp in Sources */, + A1546D381F5B53A7002FC3DF /* AbstractClusterDlg.cpp in Sources */, + A1546D391F5B53A7002FC3DF /* HClusterDlg.cpp in Sources */, + A1546D3A1F5B53A7002FC3DF /* KMeansDlg.cpp in Sources */, + A1546D3B1F5B53A7002FC3DF /* MaxpDlg.cpp in Sources */, + A1546D3C1F5B53A7002FC3DF /* MDSDlg.cpp in Sources */, + A1546D3D1F5B53A7002FC3DF /* RedcapDlg.cpp in Sources */, + A1546D3E1F5B53A7002FC3DF /* SpectralClusteringDlg.cpp in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -1502,6 +1582,7 @@ "-L/usr/lib", "-liconv", "-L./libraries/lib", + ./libraries/include/boost/stage/lib/libboost_date_time.a, ./libraries/include/boost/stage/lib/libboost_system.a, ./libraries/include/boost/stage/lib/libboost_thread.a, "-framework", @@ -1588,6 +1669,7 @@ "-L/usr/lib", "-liconv", "-L./libraries/lib", + ./libraries/include/boost/stage/lib/libboost_date_time.a, ./libraries/include/boost/stage/lib/libboost_system.a, ./libraries/include/boost/stage/lib/libboost_thread.a, "-framework", diff --git a/BuildTools/macosx/GeoDa.xcodeproj/project.pbxproj b/BuildTools/macosx/GeoDa.xcodeproj/project.pbxproj index 2d07ac73f..6ef47b6a4 100644 --- a/BuildTools/macosx/GeoDa.xcodeproj/project.pbxproj +++ b/BuildTools/macosx/GeoDa.xcodeproj/project.pbxproj @@ -7,14 +7,34 @@ objects = { /* Begin PBXBuildFile section */ + A10EF2F021273E7E00564FE1 /* AbstractCanvas.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A10EF2EE21273E7E00564FE1 /* AbstractCanvas.cpp */; }; A11B85BC1B18DC9C008B64EA /* Basemap.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A11B85BB1B18DC9C008B64EA /* Basemap.cpp */; }; A11F1B7F184FDFB3006F5F98 /* OGRColumn.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A11F1B7D184FDFB3006F5F98 /* OGRColumn.cpp */; }; A11F1B821850437A006F5F98 /* OGRTableOperation.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A11F1B801850437A006F5F98 /* OGRTableOperation.cpp */; }; + A1230E5E212DF54D002AB30A /* switch-on.png in Resources */ = {isa = PBXBuildFile; fileRef = A1230E5C212DF54C002AB30A /* switch-on.png */; }; + A1230E5F212DF54D002AB30A /* switch-off.png in Resources */ = {isa = PBXBuildFile; fileRef = A1230E5D212DF54D002AB30A /* switch-off.png */; }; + A1230E622130E783002AB30A /* MapLayer.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A1230E602130E783002AB30A /* MapLayer.cpp */; }; + A1230E652130E81A002AB30A /* MapLayerTree.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A1230E632130E81A002AB30A /* MapLayerTree.cpp */; }; A12E0F4F1705087A00B6059C /* OGRDataAdapter.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A12E0F4E1705087A00B6059C /* OGRDataAdapter.cpp */; }; + A1311C6720FFDF7100008D7F /* localjc_kernel.cl in CopyFiles */ = {isa = PBXBuildFile; fileRef = A4E00F0F20FD8ECC0038BA80 /* localjc_kernel.cl */; }; A13B6B9418760CF100F93ACF /* SaveAsDlg.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A13B6B9318760CF100F93ACF /* SaveAsDlg.cpp */; }; A14C496F1D76174000D9831C /* CsvFieldConfDlg.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A14C496D1D76174000D9831C /* CsvFieldConfDlg.cpp */; }; A16BA470183D626200D3B7DA /* DatasourceDlg.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A16BA46E183D626200D3B7DA /* DatasourceDlg.cpp */; }; A186F0A11C16508A00AEBA13 /* GdaCartoDB.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A186F09F1C16508A00AEBA13 /* GdaCartoDB.cpp */; }; + A1894C3F213F29DC00718FFC /* SpatialJoinDlg.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A1894C3D213F29DC00718FFC /* SpatialJoinDlg.cpp */; }; + A19483932118BAAA009A87A2 /* composit.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A194837A2118BAA7009A87A2 /* composit.cpp */; }; + A19483942118BAAA009A87A2 /* divided.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A194837E2118BAA7009A87A2 /* divided.cpp */; }; + A19483952118BAAA009A87A2 /* constrnt.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A194837F2118BAA7009A87A2 /* constrnt.cpp */; }; + A19483962118BAAA009A87A2 /* oglmisc.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A19483812118BAA8009A87A2 /* oglmisc.cpp */; }; + A19483972118BAAA009A87A2 /* bmpshape.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A19483852118BAA8009A87A2 /* bmpshape.cpp */; }; + A19483982118BAAA009A87A2 /* basic.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A19483862118BAA8009A87A2 /* basic.cpp */; }; + A19483992118BAAA009A87A2 /* canvas.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A19483872118BAA8009A87A2 /* canvas.cpp */; }; + A194839A2118BAAA009A87A2 /* lines.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A19483882118BAA9009A87A2 /* lines.cpp */; }; + A194839B2118BAAA009A87A2 /* basic2.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A19483892118BAA9009A87A2 /* basic2.cpp */; }; + A194839C2118BAAA009A87A2 /* mfutils.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A194838A2118BAA9009A87A2 /* mfutils.cpp */; }; + A194839D2118BAAA009A87A2 /* drawn.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A194838C2118BAA9009A87A2 /* drawn.cpp */; }; + A194839E2118BAAA009A87A2 /* ogldiag.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A19483912118BAAA009A87A2 /* ogldiag.cpp */; }; + A19483A22118BE8F009A87A2 /* MapLayoutView.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A19483A02118BE8E009A87A2 /* MapLayoutView.cpp */; }; A19F51501756A11E006E31B4 /* plugins in Resources */ = {isa = PBXBuildFile; fileRef = A19F514D1756A11E006E31B4 /* plugins */; }; A1AC05BF1C8645F300B6FE5F /* AdjustYAxisDlg.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A1AC05BD1C8645F300B6FE5F /* AdjustYAxisDlg.cpp */; }; A1B04ADD1B1921710045AA6F /* basemap_cache in CopyFiles */ = {isa = PBXBuildFile; fileRef = A1B04ADC1B1921710045AA6F /* basemap_cache */; }; @@ -37,12 +57,43 @@ A1F1BA5C178D3B46005A46E5 /* GdaCache.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A1F1BA5A178D3B46005A46E5 /* GdaCache.cpp */; }; A1F1BA99178D46B8005A46E5 /* cache.sqlite in CopyFiles */ = {isa = PBXBuildFile; fileRef = A1F1BA98178D46B8005A46E5 /* cache.sqlite */; }; A1FD8C19186908B800C35C41 /* CustomClassifPtree.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A1FD8C17186908B800C35C41 /* CustomClassifPtree.cpp */; }; + A40A6A7E20226B3C003CDD79 /* PreferenceDlg.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A40A6A7D20226B3B003CDD79 /* PreferenceDlg.cpp */; }; + A40AB92120F559F500F94543 /* scatterplot.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A40AB92020F559F500F94543 /* scatterplot.cpp */; }; + A40AB92820F675B600F94543 /* mathstuff.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A40AB92420F675B600F94543 /* mathstuff.cpp */; }; + A40AB92920F675B600F94543 /* oglstuff.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A40AB92520F675B600F94543 /* oglstuff.cpp */; }; + A40AB92A20F675B600F94543 /* oglpfuncs.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A40AB92720F675B600F94543 /* oglpfuncs.cpp */; }; + A414C88B207BED2700520546 /* MatfileReader.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A414C88A207BED2700520546 /* MatfileReader.cpp */; }; + A416A1771F84122B001F2884 /* PCASettingsDlg.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A416A1751F84122B001F2884 /* PCASettingsDlg.cpp */; }; + A42018031FB3C0AC0029709C /* skater.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A42018011FB3C0AC0029709C /* skater.cpp */; }; + A42018061FB4CF980029709C /* SkaterDlg.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A42018051FB4CF980029709C /* SkaterDlg.cpp */; }; + A42B6F781F666C57004AFAB8 /* FieldNewCalcDateTimeDlg.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A42B6F761F666C57004AFAB8 /* FieldNewCalcDateTimeDlg.cpp */; }; + A4320FC81F4735020007BE0D /* RedcapDlg.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A4320FC61F4735020007BE0D /* RedcapDlg.cpp */; }; + A432E84720A672EB007B8B25 /* distmatrix.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A432E84620A672EA007B8B25 /* distmatrix.cpp */; }; + A4368CDC1FABBBC60099FA9B /* mds.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A4368CDA1FABBBC60099FA9B /* mds.cpp */; }; + A43D124C1F1DE1D80073D408 /* MaxpDlg.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A43D124A1F1DE1D80073D408 /* MaxpDlg.cpp */; }; + A43D124F1F2088D50073D408 /* spectral.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A43D124E1F2088D50073D408 /* spectral.cpp */; }; + A43D12521F20AE450073D408 /* SpectralClusteringDlg.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A43D12511F20AE450073D408 /* SpectralClusteringDlg.cpp */; }; A43D31541E845985007488D9 /* LocalGearyCoordinator.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A43D31521E845985007488D9 /* LocalGearyCoordinator.cpp */; }; A43D31581E845C3D007488D9 /* LocalGearyMapNewView.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A43D31561E845C3D007488D9 /* LocalGearyMapNewView.cpp */; }; + A4404A02208E65DD0007753D /* wxTranslationHelper.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A4404A00208E65DC0007753D /* wxTranslationHelper.cpp */; }; + A4404A05208E9E390007753D /* lang in Resources */ = {isa = PBXBuildFile; fileRef = A4404A03208E9E380007753D /* lang */; }; + A4404A07208E9E5A0007753D /* lang in CopyFiles */ = {isa = PBXBuildFile; fileRef = A4404A03208E9E380007753D /* lang */; }; + A4404A0F209270FB0007753D /* pofiles in Resources */ = {isa = PBXBuildFile; fileRef = A4404A0E209270FB0007753D /* pofiles */; }; + A4404A12209275550007753D /* hdbscan.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A4404A10209275540007753D /* hdbscan.cpp */; }; + A4596B4E2033DB8E00C9BCC8 /* AbstractCoordinator.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A4596B4D2033DB8E00C9BCC8 /* AbstractCoordinator.cpp */; }; + A4596B512033DDFF00C9BCC8 /* AbstractClusterMap.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A4596B502033DDFF00C9BCC8 /* AbstractClusterMap.cpp */; }; A45DBDF41EDDEDAD00C2AA8A /* pca.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A45DBDF11EDDEDAD00C2AA8A /* pca.cpp */; }; A45DBDF51EDDEDAD00C2AA8A /* cluster.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A45DBDF31EDDEDAD00C2AA8A /* cluster.cpp */; }; A45DBDFA1EDDEE4D00C2AA8A /* maxp.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A45DBDF81EDDEE4D00C2AA8A /* maxp.cpp */; }; + A47614AE20759EAD00D9F3BE /* arcgis_swm.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A47614AD20759EAD00D9F3BE /* arcgis_swm.cpp */; }; + A47F792020A9F67A000AFE57 /* gpu_lisa.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A47F791E20A9F679000AFE57 /* gpu_lisa.cpp */; }; + A47F792220AA082A000AFE57 /* lisa_kernel.cl in Sources */ = {isa = PBXBuildFile; fileRef = A47F792120AA082A000AFE57 /* lisa_kernel.cl */; }; + A47F792420AA084B000AFE57 /* distmat_kernel.cl in Sources */ = {isa = PBXBuildFile; fileRef = A47F792320AA084B000AFE57 /* distmat_kernel.cl */; }; + A47F792520AA0885000AFE57 /* distmat_kernel.cl in CopyFiles */ = {isa = PBXBuildFile; fileRef = A47F792320AA084B000AFE57 /* distmat_kernel.cl */; }; + A47F792620AA0885000AFE57 /* lisa_kernel.cl in CopyFiles */ = {isa = PBXBuildFile; fileRef = A47F792120AA082A000AFE57 /* lisa_kernel.cl */; }; + A47FC9DB1F74DE1600BEFBF2 /* MLJCCoordinator.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A47FC9D91F74DE1600BEFBF2 /* MLJCCoordinator.cpp */; }; A48356BB1E456310002791C8 /* ConditionalClusterMapView.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A48356B91E456310002791C8 /* ConditionalClusterMapView.cpp */; }; + A48814EB20A50B0F005490A7 /* fastcluster.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A48814EA20A50B0F005490A7 /* fastcluster.cpp */; }; A496C99E1E6A184C008F87DD /* samples.sqlite in Resources */ = {isa = PBXBuildFile; fileRef = A496C99D1E6A184C008F87DD /* samples.sqlite */; }; A496C9A81E6A43C0008F87DD /* BaltimoreHomeSales.png in Resources */ = {isa = PBXBuildFile; fileRef = A496C9A71E6A43C0008F87DD /* BaltimoreHomeSales.png */; }; A496C9AA1E6A43CC008F87DD /* BostonHomeSales.png in Resources */ = {isa = PBXBuildFile; fileRef = A496C9A91E6A43CC008F87DD /* BostonHomeSales.png */; }; @@ -60,7 +111,27 @@ A496C9C31E6A4417008F87DD /* USHomicides.png in Resources */ = {isa = PBXBuildFile; fileRef = A496C9C21E6A4417008F87DD /* USHomicides.png */; }; A496C9C51E6A441D008F87DD /* watermark-20.png in Resources */ = {isa = PBXBuildFile; fileRef = A496C9C41E6A441D008F87DD /* watermark-20.png */; }; A49F56DD1E956FCC000309CE /* HClusterDlg.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A49F56DB1E956FCC000309CE /* HClusterDlg.cpp */; }; + A4A6AD7B207F198E00D29677 /* ShpFile.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A4A6AD7A207F198E00D29677 /* ShpFile.cpp */; }; + A4A763F41F69FB3B00EE79DD /* ColocationMapView.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A4A763F21F69FB3B00EE79DD /* ColocationMapView.cpp */; }; + A4B1F994207730FA00905246 /* matlab_mat.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A4B1F992207730FA00905246 /* matlab_mat.cpp */; }; + A4C4ABFB1F97DA2D00085D47 /* MLJCMapNewView.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A4C4ABF91F97DA2D00085D47 /* MLJCMapNewView.cpp */; }; + A4D5423D1F45037B00572878 /* redcap.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A4D5423B1F45037B00572878 /* redcap.cpp */; }; A4D9A31F1E4D5F3800EF584C /* gdaldata in Resources */ = {isa = PBXBuildFile; fileRef = A4D9A31E1E4D5F3800EF584C /* gdaldata */; }; + A4DB2CBC1EEA3A3E00BD4A54 /* Guerry.png in Resources */ = {isa = PBXBuildFile; fileRef = A4DB2CBB1EEA3A3E00BD4A54 /* Guerry.png */; }; + A4E00F1020FD8ECD0038BA80 /* localjc_kernel.cl in Sources */ = {isa = PBXBuildFile; fileRef = A4E00F0F20FD8ECC0038BA80 /* localjc_kernel.cl */; }; + A4E138B81F71A29100433256 /* geocoding.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A4E138B61F71A29100433256 /* geocoding.cpp */; }; + A4E138BB1F71D6B800433256 /* GeocodingDlg.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A4E138B91F71D6B800433256 /* GeocodingDlg.cpp */; }; + A4E5FE191F624D5600D75662 /* AggregateDlg.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A4E5FE171F624D5600D75662 /* AggregateDlg.cpp */; }; + A4ED7D442097EC55008685D6 /* ANN.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A4ED7D412097EC54008685D6 /* ANN.cpp */; }; + A4ED7D472097EDE9008685D6 /* kd_tree.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A4ED7D462097EDE9008685D6 /* kd_tree.cpp */; }; + A4ED7D542097F114008685D6 /* kNN.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A4ED7D4C2097F113008685D6 /* kNN.cpp */; }; + A4ED7D552097F114008685D6 /* kd_pr_search.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A4ED7D4E2097F113008685D6 /* kd_pr_search.cpp */; }; + A4ED7D562097F114008685D6 /* kd_search.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A4ED7D502097F114008685D6 /* kd_search.cpp */; }; + A4ED7D572097F114008685D6 /* kd_util.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A4ED7D512097F114008685D6 /* kd_util.cpp */; }; + A4ED7D582097F114008685D6 /* kd_split.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A4ED7D522097F114008685D6 /* kd_split.cpp */; }; + A4ED7D5B209A6B81008685D6 /* HDBScanDlg.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A4ED7D59209A6B81008685D6 /* HDBScanDlg.cpp */; }; + A4F5D61F1F4EA0D2007ADF25 /* AbstractClusterDlg.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A4F5D61D1F4EA0D2007ADF25 /* AbstractClusterDlg.cpp */; }; + A4F5D6221F513EA1007ADF25 /* MDSDlg.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A4F5D6201F513EA1007ADF25 /* MDSDlg.cpp */; }; A4F875771E94123F0079734E /* KMeansDlg.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A4F875751E94123F0079734E /* KMeansDlg.cpp */; }; DD00ADE811138A2C008FE572 /* TemplateFrame.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DD00ADE711138A2C008FE572 /* TemplateFrame.cpp */; }; DD0DC4BA13CBA7B10022B65A /* RangeSelectionDlg.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DD0DC4B813CBA7B10022B65A /* RangeSelectionDlg.cpp */; }; @@ -72,7 +143,6 @@ DD209598139F129900B9E648 /* GetisOrdChoiceDlg.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DD209596139F129900B9E648 /* GetisOrdChoiceDlg.cpp */; }; DD26CBE419A41A480092C0F2 /* WebViewExampleWin.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DD26CBE219A41A480092C0F2 /* WebViewExampleWin.cpp */; }; DD27ECBC0F2E43B5009C5C42 /* GenUtils.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DD64A7240F2E26AA006B1E6D /* GenUtils.cpp */; }; - DD27EF050F2F6CBE009C5C42 /* ShapeFile.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DD27EF040F2F6CBE009C5C42 /* ShapeFile.cpp */; }; DD2A6FE0178C7F7C00197093 /* DataSource.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DD2A6FDE178C7F7C00197093 /* DataSource.cpp */; }; DD2AE42A19D4F4CA00B23FB9 /* GdaJson.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DD2AE42919D4F4CA00B23FB9 /* GdaJson.cpp */; }; DD2B42B11522552B00888E51 /* BoxNewPlotView.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DD2B42AF1522552B00888E51 /* BoxNewPlotView.cpp */; }; @@ -90,7 +160,6 @@ DD409E4C19FFD43000C21A2B /* VarTools.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DD409E4A19FFD43000C21A2B /* VarTools.cpp */; }; DD40B083181894F20084173C /* VarGroupingEditorDlg.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DD40B081181894F20084173C /* VarGroupingEditorDlg.cpp */; }; DD45117119E5F65E006C5DAA /* geoda_prefs.sqlite in CopyFiles */ = {isa = PBXBuildFile; fileRef = DD45117019E5F65E006C5DAA /* geoda_prefs.sqlite */; }; - DD49747A176F59670007BB9F /* DbfTable.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DD497479176F59670007BB9F /* DbfTable.cpp */; }; DD4974B71770AC700007BB9F /* TableFrame.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DD4974B61770AC700007BB9F /* TableFrame.cpp */; }; DD4974BA1770AC840007BB9F /* TableBase.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DD4974B91770AC840007BB9F /* TableBase.cpp */; }; DD4974E21770CE9E0007BB9F /* TableInterface.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DD4974E11770CE9E0007BB9F /* TableInterface.cpp */; }; @@ -99,13 +168,11 @@ DD579B6A160BDAFE00BF8D53 /* DorlingCartogram.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DD579B68160BDAFE00BF8D53 /* DorlingCartogram.cpp */; }; DD5A579716E53EC40047DBB1 /* GeoDa.icns in Resources */ = {isa = PBXBuildFile; fileRef = DD5A579616E53EC40047DBB1 /* GeoDa.icns */; }; DD5AA73D1982D200009B30C6 /* CalcHelp.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DD5AA73B1982D200009B30C6 /* CalcHelp.cpp */; }; - DD5FA1DA0F320DD50055A0E5 /* ShapeFileHdr.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DD5FA1D90F320DD50055A0E5 /* ShapeFileHdr.cpp */; }; DD60546816A83EEF0004BF02 /* CatClassifManager.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DD60546616A83EEF0004BF02 /* CatClassifManager.cpp */; }; DD6456CA14881EA700AABF59 /* TimeChooserDlg.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DD6456C714881EA700AABF59 /* TimeChooserDlg.cpp */; }; DD64925C16DFF63400B3B0AB /* GeoDa.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DD64925A16DFF63400B3B0AB /* GeoDa.cpp */; }; DD64A2880F20FE06006B1E6D /* GeneralWxUtils.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DD64A2860F20FE06006B1E6D /* GeneralWxUtils.cpp */; }; DD64A5580F2910D2006B1E6D /* logger.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DD64A5570F2910D2006B1E6D /* logger.cpp */; }; - DD64A6AD0F2A7A81006B1E6D /* DBF.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DD64A6AC0F2A7A81006B1E6D /* DBF.cpp */; }; DD694685130307C00072386B /* RateSmoothing.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DD694684130307C00072386B /* RateSmoothing.cpp */; }; DD6B7289141A61400026D223 /* FramesManager.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DD6B7288141A61400026D223 /* FramesManager.cpp */; }; DD6C9EB61A03FD0C00F124F1 /* VarsChooserDlg.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DD6C9EB11A03FD0C00F124F1 /* VarsChooserDlg.cpp */; }; @@ -119,7 +186,6 @@ DD76D15A1A15430600A01FA5 /* LineChartCanvas.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DD76D1581A15430600A01FA5 /* LineChartCanvas.cpp */; }; DD7974C80F1D250A00496A84 /* TemplateCanvas.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DD7974C30F1D250A00496A84 /* TemplateCanvas.cpp */; }; DD7975670F1D296F00496A84 /* 3DControlPan.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DD7974FF0F1D296F00496A84 /* 3DControlPan.cpp */; }; - DD79756C0F1D296F00496A84 /* ASC2SHPDlg.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DD7975090F1D296F00496A84 /* ASC2SHPDlg.cpp */; }; DD79756D0F1D296F00496A84 /* Bnd2ShpDlg.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DD79750B0F1D296F00496A84 /* Bnd2ShpDlg.cpp */; }; DD7975700F1D296F00496A84 /* CreateGridDlg.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DD7975110F1D296F00496A84 /* CreateGridDlg.cpp */; }; DD7975710F1D296F00496A84 /* CreatingWeightDlg.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DD7975130F1D296F00496A84 /* CreatingWeightDlg.cpp */; }; @@ -131,7 +197,6 @@ DD7975890F1D296F00496A84 /* RegressionDlg.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DD7975430F1D296F00496A84 /* RegressionDlg.cpp */; }; DD79758B0F1D296F00496A84 /* RegressionReportDlg.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DD7975470F1D296F00496A84 /* RegressionReportDlg.cpp */; }; DD7975920F1D296F00496A84 /* SaveSelectionDlg.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DD7975550F1D296F00496A84 /* SaveSelectionDlg.cpp */; }; - DD7975940F1D296F00496A84 /* SHP2ASCDlg.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DD7975590F1D296F00496A84 /* SHP2ASCDlg.cpp */; }; DD7975980F1D296F00496A84 /* VariableSettingsDlg.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DD7975610F1D296F00496A84 /* VariableSettingsDlg.cpp */; }; DD7975D20F1D2A9000496A84 /* 3DPlotView.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DD7975B80F1D2A9000496A84 /* 3DPlotView.cpp */; }; DD7975D60F1D2A9000496A84 /* Geom3D.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DD7975C00F1D2A9000496A84 /* Geom3D.cpp */; }; @@ -162,20 +227,17 @@ DD89C87613D86BC7006C068D /* FieldNewCalcRateDlg.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DD89C86E13D86BC7006C068D /* FieldNewCalcRateDlg.cpp */; }; DD89C87713D86BC7006C068D /* FieldNewCalcSheetDlg.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DD89C87013D86BC7006C068D /* FieldNewCalcSheetDlg.cpp */; }; DD89C87813D86BC7006C068D /* FieldNewCalcUniDlg.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DD89C87213D86BC7006C068D /* FieldNewCalcUniDlg.cpp */; }; - DD8DCE0E19C0FD8F00E62C3D /* DataChangeType.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DD8DCE0C19C0FD8F00E62C3D /* DataChangeType.cpp */; }; DD8FACE11649595D007598CE /* DataMovieDlg.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DD8FACDF1649595D007598CE /* DataMovieDlg.cpp */; }; DD92851C17F5FC7300B9481A /* VarOrderPtree.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DD92851A17F5FC7300B9481A /* VarOrderPtree.cpp */; }; DD92851F17F5FD4500B9481A /* VarOrderMapper.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DD92851D17F5FD4500B9481A /* VarOrderMapper.cpp */; }; DD92853D17F5FE2E00B9481A /* VarGroup.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DD92853B17F5FE2E00B9481A /* VarGroup.cpp */; }; DD92D22417BAAF2300F8FE01 /* TimeEditorDlg.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DD92D22317BAAF2300F8FE01 /* TimeEditorDlg.cpp */; }; - DD9373B61AC1F99D0066AF21 /* SimplePoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DD9373B41AC1F99D0066AF21 /* SimplePoint.cpp */; }; DD9373F71AC1FEAA0066AF21 /* PolysToContigWeights.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DD9373F51AC1FEAA0066AF21 /* PolysToContigWeights.cpp */; }; DD9C1B371910267900C0A427 /* GdaConst.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DD9C1B351910267900C0A427 /* GdaConst.cpp */; }; DDA462FF164D785500EBBD8F /* TableState.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DDA462FC164D785500EBBD8F /* TableState.cpp */; }; DDA4F0A4196311A9007645E2 /* WeightsMetaInfo.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DDA4F0A3196311A9007645E2 /* WeightsMetaInfo.cpp */; }; DDA4F0AD196315AF007645E2 /* WeightUtils.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DDA4F0AB196315AF007645E2 /* WeightUtils.cpp */; }; DDA8D55214479228008156FB /* ScatterNewPlotView.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DD99BA1911D3F8D6003BB40E /* ScatterNewPlotView.cpp */; }; - DDA8D5681447948B008156FB /* ShapeUtils.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DDDC11EB1159783700E515BB /* ShapeUtils.cpp */; }; DDAA6540117F9B5D00D1010C /* Project.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DDAA653F117F9B5D00D1010C /* Project.cpp */; }; DDAD0218162754EA00748874 /* ConditionalNewView.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DDAD0216162754EA00748874 /* ConditionalNewView.cpp */; }; DDB0E42C10B34DBB00F96D57 /* AddIdVariable.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DDB0E42A10B34DBB00F96D57 /* AddIdVariable.cpp */; }; @@ -192,12 +254,7 @@ DDC9DD8A15937B2F00A0E5BA /* CsvFileUtils.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DDC9DD8815937B2F00A0E5BA /* CsvFileUtils.cpp */; }; DDC9DD9C15937C0200A0E5BA /* ImportCsvDlg.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DDC9DD9A15937C0200A0E5BA /* ImportCsvDlg.cpp */; }; DDCCB5CC1AD47C200067D6C4 /* SimpleBinsHistCanvas.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DDCCB5CA1AD47C200067D6C4 /* SimpleBinsHistCanvas.cpp */; }; - DDCFA9961A96790100747EB7 /* DbfFile.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DDCFA9941A96790100747EB7 /* DbfFile.cpp */; }; DDD13F060F2F8BE1009F7F13 /* GenGeomAlgs.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DDD13F050F2F8BE1009F7F13 /* GenGeomAlgs.cpp */; }; - DDD13F6F0F2FC802009F7F13 /* ShapeFileTriplet.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DDD13F6E0F2FC802009F7F13 /* ShapeFileTriplet.cpp */; }; - DDD13F930F2FD641009F7F13 /* BasePoint.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DDD13F920F2FD641009F7F13 /* BasePoint.cpp */; }; - DDD13FAB0F30B2E4009F7F13 /* Box.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DDD13FAA0F30B2E4009F7F13 /* Box.cpp */; }; - DDD140540F310324009F7F13 /* AbstractShape.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DDD140530F310324009F7F13 /* AbstractShape.cpp */; }; DDD2392D1AB86D8F00E4E1BF /* NumericTests.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DDD2392B1AB86D8F00E4E1BF /* NumericTests.cpp */; }; DDD593AC12E9F34C00F7A7C4 /* GeodaWeight.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DDD593AB12E9F34C00F7A7C4 /* GeodaWeight.cpp */; }; DDD593B012E9F42100F7A7C4 /* WeightsManager.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DDD593AF12E9F42100F7A7C4 /* WeightsManager.cpp */; }; @@ -208,7 +265,6 @@ DDDBF2AE163AD3AB0070610C /* ConditionalHistogramView.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DDDBF2AC163AD3AB0070610C /* ConditionalHistogramView.cpp */; }; DDE3F5081677C46500D13A2C /* CatClassification.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DDE3F5061677C46500D13A2C /* CatClassification.cpp */; }; DDE4DFD61A963B07005B9158 /* GdaShape.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DDE4DFD41A963B07005B9158 /* GdaShape.cpp */; }; - DDE4DFE91A96411A005B9158 /* ShpFile.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DDE4DFE71A96411A005B9158 /* ShpFile.cpp */; }; DDEA3CBD193CEE5C0028B746 /* GdaFlexValue.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DDEA3CB7193CEE5C0028B746 /* GdaFlexValue.cpp */; }; DDEA3CBE193CEE5C0028B746 /* GdaLexer.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DDEA3CB9193CEE5C0028B746 /* GdaLexer.cpp */; }; DDEA3CBF193CEE5C0028B746 /* GdaParser.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DDEA3CBB193CEE5C0028B746 /* GdaParser.cpp */; }; @@ -222,7 +278,6 @@ DDF53FF3167A39520042B453 /* CatClassifState.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DDF53FF0167A39520042B453 /* CatClassifState.cpp */; }; DDF5400B167A39CA0042B453 /* CatClassifDlg.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DDF54009167A39CA0042B453 /* CatClassifDlg.cpp */; }; DDF85D1813B257B6006C1B08 /* DataViewerEditFieldPropertiesDlg.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DDF85D1613B257B6006C1B08 /* DataViewerEditFieldPropertiesDlg.cpp */; }; - DDFE0E0917502E810099FFEC /* DbfColContainer.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DDFE0E0817502E810099FFEC /* DbfColContainer.cpp */; }; DDFE0E2A175034EC0099FFEC /* TimeState.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DDFE0E27175034EC0099FFEC /* TimeState.cpp */; }; DDFFC7CC1AC0E58B00F7DD6D /* CorrelogramView.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DDFFC7C51AC0E58B00F7DD6D /* CorrelogramView.cpp */; }; DDFFC7CD1AC0E58B00F7DD6D /* CorrelParamsObservable.cpp in Sources */ = {isa = PBXBuildFile; fileRef = DDFFC7C71AC0E58B00F7DD6D /* CorrelParamsObservable.cpp */; }; @@ -237,6 +292,10 @@ dstPath = ""; dstSubfolderSpec = 6; files = ( + A1311C6720FFDF7100008D7F /* localjc_kernel.cl in CopyFiles */, + A47F792520AA0885000AFE57 /* distmat_kernel.cl in CopyFiles */, + A47F792620AA0885000AFE57 /* lisa_kernel.cl in CopyFiles */, + A4404A07208E9E5A0007753D /* lang in CopyFiles */, DD2EB10219E6F0270073E36F /* geoda_prefs.json in CopyFiles */, A1B04ADD1B1921710045AA6F /* basemap_cache in CopyFiles */, A1F1BA99178D46B8005A46E5 /* cache.sqlite in CopyFiles */, @@ -247,12 +306,20 @@ /* End PBXCopyFilesBuildPhase section */ /* Begin PBXFileReference section */ + A10EF2EE21273E7E00564FE1 /* AbstractCanvas.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = AbstractCanvas.cpp; sourceTree = ""; }; + A10EF2EF21273E7E00564FE1 /* AbstractCanvas.hpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.h; path = AbstractCanvas.hpp; sourceTree = ""; }; A11B85BA1B18DC89008B64EA /* Basemap.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Basemap.h; sourceTree = ""; }; A11B85BB1B18DC9C008B64EA /* Basemap.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Basemap.cpp; sourceTree = ""; }; A11F1B7D184FDFB3006F5F98 /* OGRColumn.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = OGRColumn.cpp; path = DataViewer/OGRColumn.cpp; sourceTree = ""; }; A11F1B7E184FDFB3006F5F98 /* OGRColumn.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = OGRColumn.h; path = DataViewer/OGRColumn.h; sourceTree = ""; }; A11F1B801850437A006F5F98 /* OGRTableOperation.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = OGRTableOperation.cpp; path = DataViewer/OGRTableOperation.cpp; sourceTree = ""; }; A11F1B811850437A006F5F98 /* OGRTableOperation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = OGRTableOperation.h; path = DataViewer/OGRTableOperation.h; sourceTree = ""; }; + A1230E5C212DF54C002AB30A /* switch-on.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; name = "switch-on.png"; path = "BuildTools/CommonDistFiles/web_plugins/switch-on.png"; sourceTree = ""; }; + A1230E5D212DF54D002AB30A /* switch-off.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; name = "switch-off.png"; path = "BuildTools/CommonDistFiles/web_plugins/switch-off.png"; sourceTree = ""; }; + A1230E602130E783002AB30A /* MapLayer.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = MapLayer.cpp; sourceTree = ""; }; + A1230E612130E783002AB30A /* MapLayer.hpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.h; path = MapLayer.hpp; sourceTree = ""; }; + A1230E632130E81A002AB30A /* MapLayerTree.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = MapLayerTree.cpp; sourceTree = ""; }; + A1230E642130E81A002AB30A /* MapLayerTree.hpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.h; path = MapLayerTree.hpp; sourceTree = ""; }; A12E0F4D1705087A00B6059C /* OGRDataAdapter.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = OGRDataAdapter.h; sourceTree = ""; }; A12E0F4E1705087A00B6059C /* OGRDataAdapter.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = OGRDataAdapter.cpp; sourceTree = ""; }; A13B6B9218760CF100F93ACF /* SaveAsDlg.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SaveAsDlg.h; sourceTree = ""; }; @@ -265,6 +332,38 @@ A17336821C06917B00579354 /* WeightsManInterface.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = WeightsManInterface.h; path = VarCalc/WeightsManInterface.h; sourceTree = ""; }; A186F09F1C16508A00AEBA13 /* GdaCartoDB.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = GdaCartoDB.cpp; sourceTree = ""; }; A186F0A01C16508A00AEBA13 /* GdaCartoDB.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GdaCartoDB.h; sourceTree = ""; }; + A1894C3D213F29DC00718FFC /* SpatialJoinDlg.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = SpatialJoinDlg.cpp; sourceTree = ""; }; + A1894C3E213F29DC00718FFC /* SpatialJoinDlg.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = SpatialJoinDlg.h; sourceTree = ""; }; + A1894C41213F806700718FFC /* MapLayerStateObserver.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MapLayerStateObserver.h; sourceTree = ""; }; + A19483782118BAA7009A87A2 /* ogldiag.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ogldiag.h; sourceTree = ""; }; + A19483792118BAA7009A87A2 /* composit.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = composit.h; sourceTree = ""; }; + A194837A2118BAA7009A87A2 /* composit.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = composit.cpp; sourceTree = ""; }; + A194837B2118BAA7009A87A2 /* misc.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = misc.h; sourceTree = ""; }; + A194837C2118BAA7009A87A2 /* linesp.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = linesp.h; sourceTree = ""; }; + A194837D2118BAA7009A87A2 /* mfutils.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = mfutils.h; sourceTree = ""; }; + A194837E2118BAA7009A87A2 /* divided.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = divided.cpp; sourceTree = ""; }; + A194837F2118BAA7009A87A2 /* constrnt.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = constrnt.cpp; sourceTree = ""; }; + A19483802118BAA8009A87A2 /* divided.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = divided.h; sourceTree = ""; }; + A19483812118BAA8009A87A2 /* oglmisc.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = oglmisc.cpp; sourceTree = ""; }; + A19483822118BAA8009A87A2 /* drawnp.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = drawnp.h; sourceTree = ""; }; + A19483832118BAA8009A87A2 /* basicp.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = basicp.h; sourceTree = ""; }; + A19483842118BAA8009A87A2 /* bmpshape.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = bmpshape.h; sourceTree = ""; }; + A19483852118BAA8009A87A2 /* bmpshape.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = bmpshape.cpp; sourceTree = ""; }; + A19483862118BAA8009A87A2 /* basic.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = basic.cpp; sourceTree = ""; }; + A19483872118BAA8009A87A2 /* canvas.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = canvas.cpp; sourceTree = ""; }; + A19483882118BAA9009A87A2 /* lines.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = lines.cpp; sourceTree = ""; }; + A19483892118BAA9009A87A2 /* basic2.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = basic2.cpp; sourceTree = ""; }; + A194838A2118BAA9009A87A2 /* mfutils.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = mfutils.cpp; sourceTree = ""; }; + A194838B2118BAA9009A87A2 /* basic.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = basic.h; sourceTree = ""; }; + A194838C2118BAA9009A87A2 /* drawn.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = drawn.cpp; sourceTree = ""; }; + A194838D2118BAA9009A87A2 /* ogl.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ogl.h; sourceTree = ""; }; + A194838E2118BAA9009A87A2 /* constrnt.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = constrnt.h; sourceTree = ""; }; + A194838F2118BAAA009A87A2 /* canvas.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = canvas.h; sourceTree = ""; }; + A19483902118BAAA009A87A2 /* lines.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = lines.h; sourceTree = ""; }; + A19483912118BAAA009A87A2 /* ogldiag.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ogldiag.cpp; sourceTree = ""; }; + A19483922118BAAA009A87A2 /* drawn.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = drawn.h; sourceTree = ""; }; + A19483A02118BE8E009A87A2 /* MapLayoutView.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = MapLayoutView.cpp; sourceTree = ""; }; + A19483A12118BE8F009A87A2 /* MapLayoutView.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MapLayoutView.h; sourceTree = ""; }; A19F514D1756A11E006E31B4 /* plugins */ = {isa = PBXFileReference; lastKnownFileType = folder; name = plugins; path = BuildTools/macosx/plugins; sourceTree = ""; }; A1AC05BD1C8645F300B6FE5F /* AdjustYAxisDlg.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = AdjustYAxisDlg.cpp; sourceTree = ""; }; A1AC05BE1C8645F300B6FE5F /* AdjustYAxisDlg.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AdjustYAxisDlg.h; sourceTree = ""; }; @@ -304,19 +403,74 @@ A1F1BA98178D46B8005A46E5 /* cache.sqlite */ = {isa = PBXFileReference; lastKnownFileType = file; name = cache.sqlite; path = BuildTools/CommonDistFiles/cache.sqlite; sourceTree = ""; }; A1FD8C17186908B800C35C41 /* CustomClassifPtree.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = CustomClassifPtree.cpp; path = DataViewer/CustomClassifPtree.cpp; sourceTree = ""; }; A1FD8C18186908B800C35C41 /* CustomClassifPtree.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = CustomClassifPtree.h; path = DataViewer/CustomClassifPtree.h; sourceTree = ""; }; + A40A6A7C20226B3B003CDD79 /* PreferenceDlg.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PreferenceDlg.h; sourceTree = ""; }; + A40A6A7D20226B3B003CDD79 /* PreferenceDlg.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = PreferenceDlg.cpp; sourceTree = ""; }; + A40AB91F20F559F500F94543 /* scatterplot.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = scatterplot.h; sourceTree = ""; }; + A40AB92020F559F500F94543 /* scatterplot.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = scatterplot.cpp; sourceTree = ""; }; + A40AB92220F675B500F94543 /* mathstuff.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = mathstuff.h; sourceTree = ""; }; + A40AB92320F675B600F94543 /* oglpfuncs.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = oglpfuncs.h; sourceTree = ""; }; + A40AB92420F675B600F94543 /* mathstuff.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = mathstuff.cpp; sourceTree = ""; }; + A40AB92520F675B600F94543 /* oglstuff.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = oglstuff.cpp; sourceTree = ""; }; + A40AB92620F675B600F94543 /* oglstuff.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = oglstuff.h; sourceTree = ""; }; + A40AB92720F675B600F94543 /* oglpfuncs.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = oglpfuncs.cpp; sourceTree = ""; }; + A414C889207BED2700520546 /* MatfileReader.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = MatfileReader.h; path = io/MatfileReader.h; sourceTree = ""; }; + A414C88A207BED2700520546 /* MatfileReader.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = MatfileReader.cpp; path = io/MatfileReader.cpp; sourceTree = ""; }; + A416A1751F84122B001F2884 /* PCASettingsDlg.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = PCASettingsDlg.cpp; sourceTree = ""; }; + A416A1761F84122B001F2884 /* PCASettingsDlg.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PCASettingsDlg.h; sourceTree = ""; }; + A42018011FB3C0AC0029709C /* skater.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = skater.cpp; path = Algorithms/skater.cpp; sourceTree = ""; }; + A42018021FB3C0AC0029709C /* skater.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = skater.h; path = Algorithms/skater.h; sourceTree = ""; }; + A42018041FB4CF980029709C /* SkaterDlg.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SkaterDlg.h; sourceTree = ""; }; + A42018051FB4CF980029709C /* SkaterDlg.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = SkaterDlg.cpp; sourceTree = ""; }; + A42B6F761F666C57004AFAB8 /* FieldNewCalcDateTimeDlg.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = FieldNewCalcDateTimeDlg.cpp; sourceTree = ""; }; + A42B6F771F666C57004AFAB8 /* FieldNewCalcDateTimeDlg.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FieldNewCalcDateTimeDlg.h; sourceTree = ""; }; + A4320FC61F4735020007BE0D /* RedcapDlg.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = RedcapDlg.cpp; sourceTree = ""; }; + A4320FC71F4735020007BE0D /* RedcapDlg.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RedcapDlg.h; sourceTree = ""; }; + A432E84620A672EA007B8B25 /* distmatrix.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = distmatrix.cpp; path = Algorithms/distmatrix.cpp; sourceTree = ""; }; + A432E84820A674F7007B8B25 /* distmatrix.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = distmatrix.h; path = Algorithms/distmatrix.h; sourceTree = ""; }; + A4368CD91FABB5260099FA9B /* DataUtils.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = DataUtils.h; path = Algorithms/DataUtils.h; sourceTree = ""; }; + A4368CDA1FABBBC60099FA9B /* mds.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = mds.cpp; path = Algorithms/mds.cpp; sourceTree = ""; }; + A4368CDB1FABBBC60099FA9B /* mds.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = mds.h; path = Algorithms/mds.h; sourceTree = ""; }; + A43D124A1F1DE1D80073D408 /* MaxpDlg.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = MaxpDlg.cpp; sourceTree = ""; }; + A43D124B1F1DE1D80073D408 /* MaxpDlg.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MaxpDlg.h; sourceTree = ""; }; + A43D124D1F2088D50073D408 /* spectral.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = spectral.h; path = Algorithms/spectral.h; sourceTree = ""; }; + A43D124E1F2088D50073D408 /* spectral.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = spectral.cpp; path = Algorithms/spectral.cpp; sourceTree = ""; }; + A43D12501F20AE450073D408 /* SpectralClusteringDlg.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SpectralClusteringDlg.h; sourceTree = ""; }; + A43D12511F20AE450073D408 /* SpectralClusteringDlg.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = SpectralClusteringDlg.cpp; sourceTree = ""; }; A43D31521E845985007488D9 /* LocalGearyCoordinator.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = LocalGearyCoordinator.cpp; sourceTree = ""; }; A43D31531E845985007488D9 /* LocalGearyCoordinator.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = LocalGearyCoordinator.h; sourceTree = ""; }; A43D31551E845A0C007488D9 /* LocalGearyCoordinatorObserver.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = LocalGearyCoordinatorObserver.h; sourceTree = ""; }; A43D31561E845C3D007488D9 /* LocalGearyMapNewView.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = LocalGearyMapNewView.cpp; sourceTree = ""; }; A43D31571E845C3D007488D9 /* LocalGearyMapNewView.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = LocalGearyMapNewView.h; sourceTree = ""; }; + A4404A00208E65DC0007753D /* wxTranslationHelper.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = wxTranslationHelper.cpp; sourceTree = ""; }; + A4404A01208E65DD0007753D /* wxTranslationHelper.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = wxTranslationHelper.h; sourceTree = ""; }; + A4404A03208E9E380007753D /* lang */ = {isa = PBXFileReference; lastKnownFileType = folder; path = lang; sourceTree = ""; }; + A4404A0E209270FB0007753D /* pofiles */ = {isa = PBXFileReference; lastKnownFileType = folder; path = pofiles; sourceTree = ""; }; + A4404A10209275540007753D /* hdbscan.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = hdbscan.cpp; path = Algorithms/hdbscan.cpp; sourceTree = ""; }; + A4404A11209275550007753D /* hdbscan.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = hdbscan.h; path = Algorithms/hdbscan.h; sourceTree = ""; }; + A4596B4C2033D8F600C9BCC8 /* AbstractCoordinator.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AbstractCoordinator.h; sourceTree = ""; }; + A4596B4D2033DB8E00C9BCC8 /* AbstractCoordinator.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = AbstractCoordinator.cpp; sourceTree = ""; }; + A4596B4F2033DDFF00C9BCC8 /* AbstractClusterMap.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AbstractClusterMap.h; sourceTree = ""; }; + A4596B502033DDFF00C9BCC8 /* AbstractClusterMap.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = AbstractClusterMap.cpp; sourceTree = ""; }; A45DBDF01EDDEDAD00C2AA8A /* pca.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = pca.h; path = Algorithms/pca.h; sourceTree = ""; }; A45DBDF11EDDEDAD00C2AA8A /* pca.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = pca.cpp; path = Algorithms/pca.cpp; sourceTree = ""; }; A45DBDF21EDDEDAD00C2AA8A /* cluster.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = cluster.h; path = Algorithms/cluster.h; sourceTree = ""; }; A45DBDF31EDDEDAD00C2AA8A /* cluster.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = cluster.cpp; path = Algorithms/cluster.cpp; sourceTree = ""; }; A45DBDF81EDDEE4D00C2AA8A /* maxp.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = maxp.cpp; path = Algorithms/maxp.cpp; sourceTree = ""; }; A45DBDF91EDDEE4D00C2AA8A /* maxp.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = maxp.h; path = Algorithms/maxp.h; sourceTree = ""; }; + A46DFA8F1FA92145007F5923 /* texttable.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = texttable.h; path = Algorithms/texttable.h; sourceTree = ""; }; + A47533BC20A3BD5000695283 /* fastcluster.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = fastcluster.h; path = Algorithms/fastcluster.h; sourceTree = ""; }; + A47614AB20759E5600D9F3BE /* arcgis_swm.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = arcgis_swm.h; path = io/arcgis_swm.h; sourceTree = ""; }; + A47614AD20759EAD00D9F3BE /* arcgis_swm.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = arcgis_swm.cpp; path = io/arcgis_swm.cpp; sourceTree = ""; }; + A47F791E20A9F679000AFE57 /* gpu_lisa.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = gpu_lisa.cpp; path = Algorithms/gpu_lisa.cpp; sourceTree = ""; }; + A47F791F20A9F67A000AFE57 /* gpu_lisa.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = gpu_lisa.h; path = Algorithms/gpu_lisa.h; sourceTree = ""; }; + A47F792120AA082A000AFE57 /* lisa_kernel.cl */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.opencl; name = lisa_kernel.cl; path = Algorithms/lisa_kernel.cl; sourceTree = ""; }; + A47F792320AA084B000AFE57 /* distmat_kernel.cl */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.opencl; name = distmat_kernel.cl; path = Algorithms/distmat_kernel.cl; sourceTree = ""; }; + A47FC9D91F74DE1600BEFBF2 /* MLJCCoordinator.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = MLJCCoordinator.cpp; sourceTree = ""; }; + A47FC9DA1F74DE1600BEFBF2 /* MLJCCoordinator.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MLJCCoordinator.h; sourceTree = ""; }; + A47FC9DC1F74E31800BEFBF2 /* MLJCCoordinatorObserver.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MLJCCoordinatorObserver.h; sourceTree = ""; }; A48356B91E456310002791C8 /* ConditionalClusterMapView.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ConditionalClusterMapView.cpp; sourceTree = ""; }; A48356BA1E456310002791C8 /* ConditionalClusterMapView.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ConditionalClusterMapView.h; sourceTree = ""; }; + A48814EA20A50B0F005490A7 /* fastcluster.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = fastcluster.cpp; path = Algorithms/fastcluster.cpp; sourceTree = ""; }; A496C99D1E6A184C008F87DD /* samples.sqlite */ = {isa = PBXFileReference; lastKnownFileType = file; name = samples.sqlite; path = BuildTools/CommonDistFiles/web_plugins/samples.sqlite; sourceTree = ""; }; A496C9A71E6A43C0008F87DD /* BaltimoreHomeSales.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; name = BaltimoreHomeSales.png; path = BuildTools/CommonDistFiles/web_plugins/BaltimoreHomeSales.png; sourceTree = ""; }; A496C9A91E6A43CC008F87DD /* BostonHomeSales.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; name = BostonHomeSales.png; path = BuildTools/CommonDistFiles/web_plugins/BostonHomeSales.png; sourceTree = ""; }; @@ -336,7 +490,50 @@ A496C9C41E6A441D008F87DD /* watermark-20.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; name = "watermark-20.png"; path = "BuildTools/CommonDistFiles/web_plugins/watermark-20.png"; sourceTree = ""; }; A49F56DB1E956FCC000309CE /* HClusterDlg.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = HClusterDlg.cpp; sourceTree = ""; }; A49F56DC1E956FCC000309CE /* HClusterDlg.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HClusterDlg.h; sourceTree = ""; }; + A4A6AD79207F198D00D29677 /* ShpFile.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ShpFile.h; sourceTree = ""; }; + A4A6AD7A207F198E00D29677 /* ShpFile.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ShpFile.cpp; sourceTree = ""; }; + A4A763F21F69FB3B00EE79DD /* ColocationMapView.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ColocationMapView.cpp; sourceTree = ""; }; + A4A763F31F69FB3B00EE79DD /* ColocationMapView.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ColocationMapView.h; sourceTree = ""; }; + A4B1F992207730FA00905246 /* matlab_mat.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = matlab_mat.cpp; path = io/matlab_mat.cpp; sourceTree = ""; }; + A4B1F9952077311F00905246 /* matlab_mat.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = matlab_mat.h; path = io/matlab_mat.h; sourceTree = ""; }; + A4B1F99620783CC100905246 /* weights_interface.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = weights_interface.h; path = io/weights_interface.h; sourceTree = ""; }; + A4C4ABF91F97DA2D00085D47 /* MLJCMapNewView.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = MLJCMapNewView.cpp; sourceTree = ""; }; + A4C4ABFA1F97DA2D00085D47 /* MLJCMapNewView.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MLJCMapNewView.h; sourceTree = ""; }; + A4D5423B1F45037B00572878 /* redcap.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = redcap.cpp; path = Algorithms/redcap.cpp; sourceTree = ""; }; + A4D5423C1F45037B00572878 /* redcap.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = redcap.h; path = Algorithms/redcap.h; sourceTree = ""; }; A4D9A31E1E4D5F3800EF584C /* gdaldata */ = {isa = PBXFileReference; lastKnownFileType = folder; name = gdaldata; path = BuildTools/CommonDistFiles/gdaldata; sourceTree = ""; }; + A4DB2CBB1EEA3A3E00BD4A54 /* Guerry.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; name = Guerry.png; path = BuildTools/CommonDistFiles/web_plugins/Guerry.png; sourceTree = ""; }; + A4E00F0F20FD8ECC0038BA80 /* localjc_kernel.cl */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.opencl; name = localjc_kernel.cl; path = Algorithms/localjc_kernel.cl; sourceTree = ""; }; + A4E138B61F71A29100433256 /* geocoding.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = geocoding.cpp; path = Algorithms/geocoding.cpp; sourceTree = ""; }; + A4E138B71F71A29100433256 /* geocoding.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = geocoding.h; path = Algorithms/geocoding.h; sourceTree = ""; }; + A4E138B91F71D6B800433256 /* GeocodingDlg.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = GeocodingDlg.cpp; sourceTree = ""; }; + A4E138BA1F71D6B800433256 /* GeocodingDlg.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GeocodingDlg.h; sourceTree = ""; }; + A4E5FE171F624D5600D75662 /* AggregateDlg.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = AggregateDlg.cpp; sourceTree = ""; }; + A4E5FE181F624D5600D75662 /* AggregateDlg.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AggregateDlg.h; sourceTree = ""; }; + A4ED7D402097EC54008685D6 /* ANNx.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = ANNx.h; path = ../kNN/ANNx.h; sourceTree = ""; }; + A4ED7D412097EC54008685D6 /* ANN.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = ANN.cpp; path = ../kNN/ANN.cpp; sourceTree = ""; }; + A4ED7D422097EC54008685D6 /* ANNperf.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = ANNperf.h; path = ../kNN/ANNperf.h; sourceTree = ""; }; + A4ED7D432097EC55008685D6 /* ANN.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = ANN.h; path = ../kNN/ANN.h; sourceTree = ""; }; + A4ED7D452097ECC6008685D6 /* values.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = values.h; sourceTree = ""; }; + A4ED7D462097EDE9008685D6 /* kd_tree.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = kd_tree.cpp; sourceTree = ""; }; + A4ED7D482097F113008685D6 /* kd_tree.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = kd_tree.h; sourceTree = ""; }; + A4ED7D492097F113008685D6 /* kd_search.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = kd_search.h; sourceTree = ""; }; + A4ED7D4A2097F113008685D6 /* kd_pr_search.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = kd_pr_search.h; sourceTree = ""; }; + A4ED7D4B2097F113008685D6 /* kd_util.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = kd_util.h; sourceTree = ""; }; + A4ED7D4C2097F113008685D6 /* kNN.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = kNN.cpp; sourceTree = ""; }; + A4ED7D4D2097F113008685D6 /* pr_queue_k.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = pr_queue_k.h; sourceTree = ""; }; + A4ED7D4E2097F113008685D6 /* kd_pr_search.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = kd_pr_search.cpp; sourceTree = ""; }; + A4ED7D4F2097F113008685D6 /* pr_queue.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = pr_queue.h; sourceTree = ""; }; + A4ED7D502097F114008685D6 /* kd_search.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = kd_search.cpp; sourceTree = ""; }; + A4ED7D512097F114008685D6 /* kd_util.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = kd_util.cpp; sourceTree = ""; }; + A4ED7D522097F114008685D6 /* kd_split.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = kd_split.cpp; sourceTree = ""; }; + A4ED7D532097F114008685D6 /* kd_split.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = kd_split.h; sourceTree = ""; }; + A4ED7D59209A6B81008685D6 /* HDBScanDlg.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = HDBScanDlg.cpp; sourceTree = ""; }; + A4ED7D5A209A6B81008685D6 /* HDBScanDlg.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HDBScanDlg.h; sourceTree = ""; }; + A4F5D61D1F4EA0D2007ADF25 /* AbstractClusterDlg.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = AbstractClusterDlg.cpp; sourceTree = ""; }; + A4F5D61E1F4EA0D2007ADF25 /* AbstractClusterDlg.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AbstractClusterDlg.h; sourceTree = ""; }; + A4F5D6201F513EA1007ADF25 /* MDSDlg.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = MDSDlg.cpp; sourceTree = ""; }; + A4F5D6211F513EA1007ADF25 /* MDSDlg.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MDSDlg.h; sourceTree = ""; }; A4F875751E94123F0079734E /* KMeansDlg.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = KMeansDlg.cpp; sourceTree = ""; }; A4F875761E94123F0079734E /* KMeansDlg.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = KMeansDlg.h; sourceTree = ""; }; DD00ADE611138A2C008FE572 /* TemplateFrame.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = TemplateFrame.h; sourceTree = ""; }; @@ -358,8 +555,6 @@ DD209597139F129900B9E648 /* GetisOrdChoiceDlg.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GetisOrdChoiceDlg.h; sourceTree = ""; }; DD26CBE219A41A480092C0F2 /* WebViewExampleWin.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = WebViewExampleWin.cpp; sourceTree = ""; }; DD26CBE319A41A480092C0F2 /* WebViewExampleWin.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WebViewExampleWin.h; sourceTree = ""; }; - DD27EF030F2F6CBE009C5C42 /* ShapeFile.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ShapeFile.h; sourceTree = ""; }; - DD27EF040F2F6CBE009C5C42 /* ShapeFile.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ShapeFile.cpp; sourceTree = ""; }; DD2A6FDE178C7F7C00197093 /* DataSource.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = DataSource.cpp; path = DataViewer/DataSource.cpp; sourceTree = ""; }; DD2A6FDF178C7F7C00197093 /* DataSource.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = DataSource.h; path = DataViewer/DataSource.h; sourceTree = ""; }; DD2AE42819D4F4CA00B23FB9 /* GdaJson.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GdaJson.h; sourceTree = ""; }; @@ -393,8 +588,6 @@ DD40B081181894F20084173C /* VarGroupingEditorDlg.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = VarGroupingEditorDlg.cpp; sourceTree = ""; }; DD40B082181894F20084173C /* VarGroupingEditorDlg.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = VarGroupingEditorDlg.h; sourceTree = ""; }; DD45117019E5F65E006C5DAA /* geoda_prefs.sqlite */ = {isa = PBXFileReference; lastKnownFileType = file; name = geoda_prefs.sqlite; path = BuildTools/CommonDistFiles/geoda_prefs.sqlite; sourceTree = ""; }; - DD497478176F59670007BB9F /* DbfTable.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = DbfTable.h; path = DataViewer/DbfTable.h; sourceTree = ""; }; - DD497479176F59670007BB9F /* DbfTable.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = DbfTable.cpp; path = DataViewer/DbfTable.cpp; sourceTree = ""; }; DD4974B51770AC700007BB9F /* TableFrame.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TableFrame.h; path = DataViewer/TableFrame.h; sourceTree = ""; }; DD4974B61770AC700007BB9F /* TableFrame.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TableFrame.cpp; path = DataViewer/TableFrame.cpp; sourceTree = ""; }; DD4974B81770AC840007BB9F /* TableBase.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TableBase.h; path = DataViewer/TableBase.h; sourceTree = ""; }; @@ -411,8 +604,6 @@ DD5A579616E53EC40047DBB1 /* GeoDa.icns */ = {isa = PBXFileReference; lastKnownFileType = image.icns; path = GeoDa.icns; sourceTree = ""; }; DD5AA73B1982D200009B30C6 /* CalcHelp.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = CalcHelp.cpp; path = VarCalc/CalcHelp.cpp; sourceTree = ""; }; DD5AA73C1982D200009B30C6 /* CalcHelp.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = CalcHelp.h; path = VarCalc/CalcHelp.h; sourceTree = ""; }; - DD5FA1D80F320DD50055A0E5 /* ShapeFileHdr.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ShapeFileHdr.h; sourceTree = ""; }; - DD5FA1D90F320DD50055A0E5 /* ShapeFileHdr.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ShapeFileHdr.cpp; sourceTree = ""; }; DD60546616A83EEF0004BF02 /* CatClassifManager.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = CatClassifManager.cpp; sourceTree = ""; }; DD60546716A83EEF0004BF02 /* CatClassifManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CatClassifManager.h; sourceTree = ""; }; DD6456C714881EA700AABF59 /* TimeChooserDlg.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = TimeChooserDlg.cpp; sourceTree = ""; }; @@ -424,8 +615,6 @@ DD64A5540F291027006B1E6D /* logger.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = logger.h; sourceTree = ""; }; DD64A5570F2910D2006B1E6D /* logger.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = logger.cpp; sourceTree = ""; }; DD64A5760F2911A4006B1E6D /* nullstream.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = nullstream.h; sourceTree = ""; }; - DD64A6AB0F2A7A81006B1E6D /* DBF.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = DBF.h; sourceTree = ""; }; - DD64A6AC0F2A7A81006B1E6D /* DBF.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = DBF.cpp; sourceTree = ""; }; DD64A7230F2E26AA006B1E6D /* GenUtils.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GenUtils.h; sourceTree = ""; }; DD64A7240F2E26AA006B1E6D /* GenUtils.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = GenUtils.cpp; sourceTree = ""; }; DD694683130307C00072386B /* RateSmoothing.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RateSmoothing.h; sourceTree = ""; }; @@ -460,8 +649,6 @@ DD7974C40F1D250A00496A84 /* TemplateCanvas.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = TemplateCanvas.h; sourceTree = ""; }; DD7974FF0F1D296F00496A84 /* 3DControlPan.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = 3DControlPan.cpp; sourceTree = ""; }; DD7975000F1D296F00496A84 /* 3DControlPan.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = 3DControlPan.h; sourceTree = ""; }; - DD7975090F1D296F00496A84 /* ASC2SHPDlg.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ASC2SHPDlg.cpp; sourceTree = ""; }; - DD79750A0F1D296F00496A84 /* ASC2SHPDlg.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ASC2SHPDlg.h; sourceTree = ""; }; DD79750B0F1D296F00496A84 /* Bnd2ShpDlg.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Bnd2ShpDlg.cpp; sourceTree = ""; }; DD79750C0F1D296F00496A84 /* Bnd2ShpDlg.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Bnd2ShpDlg.h; sourceTree = ""; }; DD7975110F1D296F00496A84 /* CreateGridDlg.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = CreateGridDlg.cpp; sourceTree = ""; }; @@ -484,8 +671,6 @@ DD7975480F1D296F00496A84 /* RegressionReportDlg.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RegressionReportDlg.h; sourceTree = ""; }; DD7975550F1D296F00496A84 /* SaveSelectionDlg.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = SaveSelectionDlg.cpp; sourceTree = ""; }; DD7975560F1D296F00496A84 /* SaveSelectionDlg.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SaveSelectionDlg.h; sourceTree = ""; }; - DD7975590F1D296F00496A84 /* SHP2ASCDlg.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = SHP2ASCDlg.cpp; sourceTree = ""; }; - DD79755A0F1D296F00496A84 /* SHP2ASCDlg.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SHP2ASCDlg.h; sourceTree = ""; }; DD7975610F1D296F00496A84 /* VariableSettingsDlg.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = VariableSettingsDlg.cpp; sourceTree = ""; }; DD7975620F1D296F00496A84 /* VariableSettingsDlg.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = VariableSettingsDlg.h; sourceTree = ""; }; DD7975B80F1D2A9000496A84 /* 3DPlotView.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = 3DPlotView.cpp; sourceTree = ""; }; @@ -556,8 +741,6 @@ DD89C87113D86BC7006C068D /* FieldNewCalcSheetDlg.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FieldNewCalcSheetDlg.h; sourceTree = ""; }; DD89C87213D86BC7006C068D /* FieldNewCalcUniDlg.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = FieldNewCalcUniDlg.cpp; sourceTree = ""; }; DD89C87313D86BC7006C068D /* FieldNewCalcUniDlg.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FieldNewCalcUniDlg.h; sourceTree = ""; }; - DD8DCE0C19C0FD8F00E62C3D /* DataChangeType.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = DataChangeType.cpp; path = DataViewer/DataChangeType.cpp; sourceTree = ""; }; - DD8DCE0D19C0FD8F00E62C3D /* DataChangeType.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = DataChangeType.h; path = DataViewer/DataChangeType.h; sourceTree = ""; }; DD8FACDF1649595D007598CE /* DataMovieDlg.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = DataMovieDlg.cpp; sourceTree = ""; }; DD8FACE01649595D007598CE /* DataMovieDlg.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = DataMovieDlg.h; sourceTree = ""; }; DD92851A17F5FC7300B9481A /* VarOrderPtree.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = VarOrderPtree.cpp; path = DataViewer/VarOrderPtree.cpp; sourceTree = ""; }; @@ -568,12 +751,9 @@ DD92853C17F5FE2E00B9481A /* VarGroup.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = VarGroup.h; path = DataViewer/VarGroup.h; sourceTree = ""; }; DD92D22217BAAF2300F8FE01 /* TimeEditorDlg.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = TimeEditorDlg.h; sourceTree = ""; }; DD92D22317BAAF2300F8FE01 /* TimeEditorDlg.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = TimeEditorDlg.cpp; sourceTree = ""; }; - DD9373B41AC1F99D0066AF21 /* SimplePoint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = SimplePoint.cpp; sourceTree = ""; }; - DD9373B51AC1F99D0066AF21 /* SimplePoint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SimplePoint.h; sourceTree = ""; }; DD9373F51AC1FEAA0066AF21 /* PolysToContigWeights.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = PolysToContigWeights.cpp; sourceTree = ""; }; DD9373F61AC1FEAA0066AF21 /* PolysToContigWeights.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PolysToContigWeights.h; sourceTree = ""; }; DD93748F1AC2086B0066AF21 /* Link.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Link.h; sourceTree = ""; }; - DD972056150A6F44000206F4 /* sp_tm_conv.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = sp_tm_conv.cpp; path = CmdLineUtils/sp_tm_conv/sp_tm_conv.cpp; sourceTree = ""; }; DD99BA1811D3F8D6003BB40E /* ScatterNewPlotView.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ScatterNewPlotView.h; sourceTree = ""; }; DD99BA1911D3F8D6003BB40E /* ScatterNewPlotView.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ScatterNewPlotView.cpp; sourceTree = ""; }; DD9C1B351910267900C0A427 /* GdaConst.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = GdaConst.cpp; sourceTree = ""; }; @@ -623,19 +803,8 @@ DDC9DD9B15937C0200A0E5BA /* ImportCsvDlg.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ImportCsvDlg.h; sourceTree = ""; }; DDCCB5CA1AD47C200067D6C4 /* SimpleBinsHistCanvas.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = SimpleBinsHistCanvas.cpp; sourceTree = ""; }; DDCCB5CB1AD47C200067D6C4 /* SimpleBinsHistCanvas.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SimpleBinsHistCanvas.h; sourceTree = ""; }; - DDCFA9941A96790100747EB7 /* DbfFile.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = DbfFile.cpp; sourceTree = ""; }; - DDCFA9951A96790100747EB7 /* DbfFile.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = DbfFile.h; sourceTree = ""; }; DDD13F040F2F8BE1009F7F13 /* GenGeomAlgs.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GenGeomAlgs.h; sourceTree = ""; }; DDD13F050F2F8BE1009F7F13 /* GenGeomAlgs.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = GenGeomAlgs.cpp; sourceTree = ""; }; - DDD13F6D0F2FC802009F7F13 /* ShapeFileTriplet.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ShapeFileTriplet.h; sourceTree = ""; }; - DDD13F6E0F2FC802009F7F13 /* ShapeFileTriplet.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ShapeFileTriplet.cpp; sourceTree = ""; }; - DDD13F720F2FCEE8009F7F13 /* ShapeFileTypes.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ShapeFileTypes.h; sourceTree = ""; }; - DDD13F910F2FD641009F7F13 /* BasePoint.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = BasePoint.h; sourceTree = ""; }; - DDD13F920F2FD641009F7F13 /* BasePoint.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = BasePoint.cpp; sourceTree = ""; }; - DDD13FA90F30B2E4009F7F13 /* Box.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Box.h; sourceTree = ""; }; - DDD13FAA0F30B2E4009F7F13 /* Box.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Box.cpp; sourceTree = ""; }; - DDD140520F310324009F7F13 /* AbstractShape.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AbstractShape.h; sourceTree = ""; }; - DDD140530F310324009F7F13 /* AbstractShape.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = AbstractShape.cpp; sourceTree = ""; }; DDD2392B1AB86D8F00E4E1BF /* NumericTests.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = NumericTests.cpp; path = VarCalc/NumericTests.cpp; sourceTree = ""; }; DDD2392C1AB86D8F00E4E1BF /* NumericTests.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = NumericTests.h; path = VarCalc/NumericTests.h; sourceTree = ""; }; DDD593AA12E9F34C00F7A7C4 /* GeodaWeight.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GeodaWeight.h; sourceTree = ""; }; @@ -652,15 +821,11 @@ DDDBF29A163AD2BF0070610C /* ConditionalScatterPlotView.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ConditionalScatterPlotView.cpp; sourceTree = ""; }; DDDBF2AC163AD3AB0070610C /* ConditionalHistogramView.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ConditionalHistogramView.cpp; sourceTree = ""; }; DDDBF2AD163AD3AB0070610C /* ConditionalHistogramView.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ConditionalHistogramView.h; sourceTree = ""; }; - DDDC11EB1159783700E515BB /* ShapeUtils.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ShapeUtils.cpp; sourceTree = ""; }; - DDDC11EC1159783700E515BB /* ShapeUtils.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ShapeUtils.h; sourceTree = ""; }; DDE39D97178CDB9A00C47D58 /* PtreeInterface.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = PtreeInterface.h; path = DataViewer/PtreeInterface.h; sourceTree = ""; }; DDE3F5061677C46500D13A2C /* CatClassification.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = CatClassification.cpp; sourceTree = ""; }; DDE3F5071677C46500D13A2C /* CatClassification.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CatClassification.h; sourceTree = ""; }; DDE4DFD41A963B07005B9158 /* GdaShape.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = GdaShape.cpp; sourceTree = ""; }; DDE4DFD51A963B07005B9158 /* GdaShape.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GdaShape.h; sourceTree = ""; }; - DDE4DFE71A96411A005B9158 /* ShpFile.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ShpFile.cpp; sourceTree = ""; }; - DDE4DFE81A96411A005B9158 /* ShpFile.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ShpFile.h; sourceTree = ""; }; DDEA3CB7193CEE5C0028B746 /* GdaFlexValue.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = GdaFlexValue.cpp; path = VarCalc/GdaFlexValue.cpp; sourceTree = ""; }; DDEA3CB8193CEE5C0028B746 /* GdaFlexValue.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = GdaFlexValue.h; path = VarCalc/GdaFlexValue.h; sourceTree = ""; }; DDEA3CB9193CEE5C0028B746 /* GdaLexer.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = GdaLexer.cpp; path = VarCalc/GdaLexer.cpp; sourceTree = ""; }; @@ -682,8 +847,6 @@ DDF5400A167A39CA0042B453 /* CatClassifDlg.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CatClassifDlg.h; sourceTree = ""; }; DDF85D1613B257B6006C1B08 /* DataViewerEditFieldPropertiesDlg.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = DataViewerEditFieldPropertiesDlg.cpp; path = DataViewer/DataViewerEditFieldPropertiesDlg.cpp; sourceTree = ""; }; DDF85D1713B257B6006C1B08 /* DataViewerEditFieldPropertiesDlg.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = DataViewerEditFieldPropertiesDlg.h; path = DataViewer/DataViewerEditFieldPropertiesDlg.h; sourceTree = ""; }; - DDFE0E0717502E810099FFEC /* DbfColContainer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = DbfColContainer.h; path = DataViewer/DbfColContainer.h; sourceTree = ""; }; - DDFE0E0817502E810099FFEC /* DbfColContainer.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = DbfColContainer.cpp; path = DataViewer/DbfColContainer.cpp; sourceTree = ""; }; DDFE0E27175034EC0099FFEC /* TimeState.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TimeState.cpp; path = DataViewer/TimeState.cpp; sourceTree = ""; }; DDFE0E28175034EC0099FFEC /* TimeState.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TimeState.h; path = DataViewer/TimeState.h; sourceTree = ""; }; DDFE0E29175034EC0099FFEC /* TimeStateObserver.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TimeStateObserver.h; path = DataViewer/TimeStateObserver.h; sourceTree = ""; }; @@ -714,15 +877,128 @@ /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ + A10EF2ED21273E4900564FE1 /* visualization */ = { + isa = PBXGroup; + children = ( + A10EF2EE21273E7E00564FE1 /* AbstractCanvas.cpp */, + A10EF2EF21273E7E00564FE1 /* AbstractCanvas.hpp */, + ); + path = visualization; + sourceTree = ""; + }; + A19483772118BA8B009A87A2 /* ogl */ = { + isa = PBXGroup; + children = ( + A19483862118BAA8009A87A2 /* basic.cpp */, + A194838B2118BAA9009A87A2 /* basic.h */, + A19483892118BAA9009A87A2 /* basic2.cpp */, + A19483832118BAA8009A87A2 /* basicp.h */, + A19483852118BAA8009A87A2 /* bmpshape.cpp */, + A19483842118BAA8009A87A2 /* bmpshape.h */, + A19483872118BAA8009A87A2 /* canvas.cpp */, + A194838F2118BAAA009A87A2 /* canvas.h */, + A194837A2118BAA7009A87A2 /* composit.cpp */, + A19483792118BAA7009A87A2 /* composit.h */, + A194837F2118BAA7009A87A2 /* constrnt.cpp */, + A194838E2118BAA9009A87A2 /* constrnt.h */, + A194837E2118BAA7009A87A2 /* divided.cpp */, + A19483802118BAA8009A87A2 /* divided.h */, + A194838C2118BAA9009A87A2 /* drawn.cpp */, + A19483922118BAAA009A87A2 /* drawn.h */, + A19483822118BAA8009A87A2 /* drawnp.h */, + A19483882118BAA9009A87A2 /* lines.cpp */, + A19483902118BAAA009A87A2 /* lines.h */, + A194837C2118BAA7009A87A2 /* linesp.h */, + A194838A2118BAA9009A87A2 /* mfutils.cpp */, + A194837D2118BAA7009A87A2 /* mfutils.h */, + A194837B2118BAA7009A87A2 /* misc.h */, + A194838D2118BAA9009A87A2 /* ogl.h */, + A19483912118BAAA009A87A2 /* ogldiag.cpp */, + A19483782118BAA7009A87A2 /* ogldiag.h */, + A19483812118BAA8009A87A2 /* oglmisc.cpp */, + ); + path = ogl; + sourceTree = ""; + }; + A40AB91A20F5336600F94543 /* arizona */ = { + isa = PBXGroup; + children = ( + A40AB91C20F5338D00F94543 /* models */, + A40AB91B20F5338200F94543 /* viz3 */, + ); + path = arizona; + sourceTree = ""; + }; + A40AB91B20F5338200F94543 /* viz3 */ = { + isa = PBXGroup; + children = ( + A40AB92420F675B600F94543 /* mathstuff.cpp */, + A40AB92220F675B500F94543 /* mathstuff.h */, + A40AB92720F675B600F94543 /* oglpfuncs.cpp */, + A40AB92320F675B600F94543 /* oglpfuncs.h */, + A40AB92520F675B600F94543 /* oglstuff.cpp */, + A40AB92620F675B600F94543 /* oglstuff.h */, + A40AB91E20F533A500F94543 /* plots */, + A40AB91D20F533A000F94543 /* maps */, + ); + path = viz3; + sourceTree = ""; + }; + A40AB91C20F5338D00F94543 /* models */ = { + isa = PBXGroup; + children = ( + ); + path = models; + sourceTree = ""; + }; + A40AB91D20F533A000F94543 /* maps */ = { + isa = PBXGroup; + children = ( + ); + path = maps; + sourceTree = ""; + }; + A40AB91E20F533A500F94543 /* plots */ = { + isa = PBXGroup; + children = ( + A40AB92020F559F500F94543 /* scatterplot.cpp */, + A40AB91F20F559F500F94543 /* scatterplot.h */, + ); + path = plots; + sourceTree = ""; + }; A45DBDEF1EDDDD2600C2AA8A /* Algorithms */ = { isa = PBXGroup; children = ( + A4E00F0F20FD8ECC0038BA80 /* localjc_kernel.cl */, + A47F792320AA084B000AFE57 /* distmat_kernel.cl */, + A47F792120AA082A000AFE57 /* lisa_kernel.cl */, + A47F791E20A9F679000AFE57 /* gpu_lisa.cpp */, + A47F791F20A9F67A000AFE57 /* gpu_lisa.h */, + A432E84820A674F7007B8B25 /* distmatrix.h */, + A432E84620A672EA007B8B25 /* distmatrix.cpp */, + A48814EA20A50B0F005490A7 /* fastcluster.cpp */, + A47533BC20A3BD5000695283 /* fastcluster.h */, + A4404A10209275540007753D /* hdbscan.cpp */, + A4404A11209275550007753D /* hdbscan.h */, + A42018011FB3C0AC0029709C /* skater.cpp */, + A42018021FB3C0AC0029709C /* skater.h */, + A4368CDA1FABBBC60099FA9B /* mds.cpp */, + A4368CDB1FABBBC60099FA9B /* mds.h */, + A4368CD91FABB5260099FA9B /* DataUtils.h */, + A46DFA8F1FA92145007F5923 /* texttable.h */, + A4E138B61F71A29100433256 /* geocoding.cpp */, + A4E138B71F71A29100433256 /* geocoding.h */, + A4D5423B1F45037B00572878 /* redcap.cpp */, + A4D5423C1F45037B00572878 /* redcap.h */, + A43D124D1F2088D50073D408 /* spectral.h */, + A43D124E1F2088D50073D408 /* spectral.cpp */, A45DBDF81EDDEE4D00C2AA8A /* maxp.cpp */, A45DBDF91EDDEE4D00C2AA8A /* maxp.h */, - A45DBDF01EDDEDAD00C2AA8A /* pca.h */, A45DBDF11EDDEDAD00C2AA8A /* pca.cpp */, - A45DBDF21EDDEDAD00C2AA8A /* cluster.h */, + A45DBDF01EDDEDAD00C2AA8A /* pca.h */, A45DBDF31EDDEDAD00C2AA8A /* cluster.cpp */, + A45DBDF21EDDEDAD00C2AA8A /* cluster.h */, ); name = Algorithms; sourceTree = ""; @@ -730,6 +1006,9 @@ A45DBDF61EDDEDC400C2AA8A /* _SampleImages */ = { isa = PBXGroup; children = ( + A1230E5D212DF54D002AB30A /* switch-off.png */, + A1230E5C212DF54C002AB30A /* switch-on.png */, + A4DB2CBB1EEA3A3E00BD4A54 /* Guerry.png */, A496C9C41E6A441D008F87DD /* watermark-20.png */, A496C9C21E6A4417008F87DD /* USHomicides.png */, A496C9C01E6A440A008F87DD /* SIDSNC.png */, @@ -761,6 +1040,55 @@ name = _InternalData; sourceTree = ""; }; + A47614AC20759E6100D9F3BE /* io */ = { + isa = PBXGroup; + children = ( + A414C88A207BED2700520546 /* MatfileReader.cpp */, + A414C889207BED2700520546 /* MatfileReader.h */, + A4B1F99620783CC100905246 /* weights_interface.h */, + A4B1F9952077311F00905246 /* matlab_mat.h */, + A4B1F992207730FA00905246 /* matlab_mat.cpp */, + A47614AD20759EAD00D9F3BE /* arcgis_swm.cpp */, + A47614AB20759E5600D9F3BE /* arcgis_swm.h */, + ); + name = io; + sourceTree = ""; + }; + A4CFF027207D6D7500E2E6DE /* internationalization */ = { + isa = PBXGroup; + children = ( + A4404A0E209270FB0007753D /* pofiles */, + A4404A03208E9E380007753D /* lang */, + ); + name = internationalization; + path = ../../internationalization; + sourceTree = SOURCE_ROOT; + }; + A4ED7D3F2097EC0F008685D6 /* kNN */ = { + isa = PBXGroup; + children = ( + A4ED7D4E2097F113008685D6 /* kd_pr_search.cpp */, + A4ED7D4A2097F113008685D6 /* kd_pr_search.h */, + A4ED7D502097F114008685D6 /* kd_search.cpp */, + A4ED7D492097F113008685D6 /* kd_search.h */, + A4ED7D522097F114008685D6 /* kd_split.cpp */, + A4ED7D532097F114008685D6 /* kd_split.h */, + A4ED7D482097F113008685D6 /* kd_tree.h */, + A4ED7D512097F114008685D6 /* kd_util.cpp */, + A4ED7D4B2097F113008685D6 /* kd_util.h */, + A4ED7D4C2097F113008685D6 /* kNN.cpp */, + A4ED7D4D2097F113008685D6 /* pr_queue_k.h */, + A4ED7D4F2097F113008685D6 /* pr_queue.h */, + A4ED7D462097EDE9008685D6 /* kd_tree.cpp */, + A4ED7D452097ECC6008685D6 /* values.h */, + A4ED7D412097EC54008685D6 /* ANN.cpp */, + A4ED7D432097EC55008685D6 /* ANN.h */, + A4ED7D422097EC54008685D6 /* ANNperf.h */, + A4ED7D402097EC54008685D6 /* ANNx.h */, + ); + path = kNN; + sourceTree = ""; + }; DD7686D41A9FF446009EFC6D /* libgdiam */ = { isa = PBXGroup; children = ( @@ -773,13 +1101,18 @@ DD7974650F1D1B0700496A84 /* ../../ */ = { isa = PBXGroup; children = ( + A10EF2ED21273E4900564FE1 /* visualization */, + A19483772118BA8B009A87A2 /* ogl */, + A40AB91A20F5336600F94543 /* arizona */, + A4ED7D3F2097EC0F008685D6 /* kNN */, + A4CFF027207D6D7500E2E6DE /* internationalization */, + A47614AC20759E6100D9F3BE /* io */, A45DBDEF1EDDDD2600C2AA8A /* Algorithms */, A45DBDF61EDDEDC400C2AA8A /* _SampleImages */, A45DBDF71EDDEDDA00C2AA8A /* _InternalData */, A4D9A31E1E4D5F3800EF584C /* gdaldata */, A1C194A21B38FC67003DA7CA /* libc++.dylib */, A1B04ADC1B1921710045AA6F /* basemap_cache */, - DD972054150A6EE4000206F4 /* CmdLineUtils */, DDDFB96D134B6B73005EF636 /* DataViewer */, DD7974FE0F1D296F00496A84 /* DialogTools */, DD7975B70F1D2A9000496A84 /* Explore */, @@ -791,8 +1124,6 @@ DDEA3CB6193CEE250028B746 /* VarCalc */, DDBDFE6119E73E07004CCEDA /* web_plugins */, A19F514D1756A11E006E31B4 /* plugins */, - DDCFA9941A96790100747EB7 /* DbfFile.cpp */, - DDCFA9951A96790100747EB7 /* DbfFile.h */, DD3BA4471871EE9A00CA4152 /* DefaultVarsPtree.h */, DD3BA4461871EE9A00CA4152 /* DefaultVarsPtree.cpp */, DD9C1B361910267900C0A427 /* GdaConst.h */, @@ -806,6 +1137,8 @@ A186F0A01C16508A00AEBA13 /* GdaCartoDB.h */, DD64A2870F20FE06006B1E6D /* GeneralWxUtils.h */, DD64A2860F20FE06006B1E6D /* GeneralWxUtils.cpp */, + A4A6AD7A207F198E00D29677 /* ShpFile.cpp */, + A4A6AD79207F198D00D29677 /* ShpFile.h */, DD64925B16DFF63400B3B0AB /* GeoDa.h */, DD64925A16DFF63400B3B0AB /* GeoDa.cpp */, DDD13F040F2F8BE1009F7F13 /* GenGeomAlgs.h */, @@ -815,14 +1148,13 @@ DDFFC7EC1AC1C7CF00F7DD6D /* HighlightState.cpp */, DDFFC7ED1AC1C7CF00F7DD6D /* HighlightState.h */, DDFFC7EE1AC1C7CF00F7DD6D /* HighlightStateObserver.h */, + A1894C41213F806700718FFC /* MapLayerStateObserver.h */, DDFFC7EF1AC1C7CF00F7DD6D /* HLStateInt.h */, DDFFC7F01AC1C7CF00F7DD6D /* Observable.h */, DDFFC7F11AC1C7CF00F7DD6D /* Observer.h */, DD64A5540F291027006B1E6D /* logger.h */, DD64A5570F2910D2006B1E6D /* logger.cpp */, DD64A5760F2911A4006B1E6D /* nullstream.h */, - DDE4DFE71A96411A005B9158 /* ShpFile.cpp */, - DDE4DFE81A96411A005B9158 /* ShpFile.h */, DD72C1971AAE95480000420B /* SpatialIndAlgs.cpp */, DD72C1981AAE95480000420B /* SpatialIndAlgs.h */, DD72C1991AAE95480000420B /* SpatialIndTypes.h */, @@ -846,6 +1178,8 @@ DD409E4A19FFD43000C21A2B /* VarTools.cpp */, DD409E4B19FFD43000C21A2B /* VarTools.h */, DD84139218B24BF2007C39CF /* version.h */, + A4404A00208E65DC0007753D /* wxTranslationHelper.cpp */, + A4404A01208E65DD0007753D /* wxTranslationHelper.h */, ); path = ../../; sourceTree = ""; @@ -861,6 +1195,30 @@ DD7974FE0F1D296F00496A84 /* DialogTools */ = { isa = PBXGroup; children = ( + A4ED7D59209A6B81008685D6 /* HDBScanDlg.cpp */, + A4ED7D5A209A6B81008685D6 /* HDBScanDlg.h */, + A40A6A7D20226B3B003CDD79 /* PreferenceDlg.cpp */, + A40A6A7C20226B3B003CDD79 /* PreferenceDlg.h */, + A42018041FB4CF980029709C /* SkaterDlg.h */, + A42018051FB4CF980029709C /* SkaterDlg.cpp */, + A416A1751F84122B001F2884 /* PCASettingsDlg.cpp */, + A416A1761F84122B001F2884 /* PCASettingsDlg.h */, + A4E138B91F71D6B800433256 /* GeocodingDlg.cpp */, + A4E138BA1F71D6B800433256 /* GeocodingDlg.h */, + A42B6F761F666C57004AFAB8 /* FieldNewCalcDateTimeDlg.cpp */, + A42B6F771F666C57004AFAB8 /* FieldNewCalcDateTimeDlg.h */, + A4E5FE171F624D5600D75662 /* AggregateDlg.cpp */, + A4E5FE181F624D5600D75662 /* AggregateDlg.h */, + A4F5D6201F513EA1007ADF25 /* MDSDlg.cpp */, + A4F5D6211F513EA1007ADF25 /* MDSDlg.h */, + A4F5D61D1F4EA0D2007ADF25 /* AbstractClusterDlg.cpp */, + A4F5D61E1F4EA0D2007ADF25 /* AbstractClusterDlg.h */, + A4320FC61F4735020007BE0D /* RedcapDlg.cpp */, + A4320FC71F4735020007BE0D /* RedcapDlg.h */, + A43D12501F20AE450073D408 /* SpectralClusteringDlg.h */, + A43D12511F20AE450073D408 /* SpectralClusteringDlg.cpp */, + A43D124A1F1DE1D80073D408 /* MaxpDlg.cpp */, + A43D124B1F1DE1D80073D408 /* MaxpDlg.h */, A49F56DB1E956FCC000309CE /* HClusterDlg.cpp */, A49F56DC1E956FCC000309CE /* HClusterDlg.h */, A4F875751E94123F0079734E /* KMeansDlg.cpp */, @@ -883,8 +1241,6 @@ DD7975000F1D296F00496A84 /* 3DControlPan.h */, DDB0E42A10B34DBB00F96D57 /* AddIdVariable.cpp */, DDB0E42B10B34DBB00F96D57 /* AddIdVariable.h */, - DD7975090F1D296F00496A84 /* ASC2SHPDlg.cpp */, - DD79750A0F1D296F00496A84 /* ASC2SHPDlg.h */, A1DA623817BCBC070070CAAB /* AutoCompTextCtrl.cpp */, A1DA623917BCBC070070CAAB /* AutoCompTextCtrl.h */, DD79750B0F1D296F00496A84 /* Bnd2ShpDlg.cpp */, @@ -947,16 +1303,14 @@ DD7975440F1D296F00496A84 /* RegressionDlg.h */, DD7975470F1D296F00496A84 /* RegressionReportDlg.cpp */, DD7975480F1D296F00496A84 /* RegressionReportDlg.h */, - A13B6B9218760CF100F93ACF /* SaveAsDlg.h */, A13B6B9318760CF100F93ACF /* SaveAsDlg.cpp */, + A13B6B9218760CF100F93ACF /* SaveAsDlg.h */, DD181BC613A90445004B0EC2 /* SaveToTableDlg.cpp */, DD181BC713A90445004B0EC2 /* SaveToTableDlg.h */, DD7975550F1D296F00496A84 /* SaveSelectionDlg.cpp */, DD7975560F1D296F00496A84 /* SaveSelectionDlg.h */, DD4DED10197E16FF00FE29E8 /* SelectWeightsDlg.cpp */, DD4DED11197E16FF00FE29E8 /* SelectWeightsDlg.h */, - DD7975590F1D296F00496A84 /* SHP2ASCDlg.cpp */, - DD79755A0F1D296F00496A84 /* SHP2ASCDlg.h */, DD6456C814881EA700AABF59 /* TimeChooserDlg.h */, DD6456C714881EA700AABF59 /* TimeChooserDlg.cpp */, DD92D22217BAAF2300F8FE01 /* TimeEditorDlg.h */, @@ -969,6 +1323,8 @@ DD3082B119F709BB001E5E89 /* WebViewHelpWin.cpp */, DD8183C71970619800228B0A /* WeightsManDlg.h */, DD8183C61970619800228B0A /* WeightsManDlg.cpp */, + A1894C3D213F29DC00718FFC /* SpatialJoinDlg.cpp */, + A1894C3E213F29DC00718FFC /* SpatialJoinDlg.h */, ); path = DialogTools; sourceTree = ""; @@ -976,6 +1332,17 @@ DD7975B70F1D2A9000496A84 /* Explore */ = { isa = PBXGroup; children = ( + A4596B502033DDFF00C9BCC8 /* AbstractClusterMap.cpp */, + A4596B4F2033DDFF00C9BCC8 /* AbstractClusterMap.h */, + A4596B4D2033DB8E00C9BCC8 /* AbstractCoordinator.cpp */, + A4596B4C2033D8F600C9BCC8 /* AbstractCoordinator.h */, + A4C4ABF91F97DA2D00085D47 /* MLJCMapNewView.cpp */, + A4C4ABFA1F97DA2D00085D47 /* MLJCMapNewView.h */, + A47FC9DC1F74E31800BEFBF2 /* MLJCCoordinatorObserver.h */, + A47FC9D91F74DE1600BEFBF2 /* MLJCCoordinator.cpp */, + A47FC9DA1F74DE1600BEFBF2 /* MLJCCoordinator.h */, + A4A763F21F69FB3B00EE79DD /* ColocationMapView.cpp */, + A4A763F31F69FB3B00EE79DD /* ColocationMapView.h */, A43D31561E845C3D007488D9 /* LocalGearyMapNewView.cpp */, A43D31571E845C3D007488D9 /* LocalGearyMapNewView.h */, A43D31551E845A0C007488D9 /* LocalGearyCoordinatorObserver.h */, @@ -1049,8 +1416,6 @@ DD3079C419ED9F61001E5E89 /* LowessParamObservable.cpp */, DD3079C519ED9F61001E5E89 /* LowessParamObservable.h */, DD3079C619ED9F61001E5E89 /* LowessParamObserver.h */, - DD203F9B14C0C960006A731B /* MapNewView.cpp */, - DD203F9C14C0C960006A731B /* MapNewView.h */, DD2B43401522A95100888E51 /* PCPNewView.cpp */, DD2B43411522A95100888E51 /* PCPNewView.h */, DD409DFA19FF099E00C21A2B /* ScatterPlotMatView.h */, @@ -1076,6 +1441,14 @@ DD8183C1197054CA00228B0A /* WeightsMapCanvas.cpp */, A11B85BA1B18DC89008B64EA /* Basemap.h */, A11B85BB1B18DC9C008B64EA /* Basemap.cpp */, + DD203F9B14C0C960006A731B /* MapNewView.cpp */, + DD203F9C14C0C960006A731B /* MapNewView.h */, + A19483A02118BE8E009A87A2 /* MapLayoutView.cpp */, + A19483A12118BE8F009A87A2 /* MapLayoutView.h */, + A1230E602130E783002AB30A /* MapLayer.cpp */, + A1230E612130E783002AB30A /* MapLayer.hpp */, + A1230E632130E81A002AB30A /* MapLayerTree.cpp */, + A1230E642130E81A002AB30A /* MapLayerTree.hpp */, ); path = Explore; sourceTree = ""; @@ -1134,16 +1507,8 @@ DD7976E10F1D2D3100496A84 /* ShapeOperations */ = { isa = PBXGroup; children = ( - DDD140520F310324009F7F13 /* AbstractShape.h */, - DDD140530F310324009F7F13 /* AbstractShape.cpp */, - DDD13F910F2FD641009F7F13 /* BasePoint.h */, - DDD13F920F2FD641009F7F13 /* BasePoint.cpp */, - DDD13FA90F30B2E4009F7F13 /* Box.h */, - DDD13FAA0F30B2E4009F7F13 /* Box.cpp */, DDC9DD8815937B2F00A0E5BA /* CsvFileUtils.cpp */, DDC9DD8915937B2F00A0E5BA /* CsvFileUtils.h */, - DD64A6AB0F2A7A81006B1E6D /* DBF.h */, - DD64A6AC0F2A7A81006B1E6D /* DBF.cpp */, DD579B68160BDAFE00BF8D53 /* DorlingCartogram.cpp */, DD579B69160BDAFE00BF8D53 /* DorlingCartogram.h */, A1F1BA5A178D3B46005A46E5 /* GdaCache.cpp */, @@ -1170,17 +1535,6 @@ DD694684130307C00072386B /* RateSmoothing.cpp */, DD9373F51AC1FEAA0066AF21 /* PolysToContigWeights.cpp */, DD9373F61AC1FEAA0066AF21 /* PolysToContigWeights.h */, - DD27EF030F2F6CBE009C5C42 /* ShapeFile.h */, - DD27EF040F2F6CBE009C5C42 /* ShapeFile.cpp */, - DD5FA1D80F320DD50055A0E5 /* ShapeFileHdr.h */, - DD5FA1D90F320DD50055A0E5 /* ShapeFileHdr.cpp */, - DDD13F6D0F2FC802009F7F13 /* ShapeFileTriplet.h */, - DDD13F6E0F2FC802009F7F13 /* ShapeFileTriplet.cpp */, - DDD13F720F2FCEE8009F7F13 /* ShapeFileTypes.h */, - DDDC11EB1159783700E515BB /* ShapeUtils.cpp */, - DDDC11EC1159783700E515BB /* ShapeUtils.h */, - DD9373B41AC1F99D0066AF21 /* SimplePoint.cpp */, - DD9373B51AC1F99D0066AF21 /* SimplePoint.h */, DD307DB719F0483B001E5E89 /* SmoothingUtils.cpp */, DD307DB819F0483B001E5E89 /* SmoothingUtils.h */, DDD593AE12E9F42100F7A7C4 /* WeightsManager.h */, @@ -1198,27 +1552,9 @@ path = ShapeOperations; sourceTree = ""; }; - DD972054150A6EE4000206F4 /* CmdLineUtils */ = { - isa = PBXGroup; - children = ( - DD972055150A6F17000206F4 /* sp_tm_conv */, - ); - name = CmdLineUtils; - sourceTree = ""; - }; - DD972055150A6F17000206F4 /* sp_tm_conv */ = { - isa = PBXGroup; - children = ( - DD972056150A6F44000206F4 /* sp_tm_conv.cpp */, - ); - name = sp_tm_conv; - sourceTree = ""; - }; DDDFB96D134B6B73005EF636 /* DataViewer */ = { isa = PBXGroup; children = ( - DD8DCE0C19C0FD8F00E62C3D /* DataChangeType.cpp */, - DD8DCE0D19C0FD8F00E62C3D /* DataChangeType.h */, A1FD8C17186908B800C35C41 /* CustomClassifPtree.cpp */, A1FD8C18186908B800C35C41 /* CustomClassifPtree.h */, DD2A6FDE178C7F7C00197093 /* DataSource.cpp */, @@ -1231,10 +1567,6 @@ DDF85D1713B257B6006C1B08 /* DataViewerEditFieldPropertiesDlg.h */, DDA73B7E13672821003783BC /* DataViewerResizeColDlg.cpp */, DDA73B7F13672821003783BC /* DataViewerResizeColDlg.h */, - DDFE0E0717502E810099FFEC /* DbfColContainer.h */, - DDFE0E0817502E810099FFEC /* DbfColContainer.cpp */, - DD497478176F59670007BB9F /* DbfTable.h */, - DD497479176F59670007BB9F /* DbfTable.cpp */, DDB252B213BBFD6700A7CE26 /* MergeTableDlg.cpp */, DDB252B313BBFD6700A7CE26 /* MergeTableDlg.h */, A1E77FDB17889BE200CC1037 /* OGRTable.h */, @@ -1344,6 +1676,7 @@ DD5A579716E53EC40047DBB1 /* GeoDa.icns in Resources */, A4D9A31F1E4D5F3800EF584C /* gdaldata in Resources */, A19F51501756A11E006E31B4 /* plugins in Resources */, + A4404A05208E9E390007753D /* lang in Resources */, A496C99E1E6A184C008F87DD /* samples.sqlite in Resources */, A496C9A81E6A43C0008F87DD /* BaltimoreHomeSales.png in Resources */, A496C9AA1E6A43CC008F87DD /* BostonHomeSales.png in Resources */, @@ -1351,6 +1684,7 @@ A496C9AE1E6A43D6008F87DD /* ColombiaMalaria.png in Resources */, A496C9B01E6A43DA008F87DD /* ColumbusCrime.png in Resources */, A496C9B21E6A43E5008F87DD /* Milwaukee2000Census.png in Resources */, + A1230E5F212DF54D002AB30A /* switch-off.png in Resources */, A496C9B41E6A43E8008F87DD /* NAT.png in Resources */, A496C9B61E6A43EE008F87DD /* NepalAid.png in Resources */, A496C9B91E6A43FA008F87DD /* no_map.png in Resources */, @@ -1359,7 +1693,10 @@ A496C9BF1E6A4405008F87DD /* SanFranCrime.png in Resources */, A496C9C11E6A440A008F87DD /* SIDSNC.png in Resources */, A496C9C51E6A441D008F87DD /* watermark-20.png in Resources */, + A4404A0F209270FB0007753D /* pofiles in Resources */, A496C9C31E6A4417008F87DD /* USHomicides.png in Resources */, + A1230E5E212DF54D002AB30A /* switch-on.png in Resources */, + A4DB2CBC1EEA3A3E00BD4A54 /* Guerry.png in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -1371,65 +1708,79 @@ buildActionMask = 2147483647; files = ( DD7974C80F1D250A00496A84 /* TemplateCanvas.cpp in Sources */, + A4ED7D5B209A6B81008685D6 /* HDBScanDlg.cpp in Sources */, A1EF332F18E35D8300E19375 /* LocaleSetupDlg.cpp in Sources */, DD7975670F1D296F00496A84 /* 3DControlPan.cpp in Sources */, - DD79756C0F1D296F00496A84 /* ASC2SHPDlg.cpp in Sources */, + A43D124C1F1DE1D80073D408 /* MaxpDlg.cpp in Sources */, DD79756D0F1D296F00496A84 /* Bnd2ShpDlg.cpp in Sources */, A4F875771E94123F0079734E /* KMeansDlg.cpp in Sources */, + A40AB92920F675B600F94543 /* oglstuff.cpp in Sources */, DD7975700F1D296F00496A84 /* CreateGridDlg.cpp in Sources */, DD7975710F1D296F00496A84 /* CreatingWeightDlg.cpp in Sources */, + A40AB92120F559F500F94543 /* scatterplot.cpp in Sources */, DD79757C0F1D296F00496A84 /* HistIntervalDlg.cpp in Sources */, DD79757F0F1D296F00496A84 /* LisaWhat2OpenDlg.cpp in Sources */, + A19483942118BAAA009A87A2 /* divided.cpp in Sources */, + A4D5423D1F45037B00572878 /* redcap.cpp in Sources */, DD7975820F1D296F00496A84 /* PCPDlg.cpp in Sources */, DD7975830F1D296F00496A84 /* PermutationCounterDlg.cpp in Sources */, DD7975850F1D296F00496A84 /* RandomizationDlg.cpp in Sources */, DD7975890F1D296F00496A84 /* RegressionDlg.cpp in Sources */, + A40A6A7E20226B3C003CDD79 /* PreferenceDlg.cpp in Sources */, DD79758B0F1D296F00496A84 /* RegressionReportDlg.cpp in Sources */, + A4ED7D442097EC55008685D6 /* ANN.cpp in Sources */, A1C9F3ED18B55EE000E14394 /* FieldNameCorrectionDlg.cpp in Sources */, A43D31581E845C3D007488D9 /* LocalGearyMapNewView.cpp in Sources */, DD7975920F1D296F00496A84 /* SaveSelectionDlg.cpp in Sources */, - DD7975940F1D296F00496A84 /* SHP2ASCDlg.cpp in Sources */, + A194839D2118BAAA009A87A2 /* drawn.cpp in Sources */, DD7975980F1D296F00496A84 /* VariableSettingsDlg.cpp in Sources */, DD7975D20F1D2A9000496A84 /* 3DPlotView.cpp in Sources */, + A42018061FB4CF980029709C /* SkaterDlg.cpp in Sources */, DD7975D60F1D2A9000496A84 /* Geom3D.cpp in Sources */, + A432E84720A672EB007B8B25 /* distmatrix.cpp in Sources */, DD7976B80F1D2CA800496A84 /* DenseMatrix.cpp in Sources */, + A48814EB20A50B0F005490A7 /* fastcluster.cpp in Sources */, DD7976B90F1D2CA800496A84 /* DenseVector.cpp in Sources */, + A4F5D6221F513EA1007ADF25 /* MDSDlg.cpp in Sources */, DD7976BA0F1D2CA800496A84 /* DiagnosticReport.cpp in Sources */, DD7976BC0F1D2CA800496A84 /* mix.cpp in Sources */, + A47F792420AA084B000AFE57 /* distmat_kernel.cl in Sources */, + A19483972118BAAA009A87A2 /* bmpshape.cpp in Sources */, DD7976BD0F1D2CA800496A84 /* ML_im.cpp in Sources */, DD7976BE0F1D2CA800496A84 /* PowerLag.cpp in Sources */, + A414C88B207BED2700520546 /* MatfileReader.cpp in Sources */, DD7976BF0F1D2CA800496A84 /* PowerSymLag.cpp in Sources */, DD7976C10F1D2CA800496A84 /* smile2.cpp in Sources */, DD7976C20F1D2CA800496A84 /* SparseMatrix.cpp in Sources */, DD7976C30F1D2CA800496A84 /* SparseRow.cpp in Sources */, + A47F792220AA082A000AFE57 /* lisa_kernel.cl in Sources */, DD7976C40F1D2CA800496A84 /* SparseVector.cpp in Sources */, DD7976C50F1D2CA800496A84 /* Weights.cpp in Sources */, DD7976F30F1D2D3100496A84 /* Randik.cpp in Sources */, DD64A2880F20FE06006B1E6D /* GeneralWxUtils.cpp in Sources */, DD64A5580F2910D2006B1E6D /* logger.cpp in Sources */, - DD64A6AD0F2A7A81006B1E6D /* DBF.cpp in Sources */, DD27ECBC0F2E43B5009C5C42 /* GenUtils.cpp in Sources */, - DD27EF050F2F6CBE009C5C42 /* ShapeFile.cpp in Sources */, DDD13F060F2F8BE1009F7F13 /* GenGeomAlgs.cpp in Sources */, - DDD13F6F0F2FC802009F7F13 /* ShapeFileTriplet.cpp in Sources */, + A42018031FB3C0AC0029709C /* skater.cpp in Sources */, A186F0A11C16508A00AEBA13 /* GdaCartoDB.cpp in Sources */, - DDD13F930F2FD641009F7F13 /* BasePoint.cpp in Sources */, - DDD13FAB0F30B2E4009F7F13 /* Box.cpp in Sources */, - DDD140540F310324009F7F13 /* AbstractShape.cpp in Sources */, - DD5FA1DA0F320DD50055A0E5 /* ShapeFileHdr.cpp in Sources */, A1B13EE31C3EDFF90064AD87 /* BasemapConfDlg.cpp in Sources */, A1EBC88F1CD2B2FD001DCFE9 /* AutoUpdateDlg.cpp in Sources */, DDB0E42C10B34DBB00F96D57 /* AddIdVariable.cpp in Sources */, + A194839E2118BAAA009A87A2 /* ogldiag.cpp in Sources */, + A1894C3F213F29DC00718FFC /* SpatialJoinDlg.cpp in Sources */, DD00ADE811138A2C008FE572 /* TemplateFrame.cpp in Sources */, DDAA6540117F9B5D00D1010C /* Project.cpp in Sources */, DDB37A0811CBBB730020C8A9 /* TemplateLegend.cpp in Sources */, DD115EA312BBDDA000E1CC73 /* ProgressDlg.cpp in Sources */, DDD593AC12E9F34C00F7A7C4 /* GeodaWeight.cpp in Sources */, DDD593B012E9F42100F7A7C4 /* WeightsManager.cpp in Sources */, + A194839C2118BAAA009A87A2 /* mfutils.cpp in Sources */, A1AC05BF1C8645F300B6FE5F /* AdjustYAxisDlg.cpp in Sources */, + A194839A2118BAAA009A87A2 /* lines.cpp in Sources */, DDD593C712E9F90000F7A7C4 /* GalWeight.cpp in Sources */, DDD593CA12E9F90C00F7A7C4 /* GwtWeight.cpp in Sources */, DD694685130307C00072386B /* RateSmoothing.cpp in Sources */, + A4E00F1020FD8ECD0038BA80 /* localjc_kernel.cl in Sources */, DDF14CDA139432B000363FA1 /* DataViewerDeleteColDlg.cpp in Sources */, A1E5BC841DBFE661005739E9 /* ReportBugDlg.cpp in Sources */, DDF14CDC139432C100363FA1 /* DataViewerResizeColDlg.cpp in Sources */, @@ -1437,6 +1788,7 @@ DDB77C0D139820CB00569A1E /* GStatCoordinator.cpp in Sources */, DD209598139F129900B9E648 /* GetisOrdChoiceDlg.cpp in Sources */, DD181BC813A90445004B0EC2 /* SaveToTableDlg.cpp in Sources */, + A1230E652130E81A002AB30A /* MapLayerTree.cpp in Sources */, A45DBDFA1EDDEE4D00C2AA8A /* maxp.cpp in Sources */, DDF85D1813B257B6006C1B08 /* DataViewerEditFieldPropertiesDlg.cpp in Sources */, DDB252B513BBFD6700A7CE26 /* MergeTableDlg.cpp in Sources */, @@ -1449,10 +1801,11 @@ DD89C87813D86BC7006C068D /* FieldNewCalcUniDlg.cpp in Sources */, DDB77F3E140D3CEF0032C7E4 /* FieldNewCalcSpecialDlg.cpp in Sources */, DD6B7289141A61400026D223 /* FramesManager.cpp in Sources */, + A416A1771F84122B001F2884 /* PCASettingsDlg.cpp in Sources */, DD7D5C711427F89B00DCFE5C /* LisaCoordinator.cpp in Sources */, + A4A763F41F69FB3B00EE79DD /* ColocationMapView.cpp in Sources */, A16BA470183D626200D3B7DA /* DatasourceDlg.cpp in Sources */, DDA8D55214479228008156FB /* ScatterNewPlotView.cpp in Sources */, - DDA8D5681447948B008156FB /* ShapeUtils.cpp in Sources */, DD6456CA14881EA700AABF59 /* TimeChooserDlg.cpp in Sources */, DD203F9D14C0C960006A731B /* MapNewView.cpp in Sources */, DDF1636B15064B7800E3E6BD /* LisaMapNewView.cpp in Sources */, @@ -1461,6 +1814,7 @@ DD2B42B11522552B00888E51 /* BoxNewPlotView.cpp in Sources */, DD2B433F1522A93700888E51 /* HistogramView.cpp in Sources */, DD2B43421522A95100888E51 /* PCPNewView.cpp in Sources */, + A19483952118BAAA009A87A2 /* constrnt.cpp in Sources */, DDC9DD8515937AA000A0E5BA /* ExportCsvDlg.cpp in Sources */, DDC9DD8A15937B2F00A0E5BA /* CsvFileUtils.cpp in Sources */, DDC9DD9C15937C0200A0E5BA /* ImportCsvDlg.cpp in Sources */, @@ -1470,50 +1824,72 @@ DD579B6A160BDAFE00BF8D53 /* DorlingCartogram.cpp in Sources */, DDAD0218162754EA00748874 /* ConditionalNewView.cpp in Sources */, DDDBF286163AD1D50070610C /* ConditionalMapView.cpp in Sources */, + A40AB92A20F675B600F94543 /* oglpfuncs.cpp in Sources */, DDDBF29B163AD2BF0070610C /* ConditionalScatterPlotView.cpp in Sources */, A13B6B9418760CF100F93ACF /* SaveAsDlg.cpp in Sources */, + A43D12521F20AE450073D408 /* SpectralClusteringDlg.cpp in Sources */, DDDBF2AE163AD3AB0070610C /* ConditionalHistogramView.cpp in Sources */, DD4E8B86164818A70014F1E7 /* ConnectivityHistView.cpp in Sources */, + A4F5D61F1F4EA0D2007ADF25 /* AbstractClusterDlg.cpp in Sources */, DD8FACE11649595D007598CE /* DataMovieDlg.cpp in Sources */, DDA462FF164D785500EBBD8F /* TableState.cpp in Sources */, + A4ED7D562097F114008685D6 /* kd_search.cpp in Sources */, + A19483A22118BE8F009A87A2 /* MapLayoutView.cpp in Sources */, DDE3F5081677C46500D13A2C /* CatClassification.cpp in Sources */, A11F1B7F184FDFB3006F5F98 /* OGRColumn.cpp in Sources */, DDF53FF3167A39520042B453 /* CatClassifState.cpp in Sources */, + A47F792020A9F67A000AFE57 /* gpu_lisa.cpp in Sources */, + A1230E622130E783002AB30A /* MapLayer.cpp in Sources */, DDF5400B167A39CA0042B453 /* CatClassifDlg.cpp in Sources */, DD60546816A83EEF0004BF02 /* CatClassifManager.cpp in Sources */, + A4E5FE191F624D5600D75662 /* AggregateDlg.cpp in Sources */, A45DBDF51EDDEDAD00C2AA8A /* cluster.cpp in Sources */, + A4368CDC1FABBBC60099FA9B /* mds.cpp in Sources */, DD64925C16DFF63400B3B0AB /* GeoDa.cpp in Sources */, + A47FC9DB1F74DE1600BEFBF2 /* MLJCCoordinator.cpp in Sources */, A12E0F4F1705087A00B6059C /* OGRDataAdapter.cpp in Sources */, A1D82DEF174D3EB6003DE20A /* ConnectDatasourceDlg.cpp in Sources */, A1BE9E51174DD85F007B9C64 /* GdaAppResources.cpp in Sources */, - DDFE0E0917502E810099FFEC /* DbfColContainer.cpp in Sources */, DDFE0E2A175034EC0099FFEC /* TimeState.cpp in Sources */, - DD49747A176F59670007BB9F /* DbfTable.cpp in Sources */, + A4404A02208E65DD0007753D /* wxTranslationHelper.cpp in Sources */, + A19483962118BAAA009A87A2 /* oglmisc.cpp in Sources */, DD4974B71770AC700007BB9F /* TableFrame.cpp in Sources */, DD4974BA1770AC840007BB9F /* TableBase.cpp in Sources */, DD4974E21770CE9E0007BB9F /* TableInterface.cpp in Sources */, A1E77E1A177D6A2E00CC1037 /* ExportDataDlg.cpp in Sources */, + A10EF2F021273E7E00564FE1 /* AbstractCanvas.cpp in Sources */, + A194839B2118BAAA009A87A2 /* basic2.cpp in Sources */, A1E77FDC17889BE200CC1037 /* OGRTable.cpp in Sources */, + A4404A12209275550007753D /* hdbscan.cpp in Sources */, A1E78139178A90A100CC1037 /* OGRDatasourceProxy.cpp in Sources */, + A4ED7D552097F114008685D6 /* kd_pr_search.cpp in Sources */, A1E7813A178A90A100CC1037 /* OGRFieldProxy.cpp in Sources */, A1E7813B178A90A100CC1037 /* OGRLayerProxy.cpp in Sources */, DD2A6FE0178C7F7C00197093 /* DataSource.cpp in Sources */, A1F1BA5C178D3B46005A46E5 /* GdaCache.cpp in Sources */, DD92D22417BAAF2300F8FE01 /* TimeEditorDlg.cpp in Sources */, A1DA623A17BCBC070070CAAB /* AutoCompTextCtrl.cpp in Sources */, + A4ED7D542097F114008685D6 /* kNN.cpp in Sources */, A1B93AC017D18735007F8195 /* ProjectConf.cpp in Sources */, + A4B1F994207730FA00905246 /* matlab_mat.cpp in Sources */, A48356BB1E456310002791C8 /* ConditionalClusterMapView.cpp in Sources */, + A4596B4E2033DB8E00C9BCC8 /* AbstractCoordinator.cpp in Sources */, DD92851C17F5FC7300B9481A /* VarOrderPtree.cpp in Sources */, + A4E138B81F71A29100433256 /* geocoding.cpp in Sources */, DD92851F17F5FD4500B9481A /* VarOrderMapper.cpp in Sources */, + A4ED7D572097F114008685D6 /* kd_util.cpp in Sources */, DD92853D17F5FE2E00B9481A /* VarGroup.cpp in Sources */, + A4E138BB1F71D6B800433256 /* GeocodingDlg.cpp in Sources */, A1FD8C19186908B800C35C41 /* CustomClassifPtree.cpp in Sources */, DD40B083181894F20084173C /* VarGroupingEditorDlg.cpp in Sources */, DD7B2A9D185273FF00727A91 /* SaveButtonManager.cpp in Sources */, + A4596B512033DDFF00C9BCC8 /* AbstractClusterMap.cpp in Sources */, DD3BA0D0187111DE00CA4152 /* WeightsManPtree.cpp in Sources */, DD3BA4481871EE9A00CA4152 /* DefaultVarsPtree.cpp in Sources */, DDC48EF618AE506400FD773F /* ProjectInfoDlg.cpp in Sources */, DD0FEBBC1909B7A000930418 /* NumCategoriesDlg.cpp in Sources */, DD9C1B371910267900C0A427 /* GdaConst.cpp in Sources */, + A4ED7D472097EDE9008685D6 /* kd_tree.cpp in Sources */, DDEA3CBD193CEE5C0028B746 /* GdaFlexValue.cpp in Sources */, DDEA3CBE193CEE5C0028B746 /* GdaLexer.cpp in Sources */, DDEA3CBF193CEE5C0028B746 /* GdaParser.cpp in Sources */, @@ -1524,18 +1900,20 @@ DD817EA819676AF100228B0A /* WeightsManState.cpp in Sources */, DD8183C3197054CA00228B0A /* WeightsMapCanvas.cpp in Sources */, DD8183C81970619800228B0A /* WeightsManDlg.cpp in Sources */, + A47614AE20759EAD00D9F3BE /* arcgis_swm.cpp in Sources */, DD81857C19709B7800228B0A /* ConnectivityMapView.cpp in Sources */, DD4DED12197E16FF00FE29E8 /* SelectWeightsDlg.cpp in Sources */, DD5AA73D1982D200009B30C6 /* CalcHelp.cpp in Sources */, DD26CBE419A41A480092C0F2 /* WebViewExampleWin.cpp in Sources */, - DD8DCE0E19C0FD8F00E62C3D /* DataChangeType.cpp in Sources */, + A40AB92820F675B600F94543 /* mathstuff.cpp in Sources */, + A4320FC81F4735020007BE0D /* RedcapDlg.cpp in Sources */, DD2AE42A19D4F4CA00B23FB9 /* GdaJson.cpp in Sources */, A1CE3D331C1A427A0010F170 /* PublishDlg.cpp in Sources */, + A4A6AD7B207F198E00D29677 /* ShpFile.cpp in Sources */, DD30798E19ED80E0001E5E89 /* Lowess.cpp in Sources */, DD3079C719ED9F61001E5E89 /* LowessParamObservable.cpp in Sources */, DD3079E319EDAE6C001E5E89 /* LowessParamDlg.cpp in Sources */, DD307DB919F0483B001E5E89 /* SmoothingUtils.cpp in Sources */, - DDCFA9961A96790100747EB7 /* DbfFile.cpp in Sources */, DD3082B319F709BB001E5E89 /* WebViewHelpWin.cpp in Sources */, DD409DFB19FF099E00C21A2B /* ScatterPlotMatView.cpp in Sources */, DD409E4C19FFD43000C21A2B /* VarTools.cpp in Sources */, @@ -1548,22 +1926,27 @@ DD76D15A1A15430600A01FA5 /* LineChartCanvas.cpp in Sources */, DD6CDA7A1A255CEF00FCF2B8 /* LineChartStats.cpp in Sources */, DD88CF081A4253B700803196 /* CovSpView.cpp in Sources */, + A4ED7D582097F114008685D6 /* kd_split.cpp in Sources */, DD88CF0B1A4254D000803196 /* CovSpHLStateProxy.cpp in Sources */, DD6EE55F1A434302003AB41E /* DistancesCalc.cpp in Sources */, + A19483982118BAAA009A87A2 /* basic.cpp in Sources */, DDE4DFD61A963B07005B9158 /* GdaShape.cpp in Sources */, - DDE4DFE91A96411A005B9158 /* ShpFile.cpp in Sources */, A49F56DD1E956FCC000309CE /* HClusterDlg.cpp in Sources */, DD0FC7E81A9EC17500A6715B /* CorrelogramAlgs.cpp in Sources */, + A4C4ABFB1F97DA2D00085D47 /* MLJCMapNewView.cpp in Sources */, DD7686D71A9FF47B009EFC6D /* gdiam.cpp in Sources */, DDEFAAA71AA4F07200F6AAFA /* PointSetAlgs.cpp in Sources */, DD72C19A1AAE95480000420B /* SpatialIndAlgs.cpp in Sources */, DDD2392D1AB86D8F00E4E1BF /* NumericTests.cpp in Sources */, A43D31541E845985007488D9 /* LocalGearyCoordinator.cpp in Sources */, + A43D124F1F2088D50073D408 /* spectral.cpp in Sources */, + A42B6F781F666C57004AFAB8 /* FieldNewCalcDateTimeDlg.cpp in Sources */, DDFFC7CC1AC0E58B00F7DD6D /* CorrelogramView.cpp in Sources */, DDFFC7CD1AC0E58B00F7DD6D /* CorrelParamsObservable.cpp in Sources */, DDFFC7D51AC0E7DC00F7DD6D /* CorrelParamsDlg.cpp in Sources */, + A19483932118BAAA009A87A2 /* composit.cpp in Sources */, + A19483992118BAAA009A87A2 /* canvas.cpp in Sources */, DDFFC7F21AC1C7CF00F7DD6D /* HighlightState.cpp in Sources */, - DD9373B61AC1F99D0066AF21 /* SimplePoint.cpp in Sources */, DD9373F71AC1FEAA0066AF21 /* PolysToContigWeights.cpp in Sources */, DDCCB5CC1AD47C200067D6C4 /* SimpleBinsHistCanvas.cpp in Sources */, A11B85BC1B18DC9C008B64EA /* Basemap.cpp in Sources */, @@ -1609,8 +1992,10 @@ isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_CXX_LIBRARY = "compiler-default"; COMBINE_HIDPI_IMAGES = YES; COPY_PHASE_STRIP = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; GCC_DYNAMIC_NO_PIC = NO; GCC_ENABLE_FIX_AND_CONTINUE = YES; GCC_MODEL_TUNING = ""; @@ -1638,14 +2023,18 @@ "-D__WXOSX_COCOA__", "-D__WXDEBUG__", "-DDEBUG", + "-DEIGEN_NO_DEBUG", ); OTHER_LDFLAGS = ( "-L/usr/lib", "-liconv", "-L./libraries/lib", + ./libraries/include/boost/stage/lib/libboost_date_time.a, ./libraries/include/boost/stage/lib/libboost_system.a, ./libraries/include/boost/stage/lib/libboost_thread.a, "-framework", + OpenCL, + "-framework", IOKit, "-framework", Carbon, @@ -1671,12 +2060,14 @@ "./libraries/lib/libwx_osx_cocoau_gl-3.1.a", "./libraries/lib/libwx_osx_cocoau_richtext-3.1.a", "./libraries/lib/libwx_osx_cocoau_aui-3.1.a", - "-lwxpng-3.1", - "-lwxjpeg-3.1", + "-lpng", + "-ljpeg", + "-ltiff", "-framework", WebKit, "-lexpat", "-lwxregexu-3.1", + "-lwxscintilla-3.1", "-lz", "-lpthread", "-liconv", @@ -1699,11 +2090,14 @@ isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_CXX_LIBRARY = "compiler-default"; COMBINE_HIDPI_IMAGES = YES; COPY_PHASE_STRIP = YES; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + GCC_C_LANGUAGE_STANDARD = gnu11; GCC_ENABLE_FIX_AND_CONTINUE = NO; GCC_MODEL_TUNING = ""; + GCC_OPTIMIZATION_LEVEL = 3; GCC_PRECOMPILE_PREFIX_HEADER = NO; GCC_PREFIX_HEADER = ""; INFOPLIST_FILE = "GeoDa-Xcode-Info.plist"; @@ -1726,14 +2120,18 @@ "-D__WXMAC__", "-D__WXOSX__", "-D__WXOSX_COCOA__", + "-DEIGEN_NO_DEBUG", ); OTHER_LDFLAGS = ( "-L/usr/lib", "-liconv", "-L./libraries/lib", + ./libraries/include/boost/stage/lib/libboost_date_time.a, ./libraries/include/boost/stage/lib/libboost_system.a, ./libraries/include/boost/stage/lib/libboost_thread.a, "-framework", + OpenCL, + "-framework", IOKit, "-framework", Carbon, diff --git a/BuildTools/macosx/GeoDamake.opt b/BuildTools/macosx/GeoDamake.opt index 48e7b7fb1..cd99c0bbf 100644 --- a/BuildTools/macosx/GeoDamake.opt +++ b/BuildTools/macosx/GeoDamake.opt @@ -3,7 +3,7 @@ GeoDa_ROOT = $(GEODA_HOME)/../.. TARGET = GeoDa CC = gcc -CXX = g++ -Os -arch x86_64 +CXX = g++ -O3 -arch x86_64 LD = g++ -arch x86_64 RM = /bin/rm -f @@ -17,6 +17,7 @@ LIBS = $(WXLIBS) \ -L/usr/lib -liconv \ -L$(GEODA_HOME)/libraries/lib -lgdal -lcurl \ $(GEODA_HOME)/libraries/include/boost/stage/lib/libboost_thread.a \ + $(GEODA_HOME)/libraries/include/boost/stage/lib/libboost_date_time.a \ $(GEODA_HOME)/libraries/include/boost/stage/lib/libboost_system.a \ $(GEODA_HOME)/libraries/lib/libjson_spirit.a @@ -26,8 +27,8 @@ BOOST_HEADER = -I$(GEODA_HOME)/libraries/include/boost GDAL_HEADER = -I$(GEODA_HOME)/libraries/include CPPFLAGS = -I$(GeoDa_ROOT) $(USER_DEFS) -DLOG_ON -CFLAGS = -Os -arch x86_64 -Wall -Wdeclaration-after-statement $(USER_DEFS) $(GDAL_HEADER) -DLOG_ON -CXXFLAGS = -Os -arch x86_64 -Wall $(USER_DEFS) $(WX_HEADER) $(BOOST_HEADER) $(GDAL_HEADER) -DLOG_ON +CFLAGS = -O3 -arch x86_64 -Wall -Wdeclaration-after-statement $(USER_DEFS) $(GDAL_HEADER) -DLOG_ON -DEIGEN_NO_DEBUG +CXXFLAGS = -O3 -arch x86_64 -Wall $(USER_DEFS) $(WX_HEADER) $(BOOST_HEADER) $(GDAL_HEADER) -DLOG_ON -DEIGEN_NO_DEBUG LDFLAGS = -arch x86_64 OBJ_EXT = o diff --git a/BuildTools/macosx/auto_build.10.7.sh b/BuildTools/macosx/auto_build.10.7.sh index 7ff6d5960..ae95e222f 100755 --- a/BuildTools/macosx/auto_build.10.7.sh +++ b/BuildTools/macosx/auto_build.10.7.sh @@ -13,5 +13,5 @@ cd ~/geoda_trunk/BuildTools/macosx ./build10.7.sh $CPU $NODEBUG cd ~/geoda_trunk/BuildTools/macosx/create-dmg ./geoda.sh $VERSION -mv GeoDa$VERSION-Installer.dmg /Volumes/xun/Dropbox +mv GeoDa$VERSION-Installer.dmg /Volumes/SharedFolders/Dropbox cd .. diff --git a/BuildTools/macosx/auto_build.sh b/BuildTools/macosx/auto_build.sh index 7f48058df..ad7a67936 100755 --- a/BuildTools/macosx/auto_build.sh +++ b/BuildTools/macosx/auto_build.sh @@ -14,5 +14,5 @@ cp dep/3D* ~/geoda_trunk/Explore/ ./build.sh $CPU $NODEBUG cd ~/geoda_trunk/BuildTools/macosx/create-dmg ./geoda.sh $VERSION -mv GeoDa$VERSION-Installer.dmg /Volumes/xun/Dropbox +mv GeoDa$VERSION-Installer.dmg /Volumes/SharedFolders/Dropbox cd .. diff --git a/BuildTools/macosx/build10.7.sh b/BuildTools/macosx/build10.7.sh index 00b7888d2..d804b7b7a 100755 --- a/BuildTools/macosx/build10.7.sh +++ b/BuildTools/macosx/build10.7.sh @@ -301,6 +301,40 @@ if ! [ -f "$PREFIX/lib/$LIB_CHECKER" ] ; then echo "Error! Exit" exit fi + +######################################################################### +# install wxWidgets library +######################################################################### +LIB_NAME=wxWidgets-3.1.0 +LIB_URL=https://s3.us-east-2.amazonaws.com/geodabuild/wxWidgets-3.1.0.tar.bz2 +LIB_FILENAME=$(basename "$LIB_URL" ".tar") +LIB_CHECKER=libwx_baseu-3.1.a +echo $LIB_FILENAME + +cd $DOWNLOAD_HOME +if ! [ -f "$LIB_FILENAME" ] ; then + curl -k -o $LIB_FILENAME $LIB_URL +fi + +if ! [ -d "$LIB_NAME" ]; then + tar -xf $LIB_FILENAME +fi + +if ! [ -f "$PREFIX/lib/$LIB_CHECKER" ] ; then + cd $LIB_NAME + make clean + cp -rf $GEODA_HOME/dep/$LIB_NAME/* . + ./configure CFLAGS="$GDA_CFLAGS" CXXFLAGS="$GDA_CXXFLAGS" LDFLAGS="$GDA_LDFLAGS" OBJCFLAGS="-arch x86_64" OBJCXXFLAGS="-arch x86_64" --with-cocoa --disable-shared --disable-monolithic --with-opengl --enable-postscript --enable-textfile --without-liblzma --enable-webview --enable-compat28 --prefix=$PREFIX + $MAKER + make install + cd .. +fi + +if ! [ -f "$PREFIX/lib/$LIB_CHECKER" ] ; then + echo "Error! Exit" + exit +fi + ######################################################################### # MySQL ######################################################################### @@ -524,39 +558,6 @@ if ! [ -f "$PREFIX/lib/$LIB_CHECKER" ] ; then exit fi -######################################################################### -# install wxWidgets library -######################################################################### -LIB_NAME=wxWidgets-3.1.0 -LIB_URL=https://s3.us-east-2.amazonaws.com/geodabuild/wxWidgets-3.1.0.tar.bz2 -LIB_FILENAME=$(basename "$LIB_URL" ".tar") -LIB_CHECKER=libwx_baseu-3.1.a -echo $LIB_FILENAME - -cd $DOWNLOAD_HOME -if ! [ -f "$LIB_FILENAME" ] ; then - curl -k -o $LIB_FILENAME $LIB_URL -fi - -if ! [ -d "$LIB_NAME" ]; then - tar -xf $LIB_FILENAME -fi - -if ! [ -f "$PREFIX/lib/$LIB_CHECKER" ] ; then - cd $LIB_NAME - make clean - cp -rf $GEODA_HOME/dep/$LIB_NAME/* . - ./configure CFLAGS="$GDA_CFLAGS" CXXFLAGS="$GDA_CXXFLAGS" LDFLAGS="$GDA_LDFLAGS" OBJCFLAGS="-arch x86_64" OBJCXXFLAGS="-arch x86_64" --with-cocoa --disable-shared --disable-monolithic --with-opengl --enable-postscript --enable-textfile --without-liblzma --enable-webview --enable-compat28 --prefix=$PREFIX - $MAKER - make install - cd .. -fi - -if ! [ -f "$PREFIX/lib/$LIB_CHECKER" ] ; then - echo "Error! Exit" - exit -fi - ######################################################################### # build GeoDa ######################################################################### diff --git a/BuildTools/ubuntu/GNUmakefile b/BuildTools/ubuntu/GNUmakefile index 89ba1bb65..20717312d 100644 --- a/BuildTools/ubuntu/GNUmakefile +++ b/BuildTools/ubuntu/GNUmakefile @@ -10,8 +10,8 @@ default: compile-geoda app: build-geoda-mac -compile-geoda: algorithms-target dataviewer-target dialogtools-target \ - explore-target libgdiam-target regression-target \ +compile-geoda: ogl-target io-target algorithms-target dataviewer-target dialogtools-target \ + knn-target explore-target libgdiam-target regression-target \ shapeoperations-target resource-target varcalc-target \ geoda-target @@ -23,6 +23,15 @@ test1: resource-target: (cd $(GeoDa_ROOT)/rc; $(MAKE) xrc; $(MAKE)) +ogl-target: + (cd $(GeoDa_ROOT)/ogl; $(MAKE)) + +knn-target: + (cd $(GeoDa_ROOT)/kNN; $(MAKE)) + +io-target: + (cd $(GeoDa_ROOT)/io; $(MAKE)) + algorithms-target: (cd $(GeoDa_ROOT)/Algorithms; $(MAKE)) @@ -58,9 +67,11 @@ build-geoda-mac: mkdir build/plugins mkdir build/basemap_cache mkdir build/web_plugins + mkdir build/lang $(LD) $(LDFLAGS) $(GeoDa_OBJ) $(LIBS) -o build/GeoDa cp run.sh build/run.sh chmod +x build/run.sh + cp -rf $(GeoDa_ROOT)/internationalization/lang/* build/lang cp $(GeoDa_ROOT)/rc/data_viewer_dialogs.xrc build/Resources cp $(GeoDa_ROOT)/rc/dialogs.xrc build/Resources cp $(GeoDa_ROOT)/rc/GeoDa.icns build/Resources @@ -81,7 +92,10 @@ build-geoda-mac: cp $(GEODA_HOME)/libraries/lib/libminizip.so.0.0.0 build/plugins/libminizip.so.0 cp $(GEODA_HOME)/libraries/lib/liburiparser.so.1.0.5 build/plugins/liburiparser.so.1 cp $(GEODA_HOME)/libraries/lib/libgeos-3.3.8.so build/plugins/libgeos-3.3.8.so + cp $(GEODA_HOME)/libraries/lib/libcurl.so.4.4.0 build/plugins/libcurl.so.4 + cp $(GEODA_HOME)/libraries/lib/libcares.so.2.1.0 build/plugins/libcares.so.2 cp $(GEODA_HOME)/libraries/share/gdal/* build/gdaldata + cp $(GEODA_HOME)/../CommonDistFiles/cache.sqlite build/cache.sqlite cp -rf $(GEODA_HOME)/../CommonDistFiles/web_plugins/* build/web_plugins clean: diff --git a/BuildTools/ubuntu/GNUmakefile1804 b/BuildTools/ubuntu/GNUmakefile1804 new file mode 100644 index 000000000..82bdaf5ad --- /dev/null +++ b/BuildTools/ubuntu/GNUmakefile1804 @@ -0,0 +1,82 @@ +ifndef GEODA_HOME +$(error You have to setup GEODA_HOME variable e.g. export GEODA_HOME=PWD, or run build.sh) +endif + +include ../../GeoDamake.opt + +GeoDa_OBJ = $(wildcard $(GeoDa_ROOT)/o/*.o) + +default: compile-geoda + +app: build-geoda-mac + +compile-geoda: io-target algorithms-target dataviewer-target dialogtools-target \ + knn-target explore-target libgdiam-target regression-target \ + shapeoperations-target resource-target varcalc-target \ + geoda-target + +conf = `./libraries/bin/wx-config --libs` + +test1: + @echo test $(WX_HEADER) $(LIBS) + +resource-target: + (cd $(GeoDa_ROOT)/rc; $(MAKE) xrc; $(MAKE)) + +knn-target: + (cd $(GeoDa_ROOT)/kNN; $(MAKE)) + +io-target: + (cd $(GeoDa_ROOT)/io; $(MAKE)) + +algorithms-target: + (cd $(GeoDa_ROOT)/Algorithms; $(MAKE)) + +dataviewer-target: + (cd $(GeoDa_ROOT)/DataViewer; $(MAKE)) + +dialogtools-target: + (cd $(GeoDa_ROOT)/DialogTools; $(MAKE)) + +explore-target: + (cd $(GeoDa_ROOT)/Explore; $(MAKE)) + +libgdiam-target: + (cd $(GeoDa_ROOT)/libgdiam; $(MAKE)) + +regression-target: + (cd $(GeoDa_ROOT)/Regression; $(MAKE)) + +shapeoperations-target: + (cd $(GeoDa_ROOT)/ShapeOperations; $(MAKE)) + +varcalc-target: + (cd $(GeoDa_ROOT)/VarCalc; $(MAKE)) + +geoda-target: + (cd $(GeoDa_ROOT); $(MAKE)) + +build-geoda-mac: + rm -rf build + mkdir -p build + mkdir build/Resources + mkdir build/gdaldata + mkdir build/plugins + mkdir build/basemap_cache + mkdir build/web_plugins + $(LD) $(LDFLAGS) $(GeoDa_OBJ) $(LIBS) -o build/GeoDa + cp run.sh build/run.sh + chmod +x build/run.sh + cp $(GeoDa_ROOT)/rc/data_viewer_dialogs.xrc build/Resources + cp $(GeoDa_ROOT)/rc/dialogs.xrc build/Resources + cp $(GeoDa_ROOT)/rc/GeoDa.icns build/Resources + cp $(GeoDa_ROOT)/rc/menus.xrc build/Resources + cp $(GeoDa_ROOT)/rc/toolbar.xrc build/Resources + cp $(GEODA_HOME)/libraries/lib/libcares.so.2.1.0 build/plugins/libcares.so.2 + cp /usr/share/gdal/2.2/* build/gdaldata + cp $(GEODA_HOME)/../CommonDistFiles/cache.sqlite build/cache.sqlite + cp -rf $(GEODA_HOME)/../CommonDistFiles/web_plugins/* build/web_plugins + +clean: + rm -f ../../o/* + rm -rf build diff --git a/BuildTools/ubuntu/build64.sh b/BuildTools/ubuntu/build64.sh index 3c28ab7ef..df0a3d542 100755 --- a/BuildTools/ubuntu/build64.sh +++ b/BuildTools/ubuntu/build64.sh @@ -33,7 +33,7 @@ read -p "Do you want to install pre-requisites (e.g. libreadline, zlib, libexpat echo if [[ $REPLY =~ ^[Yy]$ ]]; then sudo apt-get update - sudo apt-get install g++ libssl-dev libreadline6-dev zlib1g-dev libexpat1-dev dh-autoreconf libcurl4-gnutls-dev libgtk-3-dev libwebkit-dev mesa-common-dev freeglut3-dev libglu1-mesa-dev libgl1-mesa-dev libgtk2.0-dev + sudo apt-get install g++ libssl-dev libreadline6-dev zlib1g-dev libexpat1-dev dh-autoreconf libcurl4-openssl-dev libgtk-3-dev libwebkit-dev mesa-common-dev freeglut3-dev libglu1-mesa-dev libgl1-mesa-dev libgtk2.0-dev # for 14.10, experimenting with adding librtmp-dev, libidn11-dev and libldap-dev fi diff --git a/BuildTools/ubuntu/build64_18.04.sh b/BuildTools/ubuntu/build64_18.04.sh new file mode 100755 index 000000000..4c1faa14c --- /dev/null +++ b/BuildTools/ubuntu/build64_18.04.sh @@ -0,0 +1,618 @@ +#!/bin/bash +############################################################################# +# ./build.sh +# ./build.sh [CPU] +# ./build.sh 8 (with debug) +# ./build.sh [CPU] [NODEBUG, true=1 false=0(default)] +# ./build.sh 8 1 (no debug) +############################################################################# +CPUS=2 +NODEBUG=1 + +if ! type "cmake" > /dev/null; then + echo "You need to install cmake to run this script." + sudo apt-get install cmake +fi + +if ! type "g++" > /dev/null; then + echo "You need to install g++/gcc version 6 to run this script." + sudo apt-get install g++-5 + sudo apt-get install gcc-5 +fi + +if ! type "svn" > /dev/null; then + echo "You need to install SVN to run this script." + sudo apt-get install subversion +fi + +if ! type "curl" > /dev/null; then + echo "You need to install curl to run this script." + sudo apt-get install curl +fi + +read -p "Do you want to install pre-requisites (e.g. libreadline, zlib, libexpat, libcurl ...)?[y/n]" -n 1 -r +echo +if [[ $REPLY =~ ^[Yy]$ ]]; then + sudo apt-get update + sudo apt-get install libssl-dev + sudo apt-get install libreadline-dev + sudo apt-get install zlib1g-dev + sudo apt-get install libexpat1-dev + sudo apt-get install dh-autoreconf + sudo apt-get install libcurl4-openssl-dev + sudo apt-get install libgtk-3-dev + sudo apt-get install libwebkit-dev + sudo apt-get install libwebkitgtk-dev + sudo apt-get install mesa-common-dev + sudo apt-get install freeglut3-dev + sudo apt-get install libglu1-mesa-dev + sudo apt-get install libgl1-mesa-dev + sudo apt-get install libgtk2.0-dev + sudo apt-get install librtmp-dev + sudo apt-get install libidn11-dev + sudo apt-get install libldap-dev +fi + +unset ORACLE_HOME +export GEODA_HOME=$PWD +PREFIX=$GEODA_HOME/libraries +DOWNLOAD_HOME=$GEODA_HOME/temp +echo $PREFIX + +MAKER="make CC=gcc-5 CPP=g++-5 CXX=g++-5 LD=g++-5 -j $CPUS" +export CFLAGS="-m64" +export CXXFLAGS="-m64" +export LDFLAGS="-m64 -L/usr/lib/x86_64-linux-gnu" + +if ! [ -d $DOWNLOAD_HOME ]; then + mkdir $DOWNLOAD_HOME +fi + +if ! [ -d $PREFIX ]; then + mkdir $PREFIX +fi + +######################################################################### +# install library function +######################################################################### +install_library() +{ + LIB_NAME=$1 + LIB_URL=$2 + LIB_CHECKER=$3 + LIB_FILENAME=$(basename "$LIB_URL") + CONFIGURE_FLAGS=$4 + echo "" + echo "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%" + echo "% Building: $LIB_FILENAME" + echo "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%" + + cd $DOWNLOAD_HOME + + if ! [ -f "$LIB_FILENAME" ] ; then + echo "$LIB_FILENAME not found. Downloading..." + curl -O $LIB_URL + else + echo "$LIB_FILENAME found. Download skipped." + fi + + if ! [ -d "$LIB_NAME" ] ; then + echo "Directory $LIB_NAME not found. Expanding..." + tar -xf $LIB_FILENAME + else + echo "Directory $LIB_NAME found. File expansion skipped." + fi + + if ! [ -f "$PREFIX/lib/$LIB_CHECKER" ] ; then + cd $LIB_NAME + chmod +x configure + ./configure CFLAGS="-m64" CXXFLAGS="-m64" LDFLAGS="-m64 -L/usr/lib/x86_64-linux-gnu" --prefix=$PREFIX $CONFIGURE_FLAGS + $MAKER + make install + fi + if ! [ -f "$PREFIX/lib/$LIB_CHECKER" ] ; then + echo "Error! Exit" + exit + fi +} +######################################################################### +# install libiConv +######################################################################### +echo "" +echo "%%%%%%%%%%%%%%%%%%%%%%" +echo "% Building: libiConv %" +echo "%%%%%%%%%%%%%%%%%%%%%%" +{ + LIB_NAME="libiconv-1.13" + LIB_URL="http://ftp.gnu.org/pub/gnu/libiconv/libiconv-1.13.tar.gz" + LIB_CHECKER="libiconv.a" + LIB_FILENAME="libiconv-1.13.tar.gz" + echo $LIB_FILENAME + + cd $DOWNLOAD_HOME + if ! [ -d "$LIB_NAME" ] ; then + curl -O $LIB_URL + tar -xf $LIB_FILENAME + fi + + if ! [ -f "$PREFIX/lib/$LIB_CHECKER" ] ; then + cd $LIB_NAME + chmod +x configure + ./configure --enable-static --prefix=$PREFIX + $MAKER + make install + fi + if ! [ -f "$PREFIX/lib/$LIB_CHECKER" ] ; then + echo "Error! Exit" + exit + fi +} + +######################################################################### +# install c-ares -- for cURL, prevent crash on Mac oSx with threads +######################################################################### +install_library c-ares-1.10.0 https://c-ares.haxx.se/download/c-ares-1.10.0.tar.gz libcares.a + + +######################################################################### +# install cURL +######################################################################### + +LIB_NAME=curl-7.61.0 +LIB_CHECKER=libcurl.a +LIB_URL=https://curl.haxx.se/download/curl-7.61.0.tar.gz +LIB_FILENAME=curl-7.61.0.tar.gz +echo $LIB_NAME + +cd $DOWNLOAD_HOME + +if ! [ -d "$LIB_NAME" ] ; then + curl -O $LIB_URL + unzip $LIB_FILENAME +fi + +if ! [ -d "$LIB_NAME" ]; then + tar -xf $LIB_FILENAME +fi + +if ! [ -f "$PREFIX/lib/$LIB_CHECKER" ] ; then + cd $LIB_NAME + ./configure --enable-ares=$PREFIX CC="$GDA_CC" CFLAGS="$GDA_CFLAGS" CXX="$GDA_CXX" CXXFLAGS="$GDA_CXXFLAGS" LDFLAGS="$GDA_LDFLAGS" --prefix=$PREFIX --without-librtmp + $MAKER + make install +fi + +if ! [ -f "$PREFIX/lib/$LIB_CHECKER" ] ; then + echo "Error! Exit" + exit +fi + +######################################################################### +# install Xerces +######################################################################### +echo "" +echo "%%%%%%%%%%%%%%%%%%%%" +echo "% Building: Xerces %" +echo "%%%%%%%%%%%%%%%%%%%%" +{ + LIB_NAME="xerces-c-3.1.1" + LIB_URL="https://s3.us-east-2.amazonaws.com/geodabuild/xerces-c-3.1.1.tar.gz" + LIB_CHECKER="libxerces-c.a" + LIB_FILENAME=$(basename "$LIB_URL" ".tar") + echo $LIB_FILENAME + + cd $DOWNLOAD_HOME + if ! [ -d "$LIB_NAME" ] ; then + curl -O $LIB_URL + tar -xf $LIB_FILENAME + fi + + if ! [ -f "$PREFIX/lib/$LIB_CHECKER" ] ; then + cd $LIB_NAME + chmod +x configure + ./configure --prefix=$PREFIX + chmod +x config/pretty-make + $MAKER + make install + fi + + if ! [ -f "$PREFIX/lib/$LIB_CHECKER" ] ; then + echo "Error! Exit" + exit + fi +} + +######################################################################### +# install GEOS +######################################################################### +install_library geos-3.6.2 https://download.osgeo.org/geos/geos-3.6.2.tar.bz2 libgeos.a + +######################################################################### +# install PROJ.4 +######################################################################### +install_library proj-4.8.0 https://s3.us-east-2.amazonaws.com/geodabuild/proj-4.8.0.tar.gz libproj.a + +######################################################################### +# install FreeXL +######################################################################### +install_library freexl-1.0.0f https://s3.us-east-2.amazonaws.com/geodabuild/freexl-1.0.0f.tar.gz libfreexl.a + +######################################################################### +# install SQLite +######################################################################### +install_library sqlite-autoconf-3071602 https://s3.us-east-2.amazonaws.com/geodabuild/sqlite-autoconf-3071602.tar.gz libsqlite3.a + +######################################################################### +# install PostgreSQL +######################################################################### +# libreadline, zlib +echo "install libreadline, zlib" +install_library postgresql-9.2.4 https://s3.us-east-2.amazonaws.com/geodabuild/postgresql-9.2.4.tar.bz2 libpq.a + +######################################################################### +# install libjpeg +######################################################################### +install_library jpeg-8 https://s3.us-east-2.amazonaws.com/geodabuild/jpegsrc.v8.tar.gz libjpeg.a + +######################################################################### +# install libkml requires 1.3 +######################################################################### +echo "" +echo "%%%%%%%%%%%%%%%%%%%%" +echo "% Building: libkml %" +echo "%%%%%%%%%%%%%%%%%%%%" +# libexpat,libcurl4-gnutls-dev +#install_library libkml-1.2.0 https://libkml.googlecode.com/files/libkml-1.2.0.tar.gz libkmlbase.a +{ + LIB_NAME="libkml" + LIB_CHECKER="libkmlbase.a" + LIB_URL=https://s3.us-east-2.amazonaws.com/geodabuild/libkml-r680.tar.gz + LIB_FILENAME=libkml-r680.tar.gz + echo $LIB_NAME + + cd $DOWNLOAD_HOME + if ! [ -d "$LIB_NAME" ] ; then + curl -O $LIB_URL + fi + + if ! [ -d "$LIB_NAME" ]; then + tar -xf $LIB_FILENAME + fi + + if ! [ -f "$PREFIX/lib/$LIB_CHECKER" ] ; then + sudo apt-get install libexpat1-dev + cp -rf ../dep/"$LIB_NAME" . + cd $LIB_NAME + ./autogen.sh + chmod +x configure + ./configure CXXFLAGS="-Wno-long-long" --prefix=$PREFIX + sed -i.old "/gtest-death-test.Plo/d" third_party/Makefile + sed -i.old "/gtest-filepath.Plo/d" third_party/Makefile + sed -i.old "/gtest-port.Plo/d" third_party/Makefile + sed -i.old "/gtest-test-part.Plo/d" third_party/Makefile + sed -i.old "/gtest-typed-test.Plo/d" third_party/Makefile + sed -i.old "/gtest-test.Plo/d" third_party/Makefile + sed -i.old "/gtest.Plo/d" third_party/Makefile + sed -i.old "/gtest_main.Plo/d" third_party/Makefile + sed -i.old "/UriCommon.Plo/d" third_party/Makefile + sed -i.old "/UriCompare.Plo/d" third_party/Makefile + sed -i.old "/UriEscape.Plo/d" third_party/Makefile + sed -i.old "/UriFile.Plo/d" third_party/Makefile + sed -i.old "/UriIp4.Plo/d" third_party/Makefile + sed -i.old "/UriIp4Base.Plo/d" third_party/Makefile + sed -i.old "/UriNormalize.Plo/d" third_party/Makefile + sed -i.old "/UriNormalizeBase.Plo/d" third_party/Makefile + sed -i.old "/UriParse.Plo/d" third_party/Makefile + sed -i.old "/UriParseBase.Plo/d" third_party/Makefile + sed -i.old "/UriQuery.Plo/d" third_party/Makefile + sed -i.old "/UriRecompose.Plo/d" third_party/Makefile + sed -i.old "/UriResolve.Plo/d" third_party/Makefile + sed -i.old "/UriShorten.Plo/d" third_party/Makefile + sed -i.old "/ioapi.Plo/d" third_party/Makefile + sed -i.old "/iomem_simple.Plo/d" third_party/Makefile + sed -i.old "/zip.Plo/d" third_party/Makefile + #$MAKER + sed -i.old "s/examples//g" Makefile + make third_party + make src + make testdata + make install + fi + + if ! [ -f "$PREFIX/lib/$LIB_CHECKER" ] ; then + echo "Error! Exit" + exit + fi +} + +######################################################################### +# install SpatiaLite +######################################################################### +echo "" +echo "%%%%%%%%%%%%%%%%%%%%%%%%" +echo "% Building: Spatialite %" +echo "%%%%%%%%%%%%%%%%%%%%%%%%" +{ + LIB_NAME=libspatialite-4.0.0 + LIB_URL=https://s3.us-east-2.amazonaws.com/geodabuild/libspatialite-4.0.0.tar.gz + LIB_FILENAME=$(basename "$LIB_URL" ".tar") + LIB_CHECKER=libspatialite.a + echo $LIB_FILENAME + + cd $DOWNLOAD_HOME + if ! [ -d "$LIB_NAME" ] ; then + curl -O $LIB_URL + tar -xf $LIB_FILENAME + fi + + if ! [ -f "$PREFIX/lib/$LIB_CHECKER" ] ; then + cd $LIB_NAME + chmod +x configure + ./configure CFLAGS="-I$PREFIX/include" CXXFLAGS="-I$PREFIX/include" LDFLAGS="-L$PREFIX/lib -liconv" --prefix=$PREFIX --with-geosconfig=$PREFIX/bin/geos-config + $MAKER + make install + fi + + if ! [ -f "$PREFIX/lib/$LIB_CHECKER" ] ; then + echo "Error! Exit" + exit + fi +} + +######################################################################### +# Eigen3 +######################################################################### +LIB_NAME=eigen3 +LIB_URL=https://s3.us-east-2.amazonaws.com/geodabuild/eigen3.zip +LIB_CHECKER=Dense +LIB_FILENAME=$LIB_NAME.zip +echo $LIB_FILENAME +cd $DOWNLOAD_HOME + +if ! [ -f "$LIB_FILENAME" ] ; then + curl -O $LIB_URL +fi + +if ! [ -d "$LIB_NAME" ]; then + unzip $LIB_FILENAME +fi + +cd $DOWNLOAD_HOME/$LIB_NAME +if ! [ -f "$PREFIX/include/eigen3/Eigen/$LIB_CHECKER" ] ; then + mkdir bld + cd bld + cmake .. -DCMAKE_INSTALL_PREFIX=$PREFIX + make install +fi + +if ! [ -f "$PREFIX/include/eigen3/Eigen/$LIB_CHECKER" ] ; then + echo "Error! Exit" + exit +fi +######################################################################### +# install boost library +######################################################################### +echo "" +echo "%%%%%%%%%%%%%%%%%%%%%%%%" +echo "% Building: Boost 1.57 %" +echo "%%%%%%%%%%%%%%%%%%%%%%%%" +{ + LIB_NAME=boost_1_57_0 + LIB_URL=https://s3.us-east-2.amazonaws.com/geodabuild/boost_1_57_0.tar.gz + LIB_FILENAME=boost_1_57_0.tar.gz + LIB_CHECKER=libboost_thread.a + echo $LIB_FILENAME + + cd $DOWNLOAD_HOME + if ! [ -f "$LIB_FILENAME" ]; then + echo "$LIB_FILENAME not found. Downloading..." + curl -O $LIB_URL + else + echo "$LIB_FILENAME found. Skipping download." + fi + + if ! [ -d "$LIB_NAME" ]; then + echo "Directory $LIB_NAME not found. Expanding archive." + tar -xf $LIB_FILENAME + else + echo "Directory $LIB_NAME found. Skipping expansion." + fi + + if ! [ -f "$GEODA_HOME/temp/$LIB_NAME/stage/lib/$LIB_CHECKER" ] ; then + echo "$LIB_CHECKER not found. Building Boost..." + cd $PREFIX/include + rm boost + ln -s $DOWNLOAD_HOME/boost_1_57_0 boost + cd $DOWNLOAD_HOME/boost_1_57_0 + chmod +x bootstrap.sh + #chmod +x tools/build/v2/engine/build.sh + ./bootstrap.sh + chmod +x b2 + ./b2 --toolset=gcc-5 --with-thread --with-date_time --with-chrono --with-system link=static threading=multi stage + fi + + if ! [ -f "$GEODA_HOME/temp/$LIB_NAME/stage/lib/$LIB_CHECKER" ] ; then + echo "Error: Target library $LIB_CHECKER not found. Exiting build." + exit + fi +} + +######################################################################### +# install JSON Spirit +######################################################################### +echo "" +echo "%%%%%%%%%%%%%%%%%%%%%%%%%" +echo "% Building: JSON Spirit %" +echo "%%%%%%%%%%%%%%%%%%%%%%%%%" +LIB_NAME="json_spirit_v4.08" +LIB_URL="https://s3.us-east-2.amazonaws.com/geodabuild/json_spirit_v4.08.zip" +LIB_CHECKER="libjson_spirit.a" +LIB_FILENAME="json_spirit_v4.08.zip" +echo $LIB_FILENAME + +cd $DOWNLOAD_HOME + +if ! [ -d "$LIB_NAME" ]; then + curl -O https://s3.us-east-2.amazonaws.com/geodabuild/json_spirit_v4.08.zip + unzip $LIB_FILENAME +fi + +cd $DOWNLOAD_HOME/$LIB_NAME + +if ! [ -f "$PREFIX/lib/$LIB_CHECKER" ] ; then + cp $GEODA_HOME/dep/json_spirit/CMakeLists.txt . + mkdir bld + cd bld + CC=$GDA_CC CXX=$GDA_CXX CFLAGS=$GDA_CFLAGS CXXFLAGS=$GDA_CXXFLAGS LDFLAGS=$GDA_LDFLAGS cmake .. + make + rm -rf "$PREFIX/include/json_spirit" + rm -f "$PREFIX/lib/$LIB_CHECKER" + mkdir "$PREFIX/include/json_spirit" + echo "Copying JSON Sprit includes..." + cp -R "../json_spirit" "$PREFIX/include/." + echo "Copying libjson_spirit.a" + cp json_spirit/libjson_spirit.a "$PREFIX/lib/." +fi + +if ! [ -f "$PREFIX/lib/$LIB_CHECKER" ] ; then + echo "Error! Exit" + exit +fi + +######################################################################### +# install CLAPACK +######################################################################### +echo "" +echo "%%%%%%%%%%%%%%%%%%%%%%%%%%%" +echo "% Building: CLAPACK 3.2.1 %" +echo "%%%%%%%%%%%%%%%%%%%%%%%%%%%" +{ + CLAPACK_NAME="CLAPACK-3.2.1" + LIB_CHECKER="libf2c.a" + echo $CLAPACK_NAME + + cd $DOWNLOAD_HOME + if ! [ -d "$CLAPACK_NAME" ]; then + curl -O https://s3.us-east-2.amazonaws.com/geodabuild/clapack.tgz + tar -xvf clapack.tgz + fi + + cp -rf $GEODA_HOME/dep/$CLAPACK_NAME . + cd $CLAPACK_NAME + if ! [ -f "libf2c.a" ] || ! [ -f "blas.a" ] || ! [ -f "lapack.a" ]; then + cp make.inc.example make.inc + $MAKER f2clib + cp F2CLIBS/libf2c.a . + $MAKER blaslib + cd INSTALL + $MAKER + cd .. + cd SRC + $MAKER + cd .. + $MAKER + mv -f blas_LINUX.a blas.a + mv -f lapack_LINUX.a lapack.a + mv -f tmglib_LINUX.a tmglib.a + cd .. + fi + + if ! [ -f "$GEODA_HOME/temp/$CLAPACK_NAME/$LIB_CHECKER" ] ; then + echo "Error! Exit" + exit + fi +} + +######################################################################### +# install json-c +######################################################################### +echo "" +echo "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%" +echo "% Building: json-c " +echo "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%" +{ + + LIB_NAME=json-c + LIB_CHECKER=libjson-c.a + + if ! [ -d "$LIB_NAME" ] ; then + git clone https://github.com/json-c/json-c.git + fi + + + if ! [ -f "$PREFIX/lib/$LIB_CHECKER" ] ; then + cd $LIB_NAME + sh autogen.sh + ./configure --prefix=$PREFIX + make + make install + fi + + #if ! [ -f "$PREFIX/lib/$LIB_CHECKER" ] ; then + #echo "Error! Exit" + #exit + #fi +} + + +######################################################################### +# install wxWidgets library +######################################################################### +echo "" +echo "%%%%%%%%%%%%%%%%%%%%%%%%%%%%" +echo "% Building wxWidgets 3.0.2 %" +echo "%%%%%%%%%%%%%%%%%%%%%%%%%%%%" +# sudo apt-get install libgtk2.0-dev libglu1-mesa-dev libgl1-mesa-dev +{ + LIB_NAME=wxWidgets-3.1.0 + LIB_URL="https://s3.us-east-2.amazonaws.com/geodabuild/wxWidgets-3.1.0.tar.bz2" + + LIB_FILENAME=$(basename "$LIB_URL" ".tar") + LIB_CHECKER=wx-config + echo $LIB_FILENAME + + cd $DOWNLOAD_HOME + if ! [ -f "$LIB_FILENAME" ] ; then + curl -k -o $LIB_FILENAME $LIB_URL + fi + + if ! [ -d "$LIB_NAME" ]; then + tar -xf $LIB_FILENAME + fi + + if ! [ -f "$PREFIX/bin/$LIB_CHECKER" ] ; then + cd $LIB_NAME + cp -rf $GEODA_HOME/dep/$LIB_NAME/* . + chmod +x configure + chmod +x src/stc/gen_iface.py + CC=gcc-5 CXX=g++-5 CPP=g++-5 LD=g++-5 ./configure --with-gtk=2 --enable-ascii --disable-shared --disable-monolithic --with-opengl --enable-postscript --without-libtiff --disable-debug --enable-webview --prefix=$PREFIX + $MAKE + make install + cd .. + fi + + if ! [ -f "$PREFIX/bin/$LIB_CHECKER" ] ; then + echo "Error! Exit" + exit + fi +} + +######################################################################### +# build GeoDa +######################################################################### +echo "" +echo "%%%%%%%%%%%%%%%%%%%" +echo "% Building: GeoDa %" +echo "%%%%%%%%%%%%%%%%%%%" +{ + cd $GEODA_HOME + cp ../../GeoDamake.ubuntu.opt ../../GeoDamake.opt + mkdir ../../o + $MAKER + cp GNUmakefile1804 GNUmakefile + make app + #cp plugins/x64/*.so build/plugins/ + cp ../CommonDistFiles/cache.sqlite build/ + cp ../CommonDistFiles/geoda_prefs.sqlite build/ + cp ../CommonDistFiles/geoda_prefs.json build/ +} diff --git a/BuildTools/ubuntu/create_deb.sh b/BuildTools/ubuntu/create_deb.sh index 7a88f66a1..05075e805 100755 --- a/BuildTools/ubuntu/create_deb.sh +++ b/BuildTools/ubuntu/create_deb.sh @@ -11,8 +11,13 @@ if ! [ -f build/GeoDa ]; then exit fi + rm -rf product -cp -rf package product +if [ $# -ne 1 ]; then + cp -rf package product +else + cp -rf package_$1 product +fi chmod +x product/DEBIAN/postinst mkdir product/usr/local @@ -32,6 +37,9 @@ if [ $MACHINE_TYPE == 'x86_64' ]; then mv product/DEBIAN/control64 product/DEBIAN/control fi -rm -f GeoDa-1.10-Ubuntu-XXbit.deb -dpkg -b product/ GeoDa-1.10-Ubuntu-XXbit.deb - +rm -f *.deb +if [ $# -ne 1 ]; then + dpkg -b product/ geoda_1.12-1xenial1.deb +else + dpkg -b product/ geoda_1.12-1$1.deb +fi diff --git a/BuildTools/ubuntu/create_deb_18.04.sh b/BuildTools/ubuntu/create_deb_18.04.sh new file mode 100755 index 000000000..998d2e122 --- /dev/null +++ b/BuildTools/ubuntu/create_deb_18.04.sh @@ -0,0 +1,45 @@ +#!/bin/bash + + +if ! [ -d build ]; then + echo "Please run build.sh to build GeoDa executable file first." + exit +fi + +if ! [ -f build/GeoDa ]; then + echo "Please run build.sh to build GeoDa executable file first." + exit +fi + + +rm -rf product +if [ $# -ne 1 ]; then + cp -rf package product +else + cp -rf package_$1 product +fi + +chmod +x product/DEBIAN/postinst +mkdir product/usr/local +mkdir product/usr/bin +mkdir product/usr/local/geoda +cp -rf build/* product/usr/local/geoda/ +cp run_geoda.sh product/usr/bin/ + +cd product +find . -name .svn |xargs rm -rf +cd .. + +MACHINE_TYPE=`uname -m` +if [ $MACHINE_TYPE == 'x86_64' ]; then + # 64-bit platform + rm product/DEBIAN/control + mv product/DEBIAN/control1804 product/DEBIAN/control +fi + +rm -f *.deb +if [ $# -ne 1 ]; then + dpkg -b product/ geoda_1.12-1xenial1.deb +else + dpkg -b product/ geoda_1.12-1$1.deb +fi diff --git a/BuildTools/ubuntu/dep/gdal-1.9.2/GDALmake64.opt b/BuildTools/ubuntu/dep/gdal-1.9.2/GDALmake64.opt index 44cdd5669..d6f915a09 100644 --- a/BuildTools/ubuntu/dep/gdal-1.9.2/GDALmake64.opt +++ b/BuildTools/ubuntu/dep/gdal-1.9.2/GDALmake64.opt @@ -21,9 +21,9 @@ LIBTOOL_FINISH = /bin/true OBJ_EXT = o endif -CC = $(LIBTOOL_COMPILE_CC) gcc -CXX = $(LIBTOOL_COMPILE_CXX) g++ -LD = $(LIBTOOL_LINK) g++ +CC = $(LIBTOOL_COMPILE_CC) gcc-5 +CXX = $(LIBTOOL_COMPILE_CXX) g++-5 +LD = $(LIBTOOL_LINK) g++-5 RM = $(LIBTOOL_CLEAN) /bin/rm -f *.lo INSTALL = $(LIBTOOL_INSTALL) $(GDAL_ROOT)/install-sh -c INSTALL_LIB = $(LIBTOOL_INSTALL) $(GDAL_ROOT)/install-sh -c @@ -69,8 +69,8 @@ INST_MAN = ${prefix}/share/gdal/man INST_HTML = $(HOME)/www/gdal CPPFLAGS = -I$(GDAL_ROOT)/port -I$(GDAL_ROOT)/gcore -I$(GDAL_ROOT)/ogr -I$(GDAL_ROOT)/ogr/ogrsf_frmts -I$(GDAL_ROOT)/alg -CFLAGS = -O2 -Wall -Wdeclaration-after-statement $(USER_DEFS) -CXXFLAGS = -O2 -Wall $(USER_DEFS) +CFLAGS = -O2 -Wall -Wdeclaration-after-statement $(USER_DEFS) -DGDAL_COMPILATION +CXXFLAGS = -O2 -Wall $(USER_DEFS) -DGDAL_COMPILATION LDFLAGS = RANLIB = ranlib @@ -128,8 +128,8 @@ INGRES_INC = # MySQL support. # HAVE_MYSQL = yes -MYSQL_LIB = $(GEODA_HOME)/temp/mysql-5.6.14/bld/libmysql/libmysqlclient.a -lpthread -MYSQL_INC = -I$(GEODA_HOME)/temp/mysql-5.6.14/include -I$(GEODA_HOME)/temp/mysql-5.6.14/bld/include +MYSQL_LIB = /usr/lib/x86_64-linux-gnu/libmysqlclient.a -lpthread +MYSQL_INC = -I/usr/include/mysql -I$(GEODA_HOME)/dep/mysql-5.6.14/include LIBS += $(MYSQL_LIB) # diff --git a/BuildTools/ubuntu/package/DEBIAN/control b/BuildTools/ubuntu/package/DEBIAN/control index 3ab7f7146..1ebbfb6b5 100644 --- a/BuildTools/ubuntu/package/DEBIAN/control +++ b/BuildTools/ubuntu/package/DEBIAN/control @@ -1,13 +1,13 @@ Package: geoda -Version: 1.10 +Version: 1.12-1xenial1 Architecture: i386 Priority: optional Section: graphics Installed-Size: 88128 -Depends: zlib1g, libexpat1, freeglut3, libreadline6, libcurl4-gnutls-dev, libgtk-3-0, libc-dev-bin, libssl0.9.8, libwebkitgtk-1.0-0 -Maintainer: Luc Anselin < luc.anselin@asu.edu > +Depends: zlib1g, libexpat1, freeglut3, libreadline6, libgtk-3-0, libc-dev-bin, libssl0.9.8, libwebkitgtk-1.0-0 +Maintainer: Luc Anselin < anselin@uchicago.edu > Provides: geoda -Homepage: http://geodacenter.asu.edu +Homepage: http://spatial.uchicago.edu Description: GeoDa Software GeoDa Software for Geospatial Analysis and Computation diff --git a/BuildTools/ubuntu/package/DEBIAN/control1804 b/BuildTools/ubuntu/package/DEBIAN/control1804 new file mode 100644 index 000000000..9ca5981ff --- /dev/null +++ b/BuildTools/ubuntu/package/DEBIAN/control1804 @@ -0,0 +1,13 @@ +Package: geoda +Version: 1.12-1xenial1 +Architecture: amd64 +Priority: optional +Section: graphics +Installed-Size: 88128 +Depends: libgdal-dev, zlib1g, libexpat1, freeglut3, libreadline7, libgtk-3-0, libc-dev-bin, libssl1.0.0, libwebkitgtk-1.0-0 +Maintainer: Luc Anselin < anselin@uchicago.edu > +Provides: geoda +Homepage: http://spatial.uchicago.edu +Description: GeoDa Software + GeoDa Software for Geospatial Analysis and Computation + diff --git a/BuildTools/ubuntu/package/DEBIAN/control64 b/BuildTools/ubuntu/package/DEBIAN/control64 index 225181447..e661ae1ee 100644 --- a/BuildTools/ubuntu/package/DEBIAN/control64 +++ b/BuildTools/ubuntu/package/DEBIAN/control64 @@ -1,13 +1,13 @@ Package: geoda -Version: 1.10 +Version: 1.12-1xenial1 Architecture: amd64 Priority: optional Section: graphics Installed-Size: 88128 -Depends: zlib1g, libexpat1, freeglut3, libreadline6, libcurl4-gnutls-dev, libgtk-3-0, libc-dev-bin, libssl1.0.0, libwebkitgtk-1.0-0 -Maintainer: Luc Anselin < luc.anselin@asu.edu > +Depends: zlib1g, libexpat1, freeglut3, libreadline6, libgtk-3-0, libc-dev-bin, libssl1.0.0, libwebkitgtk-1.0-0 +Maintainer: Luc Anselin < anselin@uchicago.edu > Provides: geoda -Homepage: http://geodacenter.asu.edu +Homepage: http://spatial.uchicago.edu Description: GeoDa Software GeoDa Software for Geospatial Analysis and Computation diff --git a/BuildTools/ubuntu/package_trusty/DEBIAN/control b/BuildTools/ubuntu/package_trusty/DEBIAN/control new file mode 100644 index 000000000..15f0e8861 --- /dev/null +++ b/BuildTools/ubuntu/package_trusty/DEBIAN/control @@ -0,0 +1,13 @@ +Package: geoda +Version: 1.12-1trusty1 +Architecture: i386 +Priority: optional +Section: graphics +Installed-Size: 88128 +Depends: zlib1g, libexpat1, freeglut3, libreadline6, libgtk-3-0, libc-dev-bin, libssl0.9.8, libwebkitgtk-1.0-0 +Maintainer: Luc Anselin < anselin@uchicago.edu > +Provides: geoda +Homepage: http://spatial.uchicago.edu +Description: GeoDa Software + GeoDa Software for Geospatial Analysis and Computation + diff --git a/BuildTools/ubuntu/package_trusty/DEBIAN/control1804 b/BuildTools/ubuntu/package_trusty/DEBIAN/control1804 new file mode 100644 index 000000000..9ca5981ff --- /dev/null +++ b/BuildTools/ubuntu/package_trusty/DEBIAN/control1804 @@ -0,0 +1,13 @@ +Package: geoda +Version: 1.12-1xenial1 +Architecture: amd64 +Priority: optional +Section: graphics +Installed-Size: 88128 +Depends: libgdal-dev, zlib1g, libexpat1, freeglut3, libreadline7, libgtk-3-0, libc-dev-bin, libssl1.0.0, libwebkitgtk-1.0-0 +Maintainer: Luc Anselin < anselin@uchicago.edu > +Provides: geoda +Homepage: http://spatial.uchicago.edu +Description: GeoDa Software + GeoDa Software for Geospatial Analysis and Computation + diff --git a/BuildTools/ubuntu/package_trusty/DEBIAN/control64 b/BuildTools/ubuntu/package_trusty/DEBIAN/control64 new file mode 100644 index 000000000..60432e2f5 --- /dev/null +++ b/BuildTools/ubuntu/package_trusty/DEBIAN/control64 @@ -0,0 +1,13 @@ +Package: geoda +Version: 1.12-1trusty1 +Architecture: amd64 +Priority: optional +Section: graphics +Installed-Size: 88128 +Depends: zlib1g, libexpat1, freeglut3, libreadline6, libgtk-3-0, libc-dev-bin, libssl1.0.0, libwebkitgtk-1.0-0 +Maintainer: Luc Anselin < anselin@uchicago.edu > +Provides: geoda +Homepage: http://spatial.uchicago.edu +Description: GeoDa Software + GeoDa Software for Geospatial Analysis and Computation + diff --git a/BuildTools/ubuntu/package_trusty/DEBIAN/postinst b/BuildTools/ubuntu/package_trusty/DEBIAN/postinst new file mode 100755 index 000000000..f6bbaac96 --- /dev/null +++ b/BuildTools/ubuntu/package_trusty/DEBIAN/postinst @@ -0,0 +1,4 @@ +#!bin/sh + +chmod +x /usr/bin/run_geoda.sh +chmod +x /usr/local/geoda/GeoDa diff --git a/BuildTools/ubuntu/package_trusty/usr/share/applications/GeoDa.desktop b/BuildTools/ubuntu/package_trusty/usr/share/applications/GeoDa.desktop new file mode 100644 index 000000000..3d2e0a261 --- /dev/null +++ b/BuildTools/ubuntu/package_trusty/usr/share/applications/GeoDa.desktop @@ -0,0 +1,10 @@ +[Desktop Entry] +Version=1.0 +Type=Application +Name=GeoDa +GenericName=GeoDa Software +Comment=GeoDa Software +Exec=run_geoda.sh +TryExec=run_geoda.sh +Icon=geoda +Categories=Education diff --git a/BuildTools/ubuntu/package_trusty/usr/share/icons/hicolor/128x128/apps/geoda.png b/BuildTools/ubuntu/package_trusty/usr/share/icons/hicolor/128x128/apps/geoda.png new file mode 100644 index 000000000..5a5e2439f Binary files /dev/null and b/BuildTools/ubuntu/package_trusty/usr/share/icons/hicolor/128x128/apps/geoda.png differ diff --git a/BuildTools/ubuntu/package_trusty/usr/share/icons/hicolor/16x16/apps/geoda.png b/BuildTools/ubuntu/package_trusty/usr/share/icons/hicolor/16x16/apps/geoda.png new file mode 100644 index 000000000..a6f2b80e7 Binary files /dev/null and b/BuildTools/ubuntu/package_trusty/usr/share/icons/hicolor/16x16/apps/geoda.png differ diff --git a/BuildTools/ubuntu/package_trusty/usr/share/icons/hicolor/22x22/apps/geoda.png b/BuildTools/ubuntu/package_trusty/usr/share/icons/hicolor/22x22/apps/geoda.png new file mode 100644 index 000000000..ef5d9d437 Binary files /dev/null and b/BuildTools/ubuntu/package_trusty/usr/share/icons/hicolor/22x22/apps/geoda.png differ diff --git a/BuildTools/ubuntu/package_trusty/usr/share/icons/hicolor/24x24/apps/geoda.png b/BuildTools/ubuntu/package_trusty/usr/share/icons/hicolor/24x24/apps/geoda.png new file mode 100644 index 000000000..ac4111b4f Binary files /dev/null and b/BuildTools/ubuntu/package_trusty/usr/share/icons/hicolor/24x24/apps/geoda.png differ diff --git a/BuildTools/ubuntu/package_trusty/usr/share/icons/hicolor/32x32/apps/geoda.png b/BuildTools/ubuntu/package_trusty/usr/share/icons/hicolor/32x32/apps/geoda.png new file mode 100644 index 000000000..2115fb85b Binary files /dev/null and b/BuildTools/ubuntu/package_trusty/usr/share/icons/hicolor/32x32/apps/geoda.png differ diff --git a/BuildTools/ubuntu/package_trusty/usr/share/icons/hicolor/48x48/apps/geoda.png b/BuildTools/ubuntu/package_trusty/usr/share/icons/hicolor/48x48/apps/geoda.png new file mode 100644 index 000000000..5a5e2439f Binary files /dev/null and b/BuildTools/ubuntu/package_trusty/usr/share/icons/hicolor/48x48/apps/geoda.png differ diff --git a/BuildTools/ubuntu/package_trusty/usr/share/icons/hicolor/64x64/apps/geoda.png b/BuildTools/ubuntu/package_trusty/usr/share/icons/hicolor/64x64/apps/geoda.png new file mode 100644 index 000000000..5a5e2439f Binary files /dev/null and b/BuildTools/ubuntu/package_trusty/usr/share/icons/hicolor/64x64/apps/geoda.png differ diff --git a/BuildTools/ubuntu/package_trusty/usr/share/icons/hicolor/96x96/apps/geoda.png b/BuildTools/ubuntu/package_trusty/usr/share/icons/hicolor/96x96/apps/geoda.png new file mode 100644 index 000000000..5a5e2439f Binary files /dev/null and b/BuildTools/ubuntu/package_trusty/usr/share/icons/hicolor/96x96/apps/geoda.png differ diff --git a/BuildTools/ubuntu/run.sh b/BuildTools/ubuntu/run.sh index e59fd9b79..562c0bd7c 100755 --- a/BuildTools/ubuntu/run.sh +++ b/BuildTools/ubuntu/run.sh @@ -6,6 +6,7 @@ GEODA_HOME=$(cd "$(dirname "$0")"; pwd) export LD_LIBRARY_PATH=$GEODA_HOME/plugins:$ORACLE_HOME:$LD_LIBRARY_PATH export GDAL_DATA=$GEODA_HOME/gdaldata export OGR_DRIVER_PATH=$GEODA_HOME/plugins -chmod +x "$GEODA_HOME/plugins/*.so" -chmod +x "$GEODA_HOME/GeoDa" +chmod +x $GEODA_HOME/plugins/* +chmod +x $GEODA_HOME/cache.sqlite +chmod +x $GEODA_HOME/GeoDa exec "$GEODA_HOME/GeoDa" diff --git a/BuildTools/ubuntu/run_geoda.sh b/BuildTools/ubuntu/run_geoda.sh index 88e495f7d..53cf6509d 100755 --- a/BuildTools/ubuntu/run_geoda.sh +++ b/BuildTools/ubuntu/run_geoda.sh @@ -6,6 +6,7 @@ GEODA_HOME=/usr/local/geoda export LD_LIBRARY_PATH=$GEODA_HOME/plugins:$ORACLE_HOME:$LD_LIBRARY_PATH export GDAL_DATA=$GEODA_HOME/gdaldata export OGR_DRIVER_PATH=$GEODA_HOME/plugins -chmod +x "$GEODA_HOME/plugins/*.so" -chmod +x "$GEODA_HOME/GeoDa" +chmod +x $GEODA_HOME/plugins/* +chmod +x $GEODA_HOME/cache.sqlite +chmod +x $GEODA_HOME/GeoDa exec "$GEODA_HOME/GeoDa" diff --git a/BuildTools/windows/GeoDa.vcxproj b/BuildTools/windows/GeoDa.vcxproj index b63aa5aaa..38f33f604 100644 --- a/BuildTools/windows/GeoDa.vcxproj +++ b/BuildTools/windows/GeoDa.vcxproj @@ -103,7 +103,7 @@ Disabled - C:\OSGeo4W\include;temp\boost_1_57_0;temp\wxWidgets-3.1.0\include;temp\wxWidgets-3.1.0\lib\vc_dll\mswud;temp\json_spirit_v4.08;temp\eigen3;%(AdditionalIncludeDirectories) + C:\Intel\OpenCL\sdk\include;C:\OSGeo4W\include;temp\boost_1_57_0;temp\wxWidgets-3.1.0\include;temp\wxWidgets-3.1.0\lib\vc_dll\mswud;temp\json_spirit_v4.08;temp\eigen3;%(AdditionalIncludeDirectories) WIN32;DEBUG;_DEBUG;_WINDOWS;__WXMSW__;__WXDEBUG__;WXUSINGDLL;UNICODE;%(PreprocessorDefinitions) false EnableFastChecks @@ -122,8 +122,8 @@ temp\wxWidgets-3.1.0\include;%(AdditionalIncludeDirectories) - gdal_i.lib;libcurl.lib;libboost_thread-vc100-mt-gd-1_57.lib;BLAS.lib;clapack.lib;libf2c.lib;json_spirit_lib.lib;sqlite3_i.lib;GlU32.lib;OpenGL32.lib;wxmsw31ud.lib;wxmsw31ud_gl.lib;wxtiffd.lib;wxjpegd.lib;wxpngd.lib;wxzlibd.lib;wxregexud.lib;wxexpatd.lib;wsock32.lib;comctl32.lib;winmm.lib;rpcrt4.lib;%(AdditionalDependencies) - C:\OSGeo4W\lib;temp\wxWidgets-3.1.0\lib\vc_dll;temp\CLAPACK-3.1.1-VisualStudio\LIB\Win32;temp\boost_1_57_0\stage\lib;temp\json_spirit_v4.08\Debug;%(AdditionalLibraryDirectories) + opencl.lib;zlibstat.lib;gdal_i.lib;libcurl.lib;libboost_date_time-vc100-mt-gd-1_57.lib;libboost_thread-vc100-mt-gd-1_57.lib;BLAS.lib;clapack.lib;libf2c.lib;json_spirit_lib.lib;sqlite3_i.lib;GlU32.lib;OpenGL32.lib;wxmsw31ud.lib;wxmsw31ud_gl.lib;wxtiffd.lib;wxjpegd.lib;wxpngd.lib;wxzlibd.lib;wxregexud.lib;wxexpatd.lib;wsock32.lib;comctl32.lib;winmm.lib;rpcrt4.lib;%(AdditionalDependencies) + C:\Intel\OpenCL\sdk\lib\x86;dep\zlib\lib;C:\OSGeo4W\lib;temp\wxWidgets-3.1.0\lib\vc_dll;temp\CLAPACK-3.1.1-VisualStudio\LIB\Win32;temp\boost_1_57_0\stage\lib;temp\json_spirit_v4.08\Debug;%(AdditionalLibraryDirectories) false %(IgnoreSpecificDefaultLibraries) true @@ -154,8 +154,8 @@ temp\wxWidgets-3.1.0\include;%(AdditionalIncludeDirectories) - gdal_i.lib;libcurl.lib;libboost_thread-vc100-mt-gd-1_57.lib;BLAS.lib;clapack.lib;libf2c.lib;json_spirit_lib.lib;sqlite3_i.lib;GlU32.lib;OpenGL32.lib;wxmsw31ud.lib;wxmsw31ud_gl.lib;wxtiffd.lib;wxjpegd.lib;wxpngd.lib;wxzlibd.lib;wxregexud.lib;wxexpatd.lib;wsock32.lib;comctl32.lib;winmm.lib;rpcrt4.lib;%(AdditionalDependencies) - C:\OSGeo4W\lib;temp\wxWidgets-3.1.0\lib\vc_dll;temp\CLAPACK-3.1.1-VisualStudio\LIB\Win32;temp\boost_1_57_0\stage\lib;temp\json_spirit_v4.08\Debug;%(AdditionalLibraryDirectories) + opencl.lib;zlibstat.lib;gdal_i.lib;libcurl.lib;libboost_date_time-vc100-mt-gd-1_57.lib;libboost_thread-vc100-mt-gd-1_57.lib;BLAS.lib;clapack.lib;libf2c.lib;json_spirit_lib.lib;sqlite3_i.lib;GlU32.lib;OpenGL32.lib;wxmsw31ud.lib;wxmsw31ud_gl.lib;wxtiffd.lib;wxjpegd.lib;wxpngd.lib;wxzlibd.lib;wxregexud.lib;wxexpatd.lib;wsock32.lib;comctl32.lib;winmm.lib;rpcrt4.lib;%(AdditionalDependencies) + C:\Intel\OpenCL\sdk\lib\x64;dep\zlib\lib;C:\OSGeo4W\lib;temp\wxWidgets-3.1.0\lib\vc_dll;temp\CLAPACK-3.1.1-VisualStudio\LIB\Win32;temp\boost_1_57_0\stage\lib;temp\json_spirit_v4.08\Debug;%(AdditionalLibraryDirectories) false %(IgnoreSpecificDefaultLibraries) true @@ -167,7 +167,7 @@ Disabled - C:\OSGeo4W\include;temp\boost_1_57_0;temp\wxWidgets-3.1.0\include;temp\wxWidgets-3.1.0\lib\vc_x64_dll\mswud;temp\json_spirit_v4.08;temp\eigen3;%(AdditionalIncludeDirectories) + C:\Intel\OpenCL\sdk\include;dep\zlib\include;C:\OSGeo4W\include;temp\boost_1_57_0;temp\wxWidgets-3.1.0\include;temp\wxWidgets-3.1.0\lib\vc_x64_dll\mswud;temp\json_spirit_v4.08;temp\eigen3;%(AdditionalIncludeDirectories) WIN32;DEBUG;_DEBUG;_WINDOWS;__WXMSW__;__WXDEBUG__;WXUSINGDLL;UNICODE;%(PreprocessorDefinitions) false EnableFastChecks @@ -180,6 +180,8 @@ /MP %(AdditionalOptions) true false + + __WXMSW__;_UNICODE;_WINDOWS;NOPCH;WXUSINGDLL;%(PreprocessorDefinitions) @@ -187,8 +189,8 @@ temp\wxWidgets-3.1.0\include;%(AdditionalIncludeDirectories) - gdal_i.lib;libcurl.lib;libboost_thread-vc100-mt-gd-1_57.lib;BLAS.lib;clapack.lib;libf2c.lib;json_spirit_lib.lib;sqlite3_i.lib;GlU32.lib;OpenGL32.lib;wxmsw31ud.lib;wxmsw31ud_gl.lib;wxtiffd.lib;wxjpegd.lib;wxpngd.lib;wxzlibd.lib;wxregexud.lib;wxexpatd.lib;wsock32.lib;comctl32.lib;winmm.lib;rpcrt4.lib;%(AdditionalDependencies) - C:\OSGeo4W\lib;temp\wxWidgets-3.1.0\lib\vc_x64_dll;temp\CLAPACK-3.1.1-VisualStudio\LIB\x64;temp\boost_1_57_0\stage\lib;temp\json_spirit_v4.08\Debug;%(AdditionalLibraryDirectories) + opencl.lib;zlibstat.lib;gdal_i.lib;libcurl.lib;libboost_date_time-vc100-mt-gd-1_57.lib;libboost_thread-vc100-mt-gd-1_57.lib;BLAS.lib;clapack.lib;libf2c.lib;json_spirit_lib.lib;sqlite3_i.lib;GlU32.lib;OpenGL32.lib;wxmsw31ud.lib;wxmsw31ud_gl.lib;wxtiffd.lib;wxjpegd.lib;wxpngd.lib;wxzlibd.lib;wxregexud.lib;wxexpatd.lib;wsock32.lib;comctl32.lib;winmm.lib;rpcrt4.lib;%(AdditionalDependencies) + C:\Intel\OpenCL\sdk\lib\x64;dep\zlib\lib;C:\OSGeo4W\lib;temp\wxWidgets-3.1.0\lib\vc_x64_dll;temp\CLAPACK-3.1.1-VisualStudio\LIB\x64;temp\boost_1_57_0\stage\lib;temp\json_spirit_v4.08\Debug;%(AdditionalLibraryDirectories) %(IgnoreSpecificDefaultLibraries) @@ -223,8 +225,8 @@ temp\wxWidgets-3.1.0\include;%(AdditionalIncludeDirectories) - gdal_i.lib;libcurl.lib;libboost_thread-vc140-mt-gd-1_57.lib;BLAS.lib;clapack.lib;libf2c.lib;json_spirit_lib.lib;sqlite3_i.lib;GlU32.lib;OpenGL32.lib;wxmsw31ud.lib;wxmsw31ud_gl.lib;wxtiffd.lib;wxjpegd.lib;wxpngd.lib;wxzlibd.lib;wxregexud.lib;wxexpatd.lib;wsock32.lib;comctl32.lib;winmm.lib;rpcrt4.lib;%(AdditionalDependencies) - C:\OSGeo4W\lib;temp\wxWidgets-3.1.0\lib\vc_x64_dll;temp\CLAPACK-3.1.1-VisualStudio\LIB\x64;temp\boost_1_57_0\stage\lib;temp\json_spirit_v4.08\Debug;%(AdditionalLibraryDirectories) + opencl.lib;zlibstat.lib;gdal_i.lib;libcurl.lib;libboost_date_time-vc140-mt-gd-1_57.lib;libboost_thread-vc140-mt-gd-1_57.lib;BLAS.lib;clapack.lib;libf2c.lib;json_spirit_lib.lib;sqlite3_i.lib;GlU32.lib;OpenGL32.lib;wxmsw31ud.lib;wxmsw31ud_gl.lib;wxtiffd.lib;wxjpegd.lib;wxpngd.lib;wxzlibd.lib;wxregexud.lib;wxexpatd.lib;wsock32.lib;comctl32.lib;winmm.lib;rpcrt4.lib;%(AdditionalDependencies) + C:\Intel\OpenCL\sdk\lib\x64;dep\zlib\lib;C:\OSGeo4W\lib;temp\wxWidgets-3.1.0\lib\vc_x64_dll;temp\CLAPACK-3.1.1-VisualStudio\LIB\x64;temp\boost_1_57_0\stage\lib;temp\json_spirit_v4.08\Debug;%(AdditionalLibraryDirectories) %(IgnoreSpecificDefaultLibraries) @@ -238,7 +240,7 @@ - C:\OSGeo4W\include;temp\boost_1_57_0;temp\wxWidgets-3.1.0\include;temp\wxWidgets-3.1.0\lib\vc_dll\mswu;temp\json_spirit_v4.08;temp\eigen3;%(AdditionalIncludeDirectories) + C:\Intel\OpenCL\sdk\include;C:\OSGeo4W\include;temp\boost_1_57_0;temp\wxWidgets-3.1.0\include;temp\wxWidgets-3.1.0\lib\vc_dll\mswu;temp\json_spirit_v4.08;temp\eigen3;%(AdditionalIncludeDirectories) WIN32;_WINDOWS;__WXMSW__;__NO_VC_CRTDBG__;WXUSINGDLL;UNICODE;%(PreprocessorDefinitions) MultiThreadedDLL @@ -254,8 +256,8 @@ temp\wxWidgets-3.1.0\include;%(AdditionalIncludeDirectories) - gdal_i.lib;libcurl.lib;libboost_thread-vc100-mt-1_57.lib;BLAS.lib;clapack.lib;libf2c.lib;json_spirit_lib.lib;sqlite3_i.lib;GlU32.lib;OpenGL32.lib;wxmsw31u.lib;wxmsw31u_gl.lib;wxtiff.lib;wxjpeg.lib;wxpng.lib;wxzlib.lib;wxregexu.lib;wxexpat.lib;wsock32.lib;comctl32.lib;winmm.lib;rpcrt4.lib;%(AdditionalDependencies) - C:\OSGeo4W\lib;temp\wxWidgets-3.1.0\lib\vc_dll;temp\CLAPACK-3.1.1-VisualStudio\LIB\Win32;temp\boost_1_57_0\stage\lib;temp\json_spirit_v4.08\Release;%(AdditionalLibraryDirectories) + opencl.lib;zlibstat.lib;gdal_i.lib;libcurl.lib;libboost_date_time-vc100-mt-1_57.lib;libboost_thread-vc100-mt-1_57.lib;BLAS.lib;clapack.lib;libf2c.lib;json_spirit_lib.lib;sqlite3_i.lib;GlU32.lib;OpenGL32.lib;wxmsw31u.lib;wxmsw31u_gl.lib;wxtiff.lib;wxjpeg.lib;wxpng.lib;wxzlib.lib;wxregexu.lib;wxexpat.lib;wsock32.lib;comctl32.lib;winmm.lib;rpcrt4.lib;%(AdditionalDependencies) + C:\Intel\OpenCL\sdk\lib\x86;dep\zlib\lib;C:\OSGeo4W\lib;temp\wxWidgets-3.1.0\lib\vc_dll;temp\CLAPACK-3.1.1-VisualStudio\LIB\Win32;temp\boost_1_57_0\stage\lib;temp\json_spirit_v4.08\Release;%(AdditionalLibraryDirectories) true Windows true @@ -265,7 +267,7 @@ - C:\OSGeo4W\include;temp\boost_1_57_0;temp\wxWidgets-3.1.0\include;temp\wxWidgets-3.1.0\lib\vc_x64_dll\mswu;temp\json_spirit_v4.08;temp\eigen3;%(AdditionalIncludeDirectories) + C:\Intel\OpenCL\sdk\include;C:\OSGeo4W\include;temp\boost_1_57_0;temp\wxWidgets-3.1.0\include;temp\wxWidgets-3.1.0\lib\vc_x64_dll\mswu;temp\json_spirit_v4.08;temp\eigen3;dep\zlib\include;%(AdditionalIncludeDirectories) WIN32;_WINDOWS;__WXMSW__;__NO_VC_CRTDBG__;WXUSINGDLL;UNICODE;%(PreprocessorDefinitions) MultiThreadedDLL @@ -282,8 +284,8 @@ temp\wxWidgets-3.1.0\include;%(AdditionalIncludeDirectories) - libcurl.lib;gdal_i.lib;libboost_thread-vc100-mt-1_57.lib;BLAS.lib;clapack.lib;libf2c.lib;json_spirit_lib.lib;sqlite3_i.lib;GlU32.lib;OpenGL32.lib;wxmsw31u.lib;wxmsw31u_gl.lib;wxtiff.lib;wxjpeg.lib;wxpng.lib;wxzlib.lib;wxregexu.lib;wxexpat.lib;wsock32.lib;comctl32.lib;winmm.lib;rpcrt4.lib;%(AdditionalDependencies) - C:\OSGeo4W\lib;temp\wxWidgets-3.1.0\lib\vc_x64_dll;temp\CLAPACK-3.1.1-VisualStudio\LIB\x64;temp\boost_1_57_0\stage\lib;temp\json_spirit_v4.08\Release;%(AdditionalLibraryDirectories) + opencl.lib;zlibstat.lib;libcurl.lib;gdal_i.lib;libboost_date_time-vc100-mt-1_57.lib;libboost_thread-vc100-mt-1_57.lib;BLAS.lib;clapack.lib;libf2c.lib;json_spirit_lib.lib;sqlite3_i.lib;GlU32.lib;OpenGL32.lib;wxmsw31u.lib;wxmsw31u_gl.lib;wxtiff.lib;wxjpeg.lib;wxpng.lib;wxzlib.lib;wxregexu.lib;wxexpat.lib;wsock32.lib;comctl32.lib;winmm.lib;rpcrt4.lib;%(AdditionalDependencies) + C:\Intel\OpenCL\sdk\lib\x64;dep\zlib\lib;C:\OSGeo4W\lib;temp\wxWidgets-3.1.0\lib\vc_x64_dll;temp\CLAPACK-3.1.1-VisualStudio\LIB\x64;temp\boost_1_57_0\stage\lib;temp\json_spirit_v4.08\Release;%(AdditionalLibraryDirectories) true Windows true @@ -291,6 +293,9 @@ + + + @@ -305,22 +310,49 @@ + + + + + + - - + + + + + + + + + + + + + + + + + + + + + + + @@ -337,6 +369,11 @@ + + + + + @@ -348,11 +385,32 @@ + + + + + + + + + + + + + + + + + + + + + + - @@ -365,13 +423,27 @@ + + + + + + + + + + + + + + + + - - @@ -381,9 +453,10 @@ - + + @@ -392,20 +465,34 @@ + + + + + + + + + + + + + + @@ -425,6 +512,12 @@ + + + + + + @@ -441,18 +534,45 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - @@ -465,12 +585,6 @@ - - - - - - @@ -495,7 +609,6 @@ - @@ -520,12 +633,10 @@ - - @@ -566,7 +677,6 @@ - @@ -601,6 +711,7 @@ + @@ -617,18 +728,7 @@ - - 4996;%(DisableSpecificWarnings) - 4996;%(DisableSpecificWarnings) - 4996;%(DisableSpecificWarnings) - 4996;%(DisableSpecificWarnings) - 4996;%(DisableSpecificWarnings) - 4996;%(DisableSpecificWarnings) - - - - @@ -639,10 +739,6 @@ - - - - @@ -661,7 +757,6 @@ - @@ -686,7 +781,6 @@ - @@ -715,7 +809,6 @@ - diff --git a/BuildTools/windows/GeoDa.vcxproj.filters b/BuildTools/windows/GeoDa.vcxproj.filters index bda9bd21e..eb6d733be 100644 --- a/BuildTools/windows/GeoDa.vcxproj.filters +++ b/BuildTools/windows/GeoDa.vcxproj.filters @@ -32,6 +32,24 @@ {26d19d80-b064-41d9-80e5-37e967c05d8a} + + {6f1478f1-4816-4219-a7a3-da8b22086f01} + + + {90f57f50-2648-4589-9585-434636a6272f} + + + {b9cdb32d-74e3-4ba7-a5ea-a0580c0c694d} + + + {0c323cad-a390-44fd-aae6-2e08cb7938a1} + + + {4bb92a90-99f0-4d47-b33d-e1663d9bfab0} + + + {85fd04ff-4aa4-45d8-8492-8a7d69f0dc17} + @@ -52,6 +70,15 @@ rc + + Algorithms + + + Algorithms + + + Algorithms + @@ -60,21 +87,9 @@ - - ShapeOperations - - - ShapeOperations - - - ShapeOperations - ShapeOperations - - ShapeOperations - ShapeOperations @@ -93,21 +108,6 @@ ShapeOperations - - ShapeOperations - - - ShapeOperations - - - ShapeOperations - - - ShapeOperations - - - ShapeOperations - ShapeOperations @@ -177,9 +177,6 @@ DialogTools - - DialogTools - DialogTools @@ -252,9 +249,6 @@ DialogTools - - DialogTools - DialogTools @@ -365,18 +359,12 @@ - - DataViewer - DataViewer DataViewer - - DataViewer - DataViewer @@ -504,9 +492,6 @@ Explore - - DataViewer - ShapeOperations @@ -569,7 +554,6 @@ libgdiam - @@ -598,9 +582,6 @@ ShapeOperations - - ShapeOperations - Explore @@ -657,26 +638,217 @@ Algorithms + + DialogTools + + + Algorithms + + + DialogTools + + + Algorithms + + + Algorithms + + + DialogTools + + + DialogTools + + + DialogTools + + + DialogTools + + + DialogTools + + + DialogTools + + + Explore + + + DialogTools + + + Explore + + + Explore + + + Explore + + + Algorithms + + + Algorithms + + + Algorithms + + + Algorithms + + + DialogTools + + + DialogTools + + + Explore + + + Explore + + + io + + + io + + + io + + + io + + + + Algorithms + + + DialogTools + + + kNN + + + kNN + + + kNN + + + kNN + + + kNN + + + kNN + + + kNN + + + kNN + + + kNN + + + kNN + + + kNN + + + Algorithms + + + Algorithms + + + Algorithms + + + arizona\viz3 + + + arizona\viz3 + + + arizona\viz3 + + + arizona\viz3\plots + + + ogl + + + ogl + + + ogl + + + ogl + + + ogl + + + ogl + + + ogl + + + ogl + + + ogl + + + ogl + + + ogl + + + ogl + + + ogl + + + ogl + + + ogl + + + Explore + + + Explore + + + + Explore + + + DialogTools + rc - - ShapeOperations - - - ShapeOperations - - - ShapeOperations - ShapeOperations - - ShapeOperations - ShapeOperations @@ -695,18 +867,6 @@ ShapeOperations - - ShapeOperations - - - ShapeOperations - - - ShapeOperations - - - ShapeOperations - ShapeOperations @@ -758,9 +918,6 @@ DialogTools - - DialogTools - DialogTools @@ -833,9 +990,6 @@ DialogTools - - DialogTools - DialogTools @@ -936,18 +1090,12 @@ - - DataViewer - DataViewer DialogTools - - DataViewer - DataViewer @@ -1064,9 +1212,6 @@ Explore - - DataViewer - ShapeOperations @@ -1123,7 +1268,6 @@ libgdiam - @@ -1144,9 +1288,6 @@ ShapeOperations - - ShapeOperations - Explore @@ -1199,5 +1340,174 @@ Algorithms + + DialogTools + + + Algorithms + + + DialogTools + + + Algorithms + + + Algorithms + + + DialogTools + + + DialogTools + + + DialogTools + + + DialogTools + + + DialogTools + + + DialogTools + + + Explore + + + DialogTools + + + Explore + + + Explore + + + Algorithms + + + Algorithms + + + DialogTools + + + DialogTools + + + Explore + + + Explore + + + io + + + io + + + io + + + + Algorithms + + + DialogTools + + + kNN + + + kNN + + + kNN + + + kNN + + + kNN + + + kNN + + + kNN + + + Algorithms + + + Algorithms + + + Algorithms + + + arizona\viz3 + + + arizona\viz3 + + + arizona\viz3 + + + arizona\viz3\plots + + + ogl + + + ogl + + + ogl + + + ogl + + + ogl + + + ogl + + + ogl + + + ogl + + + ogl + + + ogl + + + ogl + + + ogl + + + Explore + + + Explore + + + Explore + + + DialogTools + \ No newline at end of file diff --git a/BuildTools/windows/build.bat b/BuildTools/windows/build.bat index 6cf92868a..59a774b3b 100644 --- a/BuildTools/windows/build.bat +++ b/BuildTools/windows/build.bat @@ -693,8 +693,8 @@ echo ##################################################### echo # build wxWidgets echo ##################################################### echo. -set LIB_NAME=wxWidgets-3.1.0 -set LIB_URL="https://s3.us-east-2.amazonaws.com/geodabuild/wxWidgets-3.1.0.7z" +set LIB_NAME=wxWidgets-3.1.1 +set LIB_URL="https://github.com/wxWidgets/wxWidgets/releases/download/v3.1.1/wxWidgets-3.1.1.7z" REM # We are only checking for a small subset of wxWidgets libraries set ALL_EXIST=true @@ -725,7 +725,7 @@ REM # that declares wxWidgets is high-DPI display aware. wxWidgets REM # isn't high-DPI display aware and we actually want Windows 8.1 REM # to apply pixel scaling so that the layout of windows isn't messed REM # up. OSX already handles Retina displays properly. -xcopy /E /Y %BUILD_DEP%\%LIB_NAME% %DOWNLOAD_HOME%\%LIB_NAME% +REM xcopy /E /Y %BUILD_DEP%\%LIB_NAME% %DOWNLOAD_HOME%\%LIB_NAME% cd %DOWNLOAD_HOME%\%LIB_NAME%\build\msw set WX_HOME=%DOWNLOAD_HOME%\%LIB_NAME% diff --git a/BuildTools/windows/dep/zlib/README.txt b/BuildTools/windows/dep/zlib/README.txt new file mode 100644 index 000000000..aa78f27d7 --- /dev/null +++ b/BuildTools/windows/dep/zlib/README.txt @@ -0,0 +1,2 @@ +version 1.2.3 +http://www.winimage.com/zLibDll/ \ No newline at end of file diff --git a/BuildTools/windows/dep/zlib/include/zconf.h b/BuildTools/windows/dep/zlib/include/zconf.h new file mode 100644 index 000000000..03a9431c8 --- /dev/null +++ b/BuildTools/windows/dep/zlib/include/zconf.h @@ -0,0 +1,332 @@ +/* zconf.h -- configuration of the zlib compression library + * Copyright (C) 1995-2005 Jean-loup Gailly. + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* @(#) $Id$ */ + +#ifndef ZCONF_H +#define ZCONF_H + +/* + * If you *really* need a unique prefix for all types and library functions, + * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it. + */ +#ifdef Z_PREFIX +# define deflateInit_ z_deflateInit_ +# define deflate z_deflate +# define deflateEnd z_deflateEnd +# define inflateInit_ z_inflateInit_ +# define inflate z_inflate +# define inflateEnd z_inflateEnd +# define deflateInit2_ z_deflateInit2_ +# define deflateSetDictionary z_deflateSetDictionary +# define deflateCopy z_deflateCopy +# define deflateReset z_deflateReset +# define deflateParams z_deflateParams +# define deflateBound z_deflateBound +# define deflatePrime z_deflatePrime +# define inflateInit2_ z_inflateInit2_ +# define inflateSetDictionary z_inflateSetDictionary +# define inflateSync z_inflateSync +# define inflateSyncPoint z_inflateSyncPoint +# define inflateCopy z_inflateCopy +# define inflateReset z_inflateReset +# define inflateBack z_inflateBack +# define inflateBackEnd z_inflateBackEnd +# define compress z_compress +# define compress2 z_compress2 +# define compressBound z_compressBound +# define uncompress z_uncompress +# define adler32 z_adler32 +# define crc32 z_crc32 +# define get_crc_table z_get_crc_table +# define zError z_zError + +# define alloc_func z_alloc_func +# define free_func z_free_func +# define in_func z_in_func +# define out_func z_out_func +# define Byte z_Byte +# define uInt z_uInt +# define uLong z_uLong +# define Bytef z_Bytef +# define charf z_charf +# define intf z_intf +# define uIntf z_uIntf +# define uLongf z_uLongf +# define voidpf z_voidpf +# define voidp z_voidp +#endif + +#if defined(__MSDOS__) && !defined(MSDOS) +# define MSDOS +#endif +#if (defined(OS_2) || defined(__OS2__)) && !defined(OS2) +# define OS2 +#endif +#if defined(_WINDOWS) && !defined(WINDOWS) +# define WINDOWS +#endif +#if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__) +# ifndef WIN32 +# define WIN32 +# endif +#endif +#if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32) +# if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__) +# ifndef SYS16BIT +# define SYS16BIT +# endif +# endif +#endif + +/* + * Compile with -DMAXSEG_64K if the alloc function cannot allocate more + * than 64k bytes at a time (needed on systems with 16-bit int). + */ +#ifdef SYS16BIT +# define MAXSEG_64K +#endif +#ifdef MSDOS +# define UNALIGNED_OK +#endif + +#ifdef __STDC_VERSION__ +# ifndef STDC +# define STDC +# endif +# if __STDC_VERSION__ >= 199901L +# ifndef STDC99 +# define STDC99 +# endif +# endif +#endif +#if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus)) +# define STDC +#endif +#if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__)) +# define STDC +#endif +#if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32)) +# define STDC +#endif +#if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__)) +# define STDC +#endif + +#if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */ +# define STDC +#endif + +#ifndef STDC +# ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */ +# define const /* note: need a more gentle solution here */ +# endif +#endif + +/* Some Mac compilers merge all .h files incorrectly: */ +#if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__) +# define NO_DUMMY_DECL +#endif + +/* Maximum value for memLevel in deflateInit2 */ +#ifndef MAX_MEM_LEVEL +# ifdef MAXSEG_64K +# define MAX_MEM_LEVEL 8 +# else +# define MAX_MEM_LEVEL 9 +# endif +#endif + +/* Maximum value for windowBits in deflateInit2 and inflateInit2. + * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files + * created by gzip. (Files created by minigzip can still be extracted by + * gzip.) + */ +#ifndef MAX_WBITS +# define MAX_WBITS 15 /* 32K LZ77 window */ +#endif + +/* The memory requirements for deflate are (in bytes): + (1 << (windowBits+2)) + (1 << (memLevel+9)) + that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values) + plus a few kilobytes for small objects. For example, if you want to reduce + the default memory requirements from 256K to 128K, compile with + make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7" + Of course this will generally degrade compression (there's no free lunch). + + The memory requirements for inflate are (in bytes) 1 << windowBits + that is, 32K for windowBits=15 (default value) plus a few kilobytes + for small objects. +*/ + + /* Type declarations */ + +#ifndef OF /* function prototypes */ +# ifdef STDC +# define OF(args) args +# else +# define OF(args) () +# endif +#endif + +/* The following definitions for FAR are needed only for MSDOS mixed + * model programming (small or medium model with some far allocations). + * This was tested only with MSC; for other MSDOS compilers you may have + * to define NO_MEMCPY in zutil.h. If you don't need the mixed model, + * just define FAR to be empty. + */ +#ifdef SYS16BIT +# if defined(M_I86SM) || defined(M_I86MM) + /* MSC small or medium model */ +# define SMALL_MEDIUM +# ifdef _MSC_VER +# define FAR _far +# else +# define FAR far +# endif +# endif +# if (defined(__SMALL__) || defined(__MEDIUM__)) + /* Turbo C small or medium model */ +# define SMALL_MEDIUM +# ifdef __BORLANDC__ +# define FAR _far +# else +# define FAR far +# endif +# endif +#endif + +#if defined(WINDOWS) || defined(WIN32) + /* If building or using zlib as a DLL, define ZLIB_DLL. + * This is not mandatory, but it offers a little performance increase. + */ +# ifdef ZLIB_DLL +# if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500)) +# ifdef ZLIB_INTERNAL +# define ZEXTERN extern __declspec(dllexport) +# else +# define ZEXTERN extern __declspec(dllimport) +# endif +# endif +# endif /* ZLIB_DLL */ + /* If building or using zlib with the WINAPI/WINAPIV calling convention, + * define ZLIB_WINAPI. + * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI. + */ +# ifdef ZLIB_WINAPI +# ifdef FAR +# undef FAR +# endif +# include + /* No need for _export, use ZLIB.DEF instead. */ + /* For complete Windows compatibility, use WINAPI, not __stdcall. */ +# define ZEXPORT WINAPI +# ifdef WIN32 +# define ZEXPORTVA WINAPIV +# else +# define ZEXPORTVA FAR CDECL +# endif +# endif +#endif + +#if defined (__BEOS__) +# ifdef ZLIB_DLL +# ifdef ZLIB_INTERNAL +# define ZEXPORT __declspec(dllexport) +# define ZEXPORTVA __declspec(dllexport) +# else +# define ZEXPORT __declspec(dllimport) +# define ZEXPORTVA __declspec(dllimport) +# endif +# endif +#endif + +#ifndef ZEXTERN +# define ZEXTERN extern +#endif +#ifndef ZEXPORT +# define ZEXPORT +#endif +#ifndef ZEXPORTVA +# define ZEXPORTVA +#endif + +#ifndef FAR +# define FAR +#endif + +#if !defined(__MACTYPES__) +typedef unsigned char Byte; /* 8 bits */ +#endif +typedef unsigned int uInt; /* 16 bits or more */ +typedef unsigned long uLong; /* 32 bits or more */ + +#ifdef SMALL_MEDIUM + /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */ +# define Bytef Byte FAR +#else + typedef Byte FAR Bytef; +#endif +typedef char FAR charf; +typedef int FAR intf; +typedef uInt FAR uIntf; +typedef uLong FAR uLongf; + +#ifdef STDC + typedef void const *voidpc; + typedef void FAR *voidpf; + typedef void *voidp; +#else + typedef Byte const *voidpc; + typedef Byte FAR *voidpf; + typedef Byte *voidp; +#endif + +#if 0 /* HAVE_UNISTD_H -- this line is updated by ./configure */ +# include /* for off_t */ +# include /* for SEEK_* and off_t */ +# ifdef VMS +# include /* for off_t */ +# endif +# define z_off_t off_t +#endif +#ifndef SEEK_SET +# define SEEK_SET 0 /* Seek from beginning of file. */ +# define SEEK_CUR 1 /* Seek from current position. */ +# define SEEK_END 2 /* Set file pointer to EOF plus "offset" */ +#endif +#ifndef z_off_t +# define z_off_t long +#endif + +#if defined(__OS400__) +# define NO_vsnprintf +#endif + +#if defined(__MVS__) +# define NO_vsnprintf +# ifdef FAR +# undef FAR +# endif +#endif + +/* MVS linker does not support external names larger than 8 bytes */ +#if defined(__MVS__) +# pragma map(deflateInit_,"DEIN") +# pragma map(deflateInit2_,"DEIN2") +# pragma map(deflateEnd,"DEEND") +# pragma map(deflateBound,"DEBND") +# pragma map(inflateInit_,"ININ") +# pragma map(inflateInit2_,"ININ2") +# pragma map(inflateEnd,"INEND") +# pragma map(inflateSync,"INSY") +# pragma map(inflateSetDictionary,"INSEDI") +# pragma map(compressBound,"CMBND") +# pragma map(inflate_table,"INTABL") +# pragma map(inflate_fast,"INFA") +# pragma map(inflate_copyright,"INCOPY") +#endif + +#endif /* ZCONF_H */ diff --git a/BuildTools/windows/dep/zlib/include/zlib.h b/BuildTools/windows/dep/zlib/include/zlib.h new file mode 100644 index 000000000..022817927 --- /dev/null +++ b/BuildTools/windows/dep/zlib/include/zlib.h @@ -0,0 +1,1357 @@ +/* zlib.h -- interface of the 'zlib' general purpose compression library + version 1.2.3, July 18th, 2005 + + Copyright (C) 1995-2005 Jean-loup Gailly and Mark Adler + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. + + Jean-loup Gailly Mark Adler + jloup@gzip.org madler@alumni.caltech.edu + + + The data format used by the zlib library is described by RFCs (Request for + Comments) 1950 to 1952 in the files http://www.ietf.org/rfc/rfc1950.txt + (zlib format), rfc1951.txt (deflate format) and rfc1952.txt (gzip format). +*/ + +#ifndef ZLIB_H +#define ZLIB_H + +#include "zconf.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define ZLIB_VERSION "1.2.3" +#define ZLIB_VERNUM 0x1230 + +/* + The 'zlib' compression library provides in-memory compression and + decompression functions, including integrity checks of the uncompressed + data. This version of the library supports only one compression method + (deflation) but other algorithms will be added later and will have the same + stream interface. + + Compression can be done in a single step if the buffers are large + enough (for example if an input file is mmap'ed), or can be done by + repeated calls of the compression function. In the latter case, the + application must provide more input and/or consume the output + (providing more output space) before each call. + + The compressed data format used by default by the in-memory functions is + the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped + around a deflate stream, which is itself documented in RFC 1951. + + The library also supports reading and writing files in gzip (.gz) format + with an interface similar to that of stdio using the functions that start + with "gz". The gzip format is different from the zlib format. gzip is a + gzip wrapper, documented in RFC 1952, wrapped around a deflate stream. + + This library can optionally read and write gzip streams in memory as well. + + The zlib format was designed to be compact and fast for use in memory + and on communications channels. The gzip format was designed for single- + file compression on file systems, has a larger header than zlib to maintain + directory information, and uses a different, slower check method than zlib. + + The library does not install any signal handler. The decoder checks + the consistency of the compressed data, so the library should never + crash even in case of corrupted input. +*/ + +typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size)); +typedef void (*free_func) OF((voidpf opaque, voidpf address)); + +struct internal_state; + +typedef struct z_stream_s { + Bytef *next_in; /* next input byte */ + uInt avail_in; /* number of bytes available at next_in */ + uLong total_in; /* total nb of input bytes read so far */ + + Bytef *next_out; /* next output byte should be put there */ + uInt avail_out; /* remaining free space at next_out */ + uLong total_out; /* total nb of bytes output so far */ + + char *msg; /* last error message, NULL if no error */ + struct internal_state FAR *state; /* not visible by applications */ + + alloc_func zalloc; /* used to allocate the internal state */ + free_func zfree; /* used to free the internal state */ + voidpf opaque; /* private data object passed to zalloc and zfree */ + + int data_type; /* best guess about the data type: binary or text */ + uLong adler; /* adler32 value of the uncompressed data */ + uLong reserved; /* reserved for future use */ +} z_stream; + +typedef z_stream FAR *z_streamp; + +/* + gzip header information passed to and from zlib routines. See RFC 1952 + for more details on the meanings of these fields. +*/ +typedef struct gz_header_s { + int text; /* true if compressed data believed to be text */ + uLong time; /* modification time */ + int xflags; /* extra flags (not used when writing a gzip file) */ + int os; /* operating system */ + Bytef *extra; /* pointer to extra field or Z_NULL if none */ + uInt extra_len; /* extra field length (valid if extra != Z_NULL) */ + uInt extra_max; /* space at extra (only when reading header) */ + Bytef *name; /* pointer to zero-terminated file name or Z_NULL */ + uInt name_max; /* space at name (only when reading header) */ + Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */ + uInt comm_max; /* space at comment (only when reading header) */ + int hcrc; /* true if there was or will be a header crc */ + int done; /* true when done reading gzip header (not used + when writing a gzip file) */ +} gz_header; + +typedef gz_header FAR *gz_headerp; + +/* + The application must update next_in and avail_in when avail_in has + dropped to zero. It must update next_out and avail_out when avail_out + has dropped to zero. The application must initialize zalloc, zfree and + opaque before calling the init function. All other fields are set by the + compression library and must not be updated by the application. + + The opaque value provided by the application will be passed as the first + parameter for calls of zalloc and zfree. This can be useful for custom + memory management. The compression library attaches no meaning to the + opaque value. + + zalloc must return Z_NULL if there is not enough memory for the object. + If zlib is used in a multi-threaded application, zalloc and zfree must be + thread safe. + + On 16-bit systems, the functions zalloc and zfree must be able to allocate + exactly 65536 bytes, but will not be required to allocate more than this + if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS, + pointers returned by zalloc for objects of exactly 65536 bytes *must* + have their offset normalized to zero. The default allocation function + provided by this library ensures this (see zutil.c). To reduce memory + requirements and avoid any allocation of 64K objects, at the expense of + compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h). + + The fields total_in and total_out can be used for statistics or + progress reports. After compression, total_in holds the total size of + the uncompressed data and may be saved for use in the decompressor + (particularly if the decompressor wants to decompress everything in + a single step). +*/ + + /* constants */ + +#define Z_NO_FLUSH 0 +#define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */ +#define Z_SYNC_FLUSH 2 +#define Z_FULL_FLUSH 3 +#define Z_FINISH 4 +#define Z_BLOCK 5 +/* Allowed flush values; see deflate() and inflate() below for details */ + +#define Z_OK 0 +#define Z_STREAM_END 1 +#define Z_NEED_DICT 2 +#define Z_ERRNO (-1) +#define Z_STREAM_ERROR (-2) +#define Z_DATA_ERROR (-3) +#define Z_MEM_ERROR (-4) +#define Z_BUF_ERROR (-5) +#define Z_VERSION_ERROR (-6) +/* Return codes for the compression/decompression functions. Negative + * values are errors, positive values are used for special but normal events. + */ + +#define Z_NO_COMPRESSION 0 +#define Z_BEST_SPEED 1 +#define Z_BEST_COMPRESSION 9 +#define Z_DEFAULT_COMPRESSION (-1) +/* compression levels */ + +#define Z_FILTERED 1 +#define Z_HUFFMAN_ONLY 2 +#define Z_RLE 3 +#define Z_FIXED 4 +#define Z_DEFAULT_STRATEGY 0 +/* compression strategy; see deflateInit2() below for details */ + +#define Z_BINARY 0 +#define Z_TEXT 1 +#define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */ +#define Z_UNKNOWN 2 +/* Possible values of the data_type field (though see inflate()) */ + +#define Z_DEFLATED 8 +/* The deflate compression method (the only one supported in this version) */ + +#define Z_NULL 0 /* for initializing zalloc, zfree, opaque */ + +#define zlib_version zlibVersion() +/* for compatibility with versions < 1.0.2 */ + + /* basic functions */ + +ZEXTERN const char * ZEXPORT zlibVersion OF((void)); +/* The application can compare zlibVersion and ZLIB_VERSION for consistency. + If the first character differs, the library code actually used is + not compatible with the zlib.h header file used by the application. + This check is automatically made by deflateInit and inflateInit. + */ + +/* +ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level)); + + Initializes the internal stream state for compression. The fields + zalloc, zfree and opaque must be initialized before by the caller. + If zalloc and zfree are set to Z_NULL, deflateInit updates them to + use default allocation functions. + + The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9: + 1 gives best speed, 9 gives best compression, 0 gives no compression at + all (the input data is simply copied a block at a time). + Z_DEFAULT_COMPRESSION requests a default compromise between speed and + compression (currently equivalent to level 6). + + deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_STREAM_ERROR if level is not a valid compression level, + Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible + with the version assumed by the caller (ZLIB_VERSION). + msg is set to null if there is no error message. deflateInit does not + perform any compression: this will be done by deflate(). +*/ + + +ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush)); +/* + deflate compresses as much data as possible, and stops when the input + buffer becomes empty or the output buffer becomes full. It may introduce some + output latency (reading input without producing any output) except when + forced to flush. + + The detailed semantics are as follows. deflate performs one or both of the + following actions: + + - Compress more input starting at next_in and update next_in and avail_in + accordingly. If not all input can be processed (because there is not + enough room in the output buffer), next_in and avail_in are updated and + processing will resume at this point for the next call of deflate(). + + - Provide more output starting at next_out and update next_out and avail_out + accordingly. This action is forced if the parameter flush is non zero. + Forcing flush frequently degrades the compression ratio, so this parameter + should be set only when necessary (in interactive applications). + Some output may be provided even if flush is not set. + + Before the call of deflate(), the application should ensure that at least + one of the actions is possible, by providing more input and/or consuming + more output, and updating avail_in or avail_out accordingly; avail_out + should never be zero before the call. The application can consume the + compressed output when it wants, for example when the output buffer is full + (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK + and with zero avail_out, it must be called again after making room in the + output buffer because there might be more output pending. + + Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to + decide how much data to accumualte before producing output, in order to + maximize compression. + + If the parameter flush is set to Z_SYNC_FLUSH, all pending output is + flushed to the output buffer and the output is aligned on a byte boundary, so + that the decompressor can get all input data available so far. (In particular + avail_in is zero after the call if enough output space has been provided + before the call.) Flushing may degrade compression for some compression + algorithms and so it should be used only when necessary. + + If flush is set to Z_FULL_FLUSH, all output is flushed as with + Z_SYNC_FLUSH, and the compression state is reset so that decompression can + restart from this point if previous compressed data has been damaged or if + random access is desired. Using Z_FULL_FLUSH too often can seriously degrade + compression. + + If deflate returns with avail_out == 0, this function must be called again + with the same value of the flush parameter and more output space (updated + avail_out), until the flush is complete (deflate returns with non-zero + avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that + avail_out is greater than six to avoid repeated flush markers due to + avail_out == 0 on return. + + If the parameter flush is set to Z_FINISH, pending input is processed, + pending output is flushed and deflate returns with Z_STREAM_END if there + was enough output space; if deflate returns with Z_OK, this function must be + called again with Z_FINISH and more output space (updated avail_out) but no + more input data, until it returns with Z_STREAM_END or an error. After + deflate has returned Z_STREAM_END, the only possible operations on the + stream are deflateReset or deflateEnd. + + Z_FINISH can be used immediately after deflateInit if all the compression + is to be done in a single step. In this case, avail_out must be at least + the value returned by deflateBound (see below). If deflate does not return + Z_STREAM_END, then it must be called again as described above. + + deflate() sets strm->adler to the adler32 checksum of all input read + so far (that is, total_in bytes). + + deflate() may update strm->data_type if it can make a good guess about + the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered + binary. This field is only for information purposes and does not affect + the compression algorithm in any manner. + + deflate() returns Z_OK if some progress has been made (more input + processed or more output produced), Z_STREAM_END if all input has been + consumed and all output has been produced (only when flush is set to + Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example + if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible + (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not + fatal, and deflate() can be called again with more input and more output + space to continue compressing. +*/ + + +ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm)); +/* + All dynamically allocated data structures for this stream are freed. + This function discards any unprocessed input and does not flush any + pending output. + + deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the + stream state was inconsistent, Z_DATA_ERROR if the stream was freed + prematurely (some input or output was discarded). In the error case, + msg may be set but then points to a static string (which must not be + deallocated). +*/ + + +/* +ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm)); + + Initializes the internal stream state for decompression. The fields + next_in, avail_in, zalloc, zfree and opaque must be initialized before by + the caller. If next_in is not Z_NULL and avail_in is large enough (the exact + value depends on the compression method), inflateInit determines the + compression method from the zlib header and allocates all data structures + accordingly; otherwise the allocation will be deferred to the first call of + inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to + use default allocation functions. + + inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_VERSION_ERROR if the zlib library version is incompatible with the + version assumed by the caller. msg is set to null if there is no error + message. inflateInit does not perform any decompression apart from reading + the zlib header if present: this will be done by inflate(). (So next_in and + avail_in may be modified, but next_out and avail_out are unchanged.) +*/ + + +ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush)); +/* + inflate decompresses as much data as possible, and stops when the input + buffer becomes empty or the output buffer becomes full. It may introduce + some output latency (reading input without producing any output) except when + forced to flush. + + The detailed semantics are as follows. inflate performs one or both of the + following actions: + + - Decompress more input starting at next_in and update next_in and avail_in + accordingly. If not all input can be processed (because there is not + enough room in the output buffer), next_in is updated and processing + will resume at this point for the next call of inflate(). + + - Provide more output starting at next_out and update next_out and avail_out + accordingly. inflate() provides as much output as possible, until there + is no more input data or no more space in the output buffer (see below + about the flush parameter). + + Before the call of inflate(), the application should ensure that at least + one of the actions is possible, by providing more input and/or consuming + more output, and updating the next_* and avail_* values accordingly. + The application can consume the uncompressed output when it wants, for + example when the output buffer is full (avail_out == 0), or after each + call of inflate(). If inflate returns Z_OK and with zero avail_out, it + must be called again after making room in the output buffer because there + might be more output pending. + + The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH, + Z_FINISH, or Z_BLOCK. Z_SYNC_FLUSH requests that inflate() flush as much + output as possible to the output buffer. Z_BLOCK requests that inflate() stop + if and when it gets to the next deflate block boundary. When decoding the + zlib or gzip format, this will cause inflate() to return immediately after + the header and before the first block. When doing a raw inflate, inflate() + will go ahead and process the first block, and will return when it gets to + the end of that block, or when it runs out of data. + + The Z_BLOCK option assists in appending to or combining deflate streams. + Also to assist in this, on return inflate() will set strm->data_type to the + number of unused bits in the last byte taken from strm->next_in, plus 64 + if inflate() is currently decoding the last block in the deflate stream, + plus 128 if inflate() returned immediately after decoding an end-of-block + code or decoding the complete header up to just before the first byte of the + deflate stream. The end-of-block will not be indicated until all of the + uncompressed data from that block has been written to strm->next_out. The + number of unused bits may in general be greater than seven, except when + bit 7 of data_type is set, in which case the number of unused bits will be + less than eight. + + inflate() should normally be called until it returns Z_STREAM_END or an + error. However if all decompression is to be performed in a single step + (a single call of inflate), the parameter flush should be set to + Z_FINISH. In this case all pending input is processed and all pending + output is flushed; avail_out must be large enough to hold all the + uncompressed data. (The size of the uncompressed data may have been saved + by the compressor for this purpose.) The next operation on this stream must + be inflateEnd to deallocate the decompression state. The use of Z_FINISH + is never required, but can be used to inform inflate that a faster approach + may be used for the single inflate() call. + + In this implementation, inflate() always flushes as much output as + possible to the output buffer, and always uses the faster approach on the + first call. So the only effect of the flush parameter in this implementation + is on the return value of inflate(), as noted below, or when it returns early + because Z_BLOCK is used. + + If a preset dictionary is needed after this call (see inflateSetDictionary + below), inflate sets strm->adler to the adler32 checksum of the dictionary + chosen by the compressor and returns Z_NEED_DICT; otherwise it sets + strm->adler to the adler32 checksum of all output produced so far (that is, + total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described + below. At the end of the stream, inflate() checks that its computed adler32 + checksum is equal to that saved by the compressor and returns Z_STREAM_END + only if the checksum is correct. + + inflate() will decompress and check either zlib-wrapped or gzip-wrapped + deflate data. The header type is detected automatically. Any information + contained in the gzip header is not retained, so applications that need that + information should instead use raw inflate, see inflateInit2() below, or + inflateBack() and perform their own processing of the gzip header and + trailer. + + inflate() returns Z_OK if some progress has been made (more input processed + or more output produced), Z_STREAM_END if the end of the compressed data has + been reached and all uncompressed output has been produced, Z_NEED_DICT if a + preset dictionary is needed at this point, Z_DATA_ERROR if the input data was + corrupted (input stream not conforming to the zlib format or incorrect check + value), Z_STREAM_ERROR if the stream structure was inconsistent (for example + if next_in or next_out was NULL), Z_MEM_ERROR if there was not enough memory, + Z_BUF_ERROR if no progress is possible or if there was not enough room in the + output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and + inflate() can be called again with more input and more output space to + continue decompressing. If Z_DATA_ERROR is returned, the application may then + call inflateSync() to look for a good compression block if a partial recovery + of the data is desired. +*/ + + +ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm)); +/* + All dynamically allocated data structures for this stream are freed. + This function discards any unprocessed input and does not flush any + pending output. + + inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state + was inconsistent. In the error case, msg may be set but then points to a + static string (which must not be deallocated). +*/ + + /* Advanced functions */ + +/* + The following functions are needed only in some special applications. +*/ + +/* +ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm, + int level, + int method, + int windowBits, + int memLevel, + int strategy)); + + This is another version of deflateInit with more compression options. The + fields next_in, zalloc, zfree and opaque must be initialized before by + the caller. + + The method parameter is the compression method. It must be Z_DEFLATED in + this version of the library. + + The windowBits parameter is the base two logarithm of the window size + (the size of the history buffer). It should be in the range 8..15 for this + version of the library. Larger values of this parameter result in better + compression at the expense of memory usage. The default value is 15 if + deflateInit is used instead. + + windowBits can also be -8..-15 for raw deflate. In this case, -windowBits + determines the window size. deflate() will then generate raw deflate data + with no zlib header or trailer, and will not compute an adler32 check value. + + windowBits can also be greater than 15 for optional gzip encoding. Add + 16 to windowBits to write a simple gzip header and trailer around the + compressed data instead of a zlib wrapper. The gzip header will have no + file name, no extra data, no comment, no modification time (set to zero), + no header crc, and the operating system will be set to 255 (unknown). If a + gzip stream is being written, strm->adler is a crc32 instead of an adler32. + + The memLevel parameter specifies how much memory should be allocated + for the internal compression state. memLevel=1 uses minimum memory but + is slow and reduces compression ratio; memLevel=9 uses maximum memory + for optimal speed. The default value is 8. See zconf.h for total memory + usage as a function of windowBits and memLevel. + + The strategy parameter is used to tune the compression algorithm. Use the + value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a + filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no + string match), or Z_RLE to limit match distances to one (run-length + encoding). Filtered data consists mostly of small values with a somewhat + random distribution. In this case, the compression algorithm is tuned to + compress them better. The effect of Z_FILTERED is to force more Huffman + coding and less string matching; it is somewhat intermediate between + Z_DEFAULT and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as + Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy + parameter only affects the compression ratio but not the correctness of the + compressed output even if it is not set appropriately. Z_FIXED prevents the + use of dynamic Huffman codes, allowing for a simpler decoder for special + applications. + + deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid + method). msg is set to null if there is no error message. deflateInit2 does + not perform any compression: this will be done by deflate(). +*/ + +ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm, + const Bytef *dictionary, + uInt dictLength)); +/* + Initializes the compression dictionary from the given byte sequence + without producing any compressed output. This function must be called + immediately after deflateInit, deflateInit2 or deflateReset, before any + call of deflate. The compressor and decompressor must use exactly the same + dictionary (see inflateSetDictionary). + + The dictionary should consist of strings (byte sequences) that are likely + to be encountered later in the data to be compressed, with the most commonly + used strings preferably put towards the end of the dictionary. Using a + dictionary is most useful when the data to be compressed is short and can be + predicted with good accuracy; the data can then be compressed better than + with the default empty dictionary. + + Depending on the size of the compression data structures selected by + deflateInit or deflateInit2, a part of the dictionary may in effect be + discarded, for example if the dictionary is larger than the window size in + deflate or deflate2. Thus the strings most likely to be useful should be + put at the end of the dictionary, not at the front. In addition, the + current implementation of deflate will use at most the window size minus + 262 bytes of the provided dictionary. + + Upon return of this function, strm->adler is set to the adler32 value + of the dictionary; the decompressor may later use this value to determine + which dictionary has been used by the compressor. (The adler32 value + applies to the whole dictionary even if only a subset of the dictionary is + actually used by the compressor.) If a raw deflate was requested, then the + adler32 value is not computed and strm->adler is not set. + + deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a + parameter is invalid (such as NULL dictionary) or the stream state is + inconsistent (for example if deflate has already been called for this stream + or if the compression method is bsort). deflateSetDictionary does not + perform any compression: this will be done by deflate(). +*/ + +ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest, + z_streamp source)); +/* + Sets the destination stream as a complete copy of the source stream. + + This function can be useful when several compression strategies will be + tried, for example when there are several ways of pre-processing the input + data with a filter. The streams that will be discarded should then be freed + by calling deflateEnd. Note that deflateCopy duplicates the internal + compression state which can be quite large, so this strategy is slow and + can consume lots of memory. + + deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_STREAM_ERROR if the source stream state was inconsistent + (such as zalloc being NULL). msg is left unchanged in both source and + destination. +*/ + +ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm)); +/* + This function is equivalent to deflateEnd followed by deflateInit, + but does not free and reallocate all the internal compression state. + The stream will keep the same compression level and any other attributes + that may have been set by deflateInit2. + + deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent (such as zalloc or state being NULL). +*/ + +ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm, + int level, + int strategy)); +/* + Dynamically update the compression level and compression strategy. The + interpretation of level and strategy is as in deflateInit2. This can be + used to switch between compression and straight copy of the input data, or + to switch to a different kind of input data requiring a different + strategy. If the compression level is changed, the input available so far + is compressed with the old level (and may be flushed); the new level will + take effect only at the next call of deflate(). + + Before the call of deflateParams, the stream state must be set as for + a call of deflate(), since the currently available input may have to + be compressed and flushed. In particular, strm->avail_out must be non-zero. + + deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source + stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR + if strm->avail_out was zero. +*/ + +ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm, + int good_length, + int max_lazy, + int nice_length, + int max_chain)); +/* + Fine tune deflate's internal compression parameters. This should only be + used by someone who understands the algorithm used by zlib's deflate for + searching for the best matching string, and even then only by the most + fanatic optimizer trying to squeeze out the last compressed bit for their + specific input data. Read the deflate.c source code for the meaning of the + max_lazy, good_length, nice_length, and max_chain parameters. + + deflateTune() can be called after deflateInit() or deflateInit2(), and + returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream. + */ + +ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm, + uLong sourceLen)); +/* + deflateBound() returns an upper bound on the compressed size after + deflation of sourceLen bytes. It must be called after deflateInit() + or deflateInit2(). This would be used to allocate an output buffer + for deflation in a single pass, and so would be called before deflate(). +*/ + +ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm, + int bits, + int value)); +/* + deflatePrime() inserts bits in the deflate output stream. The intent + is that this function is used to start off the deflate output with the + bits leftover from a previous deflate stream when appending to it. As such, + this function can only be used for raw deflate, and must be used before the + first deflate() call after a deflateInit2() or deflateReset(). bits must be + less than or equal to 16, and that many of the least significant bits of + value will be inserted in the output. + + deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. +*/ + +ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm, + gz_headerp head)); +/* + deflateSetHeader() provides gzip header information for when a gzip + stream is requested by deflateInit2(). deflateSetHeader() may be called + after deflateInit2() or deflateReset() and before the first call of + deflate(). The text, time, os, extra field, name, and comment information + in the provided gz_header structure are written to the gzip header (xflag is + ignored -- the extra flags are set according to the compression level). The + caller must assure that, if not Z_NULL, name and comment are terminated with + a zero byte, and that if extra is not Z_NULL, that extra_len bytes are + available there. If hcrc is true, a gzip header crc is included. Note that + the current versions of the command-line version of gzip (up through version + 1.3.x) do not support header crc's, and will report that it is a "multi-part + gzip file" and give up. + + If deflateSetHeader is not used, the default gzip header has text false, + the time set to zero, and os set to 255, with no extra, name, or comment + fields. The gzip header is returned to the default state by deflateReset(). + + deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. +*/ + +/* +ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm, + int windowBits)); + + This is another version of inflateInit with an extra parameter. The + fields next_in, avail_in, zalloc, zfree and opaque must be initialized + before by the caller. + + The windowBits parameter is the base two logarithm of the maximum window + size (the size of the history buffer). It should be in the range 8..15 for + this version of the library. The default value is 15 if inflateInit is used + instead. windowBits must be greater than or equal to the windowBits value + provided to deflateInit2() while compressing, or it must be equal to 15 if + deflateInit2() was not used. If a compressed stream with a larger window + size is given as input, inflate() will return with the error code + Z_DATA_ERROR instead of trying to allocate a larger window. + + windowBits can also be -8..-15 for raw inflate. In this case, -windowBits + determines the window size. inflate() will then process raw deflate data, + not looking for a zlib or gzip header, not generating a check value, and not + looking for any check values for comparison at the end of the stream. This + is for use with other formats that use the deflate compressed data format + such as zip. Those formats provide their own check values. If a custom + format is developed using the raw deflate format for compressed data, it is + recommended that a check value such as an adler32 or a crc32 be applied to + the uncompressed data as is done in the zlib, gzip, and zip formats. For + most applications, the zlib format should be used as is. Note that comments + above on the use in deflateInit2() applies to the magnitude of windowBits. + + windowBits can also be greater than 15 for optional gzip decoding. Add + 32 to windowBits to enable zlib and gzip decoding with automatic header + detection, or add 16 to decode only the gzip format (the zlib format will + return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is + a crc32 instead of an adler32. + + inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_STREAM_ERROR if a parameter is invalid (such as a null strm). msg + is set to null if there is no error message. inflateInit2 does not perform + any decompression apart from reading the zlib header if present: this will + be done by inflate(). (So next_in and avail_in may be modified, but next_out + and avail_out are unchanged.) +*/ + +ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm, + const Bytef *dictionary, + uInt dictLength)); +/* + Initializes the decompression dictionary from the given uncompressed byte + sequence. This function must be called immediately after a call of inflate, + if that call returned Z_NEED_DICT. The dictionary chosen by the compressor + can be determined from the adler32 value returned by that call of inflate. + The compressor and decompressor must use exactly the same dictionary (see + deflateSetDictionary). For raw inflate, this function can be called + immediately after inflateInit2() or inflateReset() and before any call of + inflate() to set the dictionary. The application must insure that the + dictionary that was used for compression is provided. + + inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a + parameter is invalid (such as NULL dictionary) or the stream state is + inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the + expected one (incorrect adler32 value). inflateSetDictionary does not + perform any decompression: this will be done by subsequent calls of + inflate(). +*/ + +ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm)); +/* + Skips invalid compressed data until a full flush point (see above the + description of deflate with Z_FULL_FLUSH) can be found, or until all + available input is skipped. No output is provided. + + inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR + if no more input was provided, Z_DATA_ERROR if no flush point has been found, + or Z_STREAM_ERROR if the stream structure was inconsistent. In the success + case, the application may save the current current value of total_in which + indicates where valid compressed data was found. In the error case, the + application may repeatedly call inflateSync, providing more input each time, + until success or end of the input data. +*/ + +ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest, + z_streamp source)); +/* + Sets the destination stream as a complete copy of the source stream. + + This function can be useful when randomly accessing a large stream. The + first pass through the stream can periodically record the inflate state, + allowing restarting inflate at those points when randomly accessing the + stream. + + inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_STREAM_ERROR if the source stream state was inconsistent + (such as zalloc being NULL). msg is left unchanged in both source and + destination. +*/ + +ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm)); +/* + This function is equivalent to inflateEnd followed by inflateInit, + but does not free and reallocate all the internal decompression state. + The stream will keep attributes that may have been set by inflateInit2. + + inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent (such as zalloc or state being NULL). +*/ + +ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm, + int bits, + int value)); +/* + This function inserts bits in the inflate input stream. The intent is + that this function is used to start inflating at a bit position in the + middle of a byte. The provided bits will be used before any bytes are used + from next_in. This function should only be used with raw inflate, and + should be used before the first inflate() call after inflateInit2() or + inflateReset(). bits must be less than or equal to 16, and that many of the + least significant bits of value will be inserted in the input. + + inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. +*/ + +ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm, + gz_headerp head)); +/* + inflateGetHeader() requests that gzip header information be stored in the + provided gz_header structure. inflateGetHeader() may be called after + inflateInit2() or inflateReset(), and before the first call of inflate(). + As inflate() processes the gzip stream, head->done is zero until the header + is completed, at which time head->done is set to one. If a zlib stream is + being decoded, then head->done is set to -1 to indicate that there will be + no gzip header information forthcoming. Note that Z_BLOCK can be used to + force inflate() to return immediately after header processing is complete + and before any actual data is decompressed. + + The text, time, xflags, and os fields are filled in with the gzip header + contents. hcrc is set to true if there is a header CRC. (The header CRC + was valid if done is set to one.) If extra is not Z_NULL, then extra_max + contains the maximum number of bytes to write to extra. Once done is true, + extra_len contains the actual extra field length, and extra contains the + extra field, or that field truncated if extra_max is less than extra_len. + If name is not Z_NULL, then up to name_max characters are written there, + terminated with a zero unless the length is greater than name_max. If + comment is not Z_NULL, then up to comm_max characters are written there, + terminated with a zero unless the length is greater than comm_max. When + any of extra, name, or comment are not Z_NULL and the respective field is + not present in the header, then that field is set to Z_NULL to signal its + absence. This allows the use of deflateSetHeader() with the returned + structure to duplicate the header. However if those fields are set to + allocated memory, then the application will need to save those pointers + elsewhere so that they can be eventually freed. + + If inflateGetHeader is not used, then the header information is simply + discarded. The header is always checked for validity, including the header + CRC if present. inflateReset() will reset the process to discard the header + information. The application would need to call inflateGetHeader() again to + retrieve the header from the next gzip stream. + + inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. +*/ + +/* +ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits, + unsigned char FAR *window)); + + Initialize the internal stream state for decompression using inflateBack() + calls. The fields zalloc, zfree and opaque in strm must be initialized + before the call. If zalloc and zfree are Z_NULL, then the default library- + derived memory allocation routines are used. windowBits is the base two + logarithm of the window size, in the range 8..15. window is a caller + supplied buffer of that size. Except for special applications where it is + assured that deflate was used with small window sizes, windowBits must be 15 + and a 32K byte window must be supplied to be able to decompress general + deflate streams. + + See inflateBack() for the usage of these routines. + + inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of + the paramaters are invalid, Z_MEM_ERROR if the internal state could not + be allocated, or Z_VERSION_ERROR if the version of the library does not + match the version of the header file. +*/ + +typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *)); +typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned)); + +ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm, + in_func in, void FAR *in_desc, + out_func out, void FAR *out_desc)); +/* + inflateBack() does a raw inflate with a single call using a call-back + interface for input and output. This is more efficient than inflate() for + file i/o applications in that it avoids copying between the output and the + sliding window by simply making the window itself the output buffer. This + function trusts the application to not change the output buffer passed by + the output function, at least until inflateBack() returns. + + inflateBackInit() must be called first to allocate the internal state + and to initialize the state with the user-provided window buffer. + inflateBack() may then be used multiple times to inflate a complete, raw + deflate stream with each call. inflateBackEnd() is then called to free + the allocated state. + + A raw deflate stream is one with no zlib or gzip header or trailer. + This routine would normally be used in a utility that reads zip or gzip + files and writes out uncompressed files. The utility would decode the + header and process the trailer on its own, hence this routine expects + only the raw deflate stream to decompress. This is different from the + normal behavior of inflate(), which expects either a zlib or gzip header and + trailer around the deflate stream. + + inflateBack() uses two subroutines supplied by the caller that are then + called by inflateBack() for input and output. inflateBack() calls those + routines until it reads a complete deflate stream and writes out all of the + uncompressed data, or until it encounters an error. The function's + parameters and return types are defined above in the in_func and out_func + typedefs. inflateBack() will call in(in_desc, &buf) which should return the + number of bytes of provided input, and a pointer to that input in buf. If + there is no input available, in() must return zero--buf is ignored in that + case--and inflateBack() will return a buffer error. inflateBack() will call + out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out() + should return zero on success, or non-zero on failure. If out() returns + non-zero, inflateBack() will return with an error. Neither in() nor out() + are permitted to change the contents of the window provided to + inflateBackInit(), which is also the buffer that out() uses to write from. + The length written by out() will be at most the window size. Any non-zero + amount of input may be provided by in(). + + For convenience, inflateBack() can be provided input on the first call by + setting strm->next_in and strm->avail_in. If that input is exhausted, then + in() will be called. Therefore strm->next_in must be initialized before + calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called + immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in + must also be initialized, and then if strm->avail_in is not zero, input will + initially be taken from strm->next_in[0 .. strm->avail_in - 1]. + + The in_desc and out_desc parameters of inflateBack() is passed as the + first parameter of in() and out() respectively when they are called. These + descriptors can be optionally used to pass any information that the caller- + supplied in() and out() functions need to do their job. + + On return, inflateBack() will set strm->next_in and strm->avail_in to + pass back any unused input that was provided by the last in() call. The + return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR + if in() or out() returned an error, Z_DATA_ERROR if there was a format + error in the deflate stream (in which case strm->msg is set to indicate the + nature of the error), or Z_STREAM_ERROR if the stream was not properly + initialized. In the case of Z_BUF_ERROR, an input or output error can be + distinguished using strm->next_in which will be Z_NULL only if in() returned + an error. If strm->next is not Z_NULL, then the Z_BUF_ERROR was due to + out() returning non-zero. (in() will always be called before out(), so + strm->next_in is assured to be defined if out() returns non-zero.) Note + that inflateBack() cannot return Z_OK. +*/ + +ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm)); +/* + All memory allocated by inflateBackInit() is freed. + + inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream + state was inconsistent. +*/ + +ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void)); +/* Return flags indicating compile-time options. + + Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other: + 1.0: size of uInt + 3.2: size of uLong + 5.4: size of voidpf (pointer) + 7.6: size of z_off_t + + Compiler, assembler, and debug options: + 8: DEBUG + 9: ASMV or ASMINF -- use ASM code + 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention + 11: 0 (reserved) + + One-time table building (smaller code, but not thread-safe if true): + 12: BUILDFIXED -- build static block decoding tables when needed + 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed + 14,15: 0 (reserved) + + Library content (indicates missing functionality): + 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking + deflate code when not needed) + 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect + and decode gzip streams (to avoid linking crc code) + 18-19: 0 (reserved) + + Operation variations (changes in library functionality): + 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate + 21: FASTEST -- deflate algorithm with only one, lowest compression level + 22,23: 0 (reserved) + + The sprintf variant used by gzprintf (zero is best): + 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format + 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure! + 26: 0 = returns value, 1 = void -- 1 means inferred string length returned + + Remainder: + 27-31: 0 (reserved) + */ + + + /* utility functions */ + +/* + The following utility functions are implemented on top of the + basic stream-oriented functions. To simplify the interface, some + default options are assumed (compression level and memory usage, + standard memory allocation functions). The source code of these + utility functions can easily be modified if you need special options. +*/ + +ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen, + const Bytef *source, uLong sourceLen)); +/* + Compresses the source buffer into the destination buffer. sourceLen is + the byte length of the source buffer. Upon entry, destLen is the total + size of the destination buffer, which must be at least the value returned + by compressBound(sourceLen). Upon exit, destLen is the actual size of the + compressed buffer. + This function can be used to compress a whole file at once if the + input file is mmap'ed. + compress returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_BUF_ERROR if there was not enough room in the output + buffer. +*/ + +ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen, + const Bytef *source, uLong sourceLen, + int level)); +/* + Compresses the source buffer into the destination buffer. The level + parameter has the same meaning as in deflateInit. sourceLen is the byte + length of the source buffer. Upon entry, destLen is the total size of the + destination buffer, which must be at least the value returned by + compressBound(sourceLen). Upon exit, destLen is the actual size of the + compressed buffer. + + compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_BUF_ERROR if there was not enough room in the output buffer, + Z_STREAM_ERROR if the level parameter is invalid. +*/ + +ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen)); +/* + compressBound() returns an upper bound on the compressed size after + compress() or compress2() on sourceLen bytes. It would be used before + a compress() or compress2() call to allocate the destination buffer. +*/ + +ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen, + const Bytef *source, uLong sourceLen)); +/* + Decompresses the source buffer into the destination buffer. sourceLen is + the byte length of the source buffer. Upon entry, destLen is the total + size of the destination buffer, which must be large enough to hold the + entire uncompressed data. (The size of the uncompressed data must have + been saved previously by the compressor and transmitted to the decompressor + by some mechanism outside the scope of this compression library.) + Upon exit, destLen is the actual size of the compressed buffer. + This function can be used to decompress a whole file at once if the + input file is mmap'ed. + + uncompress returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_BUF_ERROR if there was not enough room in the output + buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete. +*/ + + +typedef voidp gzFile; + +ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode)); +/* + Opens a gzip (.gz) file for reading or writing. The mode parameter + is as in fopen ("rb" or "wb") but can also include a compression level + ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for + Huffman only compression as in "wb1h", or 'R' for run-length encoding + as in "wb1R". (See the description of deflateInit2 for more information + about the strategy parameter.) + + gzopen can be used to read a file which is not in gzip format; in this + case gzread will directly read from the file without decompression. + + gzopen returns NULL if the file could not be opened or if there was + insufficient memory to allocate the (de)compression state; errno + can be checked to distinguish the two cases (if errno is zero, the + zlib error is Z_MEM_ERROR). */ + +ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode)); +/* + gzdopen() associates a gzFile with the file descriptor fd. File + descriptors are obtained from calls like open, dup, creat, pipe or + fileno (in the file has been previously opened with fopen). + The mode parameter is as in gzopen. + The next call of gzclose on the returned gzFile will also close the + file descriptor fd, just like fclose(fdopen(fd), mode) closes the file + descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode). + gzdopen returns NULL if there was insufficient memory to allocate + the (de)compression state. +*/ + +ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy)); +/* + Dynamically update the compression level or strategy. See the description + of deflateInit2 for the meaning of these parameters. + gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not + opened for writing. +*/ + +ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len)); +/* + Reads the given number of uncompressed bytes from the compressed file. + If the input file was not in gzip format, gzread copies the given number + of bytes into the buffer. + gzread returns the number of uncompressed bytes actually read (0 for + end of file, -1 for error). */ + +ZEXTERN int ZEXPORT gzwrite OF((gzFile file, + voidpc buf, unsigned len)); +/* + Writes the given number of uncompressed bytes into the compressed file. + gzwrite returns the number of uncompressed bytes actually written + (0 in case of error). +*/ + +ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...)); +/* + Converts, formats, and writes the args to the compressed file under + control of the format string, as in fprintf. gzprintf returns the number of + uncompressed bytes actually written (0 in case of error). The number of + uncompressed bytes written is limited to 4095. The caller should assure that + this limit is not exceeded. If it is exceeded, then gzprintf() will return + return an error (0) with nothing written. In this case, there may also be a + buffer overflow with unpredictable consequences, which is possible only if + zlib was compiled with the insecure functions sprintf() or vsprintf() + because the secure snprintf() or vsnprintf() functions were not available. +*/ + +ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s)); +/* + Writes the given null-terminated string to the compressed file, excluding + the terminating null character. + gzputs returns the number of characters written, or -1 in case of error. +*/ + +ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len)); +/* + Reads bytes from the compressed file until len-1 characters are read, or + a newline character is read and transferred to buf, or an end-of-file + condition is encountered. The string is then terminated with a null + character. + gzgets returns buf, or Z_NULL in case of error. +*/ + +ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c)); +/* + Writes c, converted to an unsigned char, into the compressed file. + gzputc returns the value that was written, or -1 in case of error. +*/ + +ZEXTERN int ZEXPORT gzgetc OF((gzFile file)); +/* + Reads one byte from the compressed file. gzgetc returns this byte + or -1 in case of end of file or error. +*/ + +ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file)); +/* + Push one character back onto the stream to be read again later. + Only one character of push-back is allowed. gzungetc() returns the + character pushed, or -1 on failure. gzungetc() will fail if a + character has been pushed but not read yet, or if c is -1. The pushed + character will be discarded if the stream is repositioned with gzseek() + or gzrewind(). +*/ + +ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush)); +/* + Flushes all pending output into the compressed file. The parameter + flush is as in the deflate() function. The return value is the zlib + error number (see function gzerror below). gzflush returns Z_OK if + the flush parameter is Z_FINISH and all output could be flushed. + gzflush should be called only when strictly necessary because it can + degrade compression. +*/ + +ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file, + z_off_t offset, int whence)); +/* + Sets the starting position for the next gzread or gzwrite on the + given compressed file. The offset represents a number of bytes in the + uncompressed data stream. The whence parameter is defined as in lseek(2); + the value SEEK_END is not supported. + If the file is opened for reading, this function is emulated but can be + extremely slow. If the file is opened for writing, only forward seeks are + supported; gzseek then compresses a sequence of zeroes up to the new + starting position. + + gzseek returns the resulting offset location as measured in bytes from + the beginning of the uncompressed stream, or -1 in case of error, in + particular if the file is opened for writing and the new starting position + would be before the current position. +*/ + +ZEXTERN int ZEXPORT gzrewind OF((gzFile file)); +/* + Rewinds the given file. This function is supported only for reading. + + gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET) +*/ + +ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file)); +/* + Returns the starting position for the next gzread or gzwrite on the + given compressed file. This position represents a number of bytes in the + uncompressed data stream. + + gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR) +*/ + +ZEXTERN int ZEXPORT gzeof OF((gzFile file)); +/* + Returns 1 when EOF has previously been detected reading the given + input stream, otherwise zero. +*/ + +ZEXTERN int ZEXPORT gzdirect OF((gzFile file)); +/* + Returns 1 if file is being read directly without decompression, otherwise + zero. +*/ + +ZEXTERN int ZEXPORT gzclose OF((gzFile file)); +/* + Flushes all pending output if necessary, closes the compressed file + and deallocates all the (de)compression state. The return value is the zlib + error number (see function gzerror below). +*/ + +ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum)); +/* + Returns the error message for the last error which occurred on the + given compressed file. errnum is set to zlib error number. If an + error occurred in the file system and not in the compression library, + errnum is set to Z_ERRNO and the application may consult errno + to get the exact error code. +*/ + +ZEXTERN void ZEXPORT gzclearerr OF((gzFile file)); +/* + Clears the error and end-of-file flags for file. This is analogous to the + clearerr() function in stdio. This is useful for continuing to read a gzip + file that is being written concurrently. +*/ + + /* checksum functions */ + +/* + These functions are not related to compression but are exported + anyway because they might be useful in applications using the + compression library. +*/ + +ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len)); +/* + Update a running Adler-32 checksum with the bytes buf[0..len-1] and + return the updated checksum. If buf is NULL, this function returns + the required initial value for the checksum. + An Adler-32 checksum is almost as reliable as a CRC32 but can be computed + much faster. Usage example: + + uLong adler = adler32(0L, Z_NULL, 0); + + while (read_buffer(buffer, length) != EOF) { + adler = adler32(adler, buffer, length); + } + if (adler != original_adler) error(); +*/ + +ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2, + z_off_t len2)); +/* + Combine two Adler-32 checksums into one. For two sequences of bytes, seq1 + and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for + each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of + seq1 and seq2 concatenated, requiring only adler1, adler2, and len2. +*/ + +ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len)); +/* + Update a running CRC-32 with the bytes buf[0..len-1] and return the + updated CRC-32. If buf is NULL, this function returns the required initial + value for the for the crc. Pre- and post-conditioning (one's complement) is + performed within this function so it shouldn't be done by the application. + Usage example: + + uLong crc = crc32(0L, Z_NULL, 0); + + while (read_buffer(buffer, length) != EOF) { + crc = crc32(crc, buffer, length); + } + if (crc != original_crc) error(); +*/ + +ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2)); + +/* + Combine two CRC-32 check values into one. For two sequences of bytes, + seq1 and seq2 with lengths len1 and len2, CRC-32 check values were + calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32 + check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and + len2. +*/ + + + /* various hacks, don't look :) */ + +/* deflateInit and inflateInit are macros to allow checking the zlib version + * and the compiler's view of z_stream: + */ +ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level, + const char *version, int stream_size)); +ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm, + const char *version, int stream_size)); +ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method, + int windowBits, int memLevel, + int strategy, const char *version, + int stream_size)); +ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits, + const char *version, int stream_size)); +ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits, + unsigned char FAR *window, + const char *version, + int stream_size)); +#define deflateInit(strm, level) \ + deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream)) +#define inflateInit(strm) \ + inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream)) +#define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \ + deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\ + (strategy), ZLIB_VERSION, sizeof(z_stream)) +#define inflateInit2(strm, windowBits) \ + inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream)) +#define inflateBackInit(strm, windowBits, window) \ + inflateBackInit_((strm), (windowBits), (window), \ + ZLIB_VERSION, sizeof(z_stream)) + + +#if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL) + struct internal_state {int dummy;}; /* hack for buggy compilers */ +#endif + +ZEXTERN const char * ZEXPORT zError OF((int)); +ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp z)); +ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void)); + +#ifdef __cplusplus +} +#endif + +#endif /* ZLIB_H */ diff --git a/BuildTools/windows/dep/zlib/lib/zlibstat.lib b/BuildTools/windows/dep/zlib/lib/zlibstat.lib new file mode 100644 index 000000000..cad0ab320 Binary files /dev/null and b/BuildTools/windows/dep/zlib/lib/zlibstat.lib differ diff --git a/BuildTools/windows/installer/32bit/GeoDa.iss b/BuildTools/windows/installer/32bit/GeoDa.iss index f5e88a899..6b80dbb28 100644 --- a/BuildTools/windows/installer/32bit/GeoDa.iss +++ b/BuildTools/windows/installer/32bit/GeoDa.iss @@ -1,11 +1,11 @@ [Setup] AppName=GeoDa AppPublisher=GeoDa Center -AppPublisherURL=https://geodacenter.asu.edu/ -AppSupportURL=https://geodacenter.asu.edu/ -AppUpdatesURL=https://geodacenter.asu.edu/ +AppPublisherURL=https://spatial.uchiago.edu/ +AppSupportURL=https://spatial.uchiago.edu/ +AppUpdatesURL=https://spatial.uchiago.edu/ AppSupportPhone=(480)965-7533 -AppVersion=1.8 +AppVersion=1.12 DefaultDirName={pf}\GeoDa Software DefaultGroupName=GeoDa Software ; Since no icons will be created in "{group}", we don't need the wizard @@ -36,6 +36,7 @@ Source: "..\..\..\CommonDistFiles\geoda_prefs.json"; DestDir: "{app}" Source: "..\..\..\CommonDistFiles\web_plugins\*"; DestDir: "{app}\web_plugins"; Flags: recursesubdirs Source: "vcredist_x86.exe"; DestDir: "{app}" +Source: "OpenCL.dll"; DestDir: "{app}" Source: "ogr_FileGDB.dll"; DestDir: "{app}" Source: "ogr_OCI.dll"; DestDir: "{app}" Source: "ogr_SDE.dll"; DestDir: "{app}" @@ -58,6 +59,8 @@ Source: "..\..\temp\boost_1_57_0\stage\lib\boost_chrono-vc100-mt-1_57.dll"; Dest Source: "..\..\temp\boost_1_57_0\stage\lib\boost_thread-vc100-mt-1_57.dll"; DestDir: "{app}" Source: "..\..\temp\boost_1_57_0\stage\lib\boost_system-vc100-mt-1_57.dll"; DestDir: "{app}" +Source: "..\..\..\..\Algorithms\lisa_kernel.cl"; DestDir: "{app}" +Source: "..\..\..\..\internationalization\lang\*"; DestDir: "{app}\lang"; Flags: recursesubdirs Source: "..\..\..\..\SampleData\Examples\*"; DestDir: "{app}\Examples"; Flags: recursesubdirs uninsneveruninstall @@ -156,5 +159,63 @@ begin end; end; +var + Button: TNewButton; + ComboBox: TNewComboBox; + CustomPage: TWizardPage; + langCode: string; + +procedure ComboBoxChange(Sender: TObject); +begin + case ComboBox.ItemIndex of + 0: + begin + langCode := '58'; + end; + 1: + begin + langCode := '45'; // chinese + end; + 2: + begin + langCode := '179'; // spanish + end; + end; +end; + +procedure InitializeWizard; +var + DescLabel: TLabel; +begin + CustomPage := CreateCustomPage(wpSelectDir, 'Language Selection', 'Please select a language for GeoDa'); + + DescLabel := TLabel.Create(WizardForm); + DescLabel.Parent := CustomPage.Surface; + DescLabel.Left := 0; + DescLabel.Top := 0; + DescLabel.Caption := ''; + + ComboBox := TNewComboBox.Create(WizardForm); + ComboBox.Parent := CustomPage.Surface; + ComboBox.Left := 0; + ComboBox.Top := DescLabel.Top + DescLabel.Height + 6; + ComboBox.Width := 220; + ComboBox.Style := csDropDownList; + ComboBox.Items.Add('English'); + ComboBox.Items.Add('Chinese (Simplified)'); + ComboBox.Items.Add('Spanish'); + ComboBox.ItemIndex := 0; + ComboBox.OnChange := @ComboBoxChange; + langCode := '58'; +end; + +function getLangCode(Param: String): String; +begin + Result := langCode; +end; + +[INI] +Filename: "{app}\lang\config.ini"; Section: "Translation"; Key: "Language"; String: {code:getLangCode|{app}} + [Run] Filename: {app}\vcredist_x86.exe; StatusMsg: Installing Visual Studio 2010 SP1 C++ CRT Libraries...; Check: VCRedistNeedsInstall diff --git a/BuildTools/windows/installer/32bit/OpenCL.dll b/BuildTools/windows/installer/32bit/OpenCL.dll new file mode 100644 index 000000000..da84e7fa2 Binary files /dev/null and b/BuildTools/windows/installer/32bit/OpenCL.dll differ diff --git a/BuildTools/windows/installer/64bit/GeoDa.iss b/BuildTools/windows/installer/64bit/GeoDa.iss index bd2947c99..d85bcf50a 100644 --- a/BuildTools/windows/installer/64bit/GeoDa.iss +++ b/BuildTools/windows/installer/64bit/GeoDa.iss @@ -1,11 +1,11 @@ [Setup] AppName=GeoDa AppPublisher=GeoDa Center -AppPublisherURL=https://geodacenter.asu.edu/ -AppSupportURL=https://geodacenter.asu.edu/ -AppUpdatesURL=https://geodacenter.asu.edu/ +AppPublisherURL=https://spatial.uchiago.edu/ +AppSupportURL=https://spatial.uchiago.edu/ +AppUpdatesURL=https://spatial.uchiago.edu/ AppSupportPhone=(480)965-7533 -AppVersion=1.8 +AppVersion=1.12 DefaultDirName={pf}\GeoDa Software DefaultGroupName=GeoDa Software ; Since no icons will be created in "{group}", we don't need the wizard @@ -32,11 +32,17 @@ ArchitecturesInstallIn64BitMode=x64 ChangesAssociations=yes +ShowLanguageDialog=yes + +[Languages] +Name: "en"; MessagesFile: "compiler:Default.isl" +Name: "zh"; MessagesFile: "compiler:Languages\ChineseSimplified.isl" + [dirs] Name: "{app}"; Permissions: everyone-full; Check: InitializeSetup Name: "{app}\Examples"; Permissions: everyone-full Name: "{app}\basemap_cache"; Permissions: everyone-full - +Name: "{app}\lang"; Permissions: everyone-full [Files] @@ -50,6 +56,7 @@ Source: "..\..\..\CommonDistFiles\geoda_prefs.json"; DestDir: "{app}" Source: "..\..\..\CommonDistFiles\web_plugins\*"; DestDir: "{app}\web_plugins"; Flags: recursesubdirs Source: "vcredist_x64.exe"; DestDir: "{app}" +Source: "OpenCL.dll"; DestDir: "{app}" Source: "ogr_FileGDB.dll"; DestDir: "{app}" Source: "ogr_OCI.dll"; DestDir: "{app}" Source: "ogr_SDE.dll"; DestDir: "{app}" @@ -72,6 +79,8 @@ Source: "..\..\temp\boost_1_57_0\stage\lib\boost_chrono-vc100-mt-1_57.dll"; Dest Source: "..\..\temp\boost_1_57_0\stage\lib\boost_thread-vc100-mt-1_57.dll"; DestDir: "{app}" Source: "..\..\temp\boost_1_57_0\stage\lib\boost_system-vc100-mt-1_57.dll"; DestDir: "{app}" +Source: "..\..\..\..\Algorithms\lisa_kernel.cl"; DestDir: "{app}" +Source: "..\..\..\..\internationalization\lang\*"; DestDir: "{app}\lang"; Flags: recursesubdirs Source: "..\..\..\..\SampleData\Examples\*"; DestDir: "{app}\Examples"; Flags: recursesubdirs Source: "..\..\temp\gdal\data\*"; DestDir: "{app}\data"; Flags: recursesubdirs @@ -169,6 +178,64 @@ begin end; end; +var + Button: TNewButton; + ComboBox: TNewComboBox; + CustomPage: TWizardPage; + langCode: string; + +procedure ComboBoxChange(Sender: TObject); +begin + case ComboBox.ItemIndex of + 0: + begin + langCode := '58'; + end; + 1: + begin + langCode := '45'; // chinese + end; + 2: + begin + langCode := '179'; // spanish + end; + end; +end; + +procedure InitializeWizard; +var + DescLabel: TLabel; +begin + CustomPage := CreateCustomPage(wpSelectDir, 'Language Selection', 'Please select a language for GeoDa'); + + DescLabel := TLabel.Create(WizardForm); + DescLabel.Parent := CustomPage.Surface; + DescLabel.Left := 0; + DescLabel.Top := 0; + DescLabel.Caption := ''; + + ComboBox := TNewComboBox.Create(WizardForm); + ComboBox.Parent := CustomPage.Surface; + ComboBox.Left := 0; + ComboBox.Top := DescLabel.Top + DescLabel.Height + 6; + ComboBox.Width := 220; + ComboBox.Style := csDropDownList; + ComboBox.Items.Add('English'); + ComboBox.Items.Add('Chinese (Simplified)'); + ComboBox.Items.Add('Spanish'); + ComboBox.ItemIndex := 0; + ComboBox.OnChange := @ComboBoxChange; + langCode := '58'; +end; + +function getLangCode(Param: String): String; +begin + Result := langCode; +end; + +[INI] +Filename: "{app}\lang\config.ini"; Section: "Translation"; Key: "Language"; String: {code:getLangCode|{app}} + [Run] Filename: {app}\vcredist_x64.exe; StatusMsg: Installing Visual Studio 2010 SP1 C++ CRT Libraries...; Check: VCRedistNeedsInstall diff --git a/BuildTools/windows/installer/64bit/OpenCL.dll b/BuildTools/windows/installer/64bit/OpenCL.dll new file mode 100644 index 000000000..d6b9dcb10 Binary files /dev/null and b/BuildTools/windows/installer/64bit/OpenCL.dll differ diff --git a/CmdLineUtils/header_util/Makefile b/CmdLineUtils/header_util/Makefile deleted file mode 100644 index f7408cfd2..000000000 --- a/CmdLineUtils/header_util/Makefile +++ /dev/null @@ -1,35 +0,0 @@ -APPNAME = header_util -CC = g++ -DEBUG = -g -CFLAGS = `wx-config --cxxflags core` -LFLAGS = `wx-config --libs core` - -TEST_FILE_LIST = foo_dir/a_dir/file1.h foo_dir/a_dir/file1.cpp \ - foo_dir/a_dir/file2.h foo_dir/a_dir/file2.cpp \ - foo_dir/a_dir/file3.h foo_dir/a_dir/file3.cpp \ - foo_dir/b_dir/file1.h foo_dir/b_dir/file1.cpp \ - foo_dir/b_dir/file2.h foo_dir/b_dir/file2.cpp \ - foo_dir/b_dir/file3.h foo_dir/b_dir/file3.cpp - -all: $(APPNAME) - -all64: $(APPNAME)64 - -$(APPNAME)64 : $(APPNAME)64.o - $(CC) -o $(APPNAME)64 $(APPNAME)64.o -m64 $(LFLAGS) - -$(APPNAME)64.o : $(APPNAME).cpp - $(CC) -o $(APPNAME)64.o -m64 $(CFLAGS) -c $(APPNAME).cpp - -$(APPNAME) : $(APPNAME).o - $(CC) -o $(APPNAME) $(APPNAME).o -m32 $(LFLAGS) - -$(APPNAME).o : $(APPNAME).cpp - $(CC) -m32 $(CFLAGS) -c $(APPNAME).cpp - -reset: - rm -f $(TEST_FILE_LIST) - touch $(TEST_FILE_LIST) - -clean: - rm -f *.o $(APPNAME) $(APPNAME)64 diff --git a/CmdLineUtils/header_util/file_list.txt b/CmdLineUtils/header_util/file_list.txt deleted file mode 100644 index f4891f716..000000000 --- a/CmdLineUtils/header_util/file_list.txt +++ /dev/null @@ -1,6 +0,0 @@ -./foo_dir/a_dir/file1.h - -foo_dir/a_dir/file2.h -foo_dir/a_dir/bogus.h -foo_dir/b_dir/file1.cpp - diff --git a/CmdLineUtils/header_util/foo_dir/a_dir/file1.cpp b/CmdLineUtils/header_util/foo_dir/a_dir/file1.cpp deleted file mode 100644 index e69de29bb..000000000 diff --git a/CmdLineUtils/header_util/foo_dir/a_dir/file1.h b/CmdLineUtils/header_util/foo_dir/a_dir/file1.h deleted file mode 100644 index e69de29bb..000000000 diff --git a/CmdLineUtils/header_util/foo_dir/a_dir/file2.cpp b/CmdLineUtils/header_util/foo_dir/a_dir/file2.cpp deleted file mode 100644 index e69de29bb..000000000 diff --git a/CmdLineUtils/header_util/foo_dir/a_dir/file2.h b/CmdLineUtils/header_util/foo_dir/a_dir/file2.h deleted file mode 100644 index e69de29bb..000000000 diff --git a/CmdLineUtils/header_util/foo_dir/a_dir/file3.cpp b/CmdLineUtils/header_util/foo_dir/a_dir/file3.cpp deleted file mode 100644 index e69de29bb..000000000 diff --git a/CmdLineUtils/header_util/foo_dir/a_dir/file3.h b/CmdLineUtils/header_util/foo_dir/a_dir/file3.h deleted file mode 100644 index e69de29bb..000000000 diff --git a/CmdLineUtils/header_util/foo_dir/b_dir/file1.cpp b/CmdLineUtils/header_util/foo_dir/b_dir/file1.cpp deleted file mode 100644 index e69de29bb..000000000 diff --git a/CmdLineUtils/header_util/foo_dir/b_dir/file1.h b/CmdLineUtils/header_util/foo_dir/b_dir/file1.h deleted file mode 100644 index e69de29bb..000000000 diff --git a/CmdLineUtils/header_util/foo_dir/b_dir/file2.cpp b/CmdLineUtils/header_util/foo_dir/b_dir/file2.cpp deleted file mode 100644 index e69de29bb..000000000 diff --git a/CmdLineUtils/header_util/foo_dir/b_dir/file2.h b/CmdLineUtils/header_util/foo_dir/b_dir/file2.h deleted file mode 100644 index e69de29bb..000000000 diff --git a/CmdLineUtils/header_util/foo_dir/b_dir/file3.cpp b/CmdLineUtils/header_util/foo_dir/b_dir/file3.cpp deleted file mode 100644 index e69de29bb..000000000 diff --git a/CmdLineUtils/header_util/foo_dir/b_dir/file3.h b/CmdLineUtils/header_util/foo_dir/b_dir/file3.h deleted file mode 100644 index e69de29bb..000000000 diff --git a/CmdLineUtils/header_util/header_util.cpp b/CmdLineUtils/header_util/header_util.cpp deleted file mode 100644 index 6d6c95f75..000000000 --- a/CmdLineUtils/header_util/header_util.cpp +++ /dev/null @@ -1,183 +0,0 @@ -#include -#include -#include -#include // ::wxFileExists, ::wxCopyFile, etc. -#include -#include -#include // wxTextFile -#include // wxTextInputStream -#include // wxFileInputStream - -using namespace std; // cout, cerr, clog - -void display_usage() -{ - cout << "Usage: header_util help\n"; - cout << " header_util test\n"; - cout << " header_util delete_lines " - "\n"; - cout << " header_util prepend " - "\n" << endl; -} - -void get_file_names(const wxString& file_list_fname, - vector& file_names) -{ - wxFileInputStream fl_file_is(file_list_fname); - wxTextInputStream fl_text_is(fl_file_is); - wxString line; - while (!fl_file_is.Eof()) { - fl_text_is >> line; - if (!line.IsEmpty()) { - if (!wxFileExists(line)) { - wxLogMessage("Warning: " + line + " does not exist"); - } else { - file_names.push_back(line); - } - } - } -} - -void get_prepend_lines(const wxString& prepend_text_fname, - vector& pt_lines) -{ - wxFileInputStream pt_file_is(prepend_text_fname); - wxTextInputStream pt_text_is(pt_file_is); - while (!pt_file_is.Eof()) { - pt_lines.push_back(pt_text_is.ReadLine()); - } -} - -void test() -{ - cout << "Test" << endl; - if (!wxFileExists("foo_bar.txt")) { - cout << "foo_bar.txt does not exist." << endl; - } - if (!wxFileExists("file_list.txt")) { - cout << "file_list.txt does not exist, exiting." << endl; - return; - } - if (!wxFileExists("prepend_text.txt")) { - cout << "prepend_text.txt does not exist, exiting." << endl; - return; - } - - cout << "Contents of file_list.txt:" << endl; - vector file_names; - get_file_names("file_list.txt", file_names); - for (int i=0, iend=file_names.size(); i pt_lines; - get_prepend_lines("prepend_text.txt", pt_lines); - for (int i=0, iend=pt_lines.size(); i file_names; - get_file_names(file_list_fname, file_names); - - for (int i=0, iend=file_names.size(); i num_lines) del_lines = num_lines; - for (long j=0; j file_names; - get_file_names(file_list_fname, file_names); - vector pt_lines; - get_prepend_lines(prepend_text_fname, pt_lines); - - for (int i=0, iend=file_names.size(); i=0; j--) { - tf.InsertLine(pt_lines[j], 0); - } - tf.Write(); // must call write to save changes - } -} - -int main(int argc, char **argv) -{ - cout << "header_util: A program for modifying the top lines\n"; - cout << " of source files.\n" << endl; - wxLog* logger = new wxLogStream(&std::cout); - wxLog::SetActiveTarget(logger); - //wxLogMessage("Sample Log Message, works with threads!"); - - if (argc < 2) { - cout << "Error: Insufficient number of arguments." << endl; - display_usage(); - } else if (strcmp(argv[1], "help") == 0) { - display_usage(); - } else if (strcmp(argv[1], "test") == 0) { - test(); - } else if (strcmp(argv[1], "delete_lines") == 0) { - if (argc < 4) { - cout << "Error: Insufficient number of arguments for delete_lines."; - cout << endl; - cout << "Usage: header_util delete_lines " - "\n"; - } else { - wxString file_list_fname(argv[2]); - wxString str_num_lines(argv[3]); - long num_lines = 0; - str_num_lines.ToLong(&num_lines); - if (num_lines < 0) num_lines = 0; - delete_lines(file_list_fname, num_lines); - } - } else if (strcmp(argv[1], "prepend") == 0) { - if (argc < 4) { - cout << "Error: Insufficient number of arguments for prepend."; - cout << endl; - cout << "Usage: header_util prepend " - "\n" << endl; - } else { - wxString file_list_fname(argv[2]); - wxString prepend_text_fname(argv[3]); - prepend(file_list_fname, prepend_text_fname); - } - } else { - cout << "Error: Unknown command \"" << argv[1] << "\"." << endl; - display_usage(); - } - - delete logger; - return 0; -} diff --git a/CmdLineUtils/header_util/prepend_text.txt b/CmdLineUtils/header_util/prepend_text.txt deleted file mode 100644 index 75efb9959..000000000 --- a/CmdLineUtils/header_util/prepend_text.txt +++ /dev/null @@ -1,4 +0,0 @@ -Prepend text line 1 -Prepend text line 2 - -Prepend text line 3 diff --git a/CmdLineUtils/sp_tm_conv/Makefile b/CmdLineUtils/sp_tm_conv/Makefile deleted file mode 100644 index cb21ab114..000000000 --- a/CmdLineUtils/sp_tm_conv/Makefile +++ /dev/null @@ -1,30 +0,0 @@ -APPNAME = sp_tm_conv -CC = g++ -DEBUG = -g -CFLAGS = `wx-config --cxxflags core` $(DEBUG) -I/usr/local/include/boost -LFLAGS = `wx-config --libs core` - -all: $(APPNAME) - -all64: $(APPNAME)64 - -$(APPNAME)64 : $(APPNAME)64.o DbfFile64.o - $(CC) -o $(APPNAME)64 $(APPNAME)64.o DbfFile64.o -m64 $(LFLAGS) - -$(APPNAME)64.o : $(APPNAME).cpp - $(CC) -o $(APPNAME)64.o -m64 $(CFLAGS) -c $(APPNAME).cpp - -DbfFile64.o : ../../ShapeOperations/DbfFile.h ../../ShapeOperations/DbfFile.cpp - $(CC) -o DbfFile64.o -m64 $(CFLAGS) -c ../../ShapeOperations/DbfFile.cpp - -$(APPNAME) : $(APPNAME).o DbfFile.o - $(CC) -o $(APPNAME) $(APPNAME).o DbfFile.o -m32 $(LFLAGS) - -$(APPNAME).o : $(APPNAME).cpp - $(CC) -m32 $(CFLAGS) -c $(APPNAME).cpp - -DbfFile.o : ../../ShapeOperations/DbfFile.h ../../ShapeOperations/DbfFile.cpp - $(CC) -o DbfFile.o -m32 $(CFLAGS) -c ../../ShapeOperations/DbfFile.cpp - -clean: - rm -f *.o $(APPNAME) $(APPNAME)64 diff --git a/CmdLineUtils/sp_tm_conv/nat.dbf b/CmdLineUtils/sp_tm_conv/nat.dbf deleted file mode 100644 index 1e563cf5c..000000000 Binary files a/CmdLineUtils/sp_tm_conv/nat.dbf and /dev/null differ diff --git a/CmdLineUtils/sp_tm_conv/nat_sp_tm_config.txt b/CmdLineUtils/sp_tm_conv/nat_sp_tm_config.txt deleted file mode 100644 index a6e708906..000000000 --- a/CmdLineUtils/sp_tm_conv/nat_sp_tm_config.txt +++ /dev/null @@ -1,19 +0,0 @@ -input: nat.dbf -output: nat_st.dbf -space-id: FIPSNO -time-id: YEAR integer 1960 1970 1980 1990 -HR HR60 HR70 HR80 HR90 -HC HC60 HC70 HC80 HC90 -PO PO60 PO70 PO80 PO90 -RD RD60 RD70 RD80 RD90 -PS PS60 PS70 PS80 PS90 -UE UE60 UE70 UE80 UE90 -DV DV60 DV70 DV80 DV90 -MA MA60 MA70 MA80 MA90 -POL POL60 POL70 POL80 POL90 -DNL DNL60 DNL70 DNL80 DNL90 -MFIL MFIL59 MFIL69 MFIL79 MFIL89 -FP FP59 FP69 FP79 FP89 -BLK BLK60 BLK70 BLK80 BLK90 -GI GI59 GI69 GI79 GI89 -FH FH60 FH70 FH80 FH90 diff --git a/CmdLineUtils/sp_tm_conv/sp_tm_conv.cpp b/CmdLineUtils/sp_tm_conv/sp_tm_conv.cpp deleted file mode 100644 index 01e8f01f0..000000000 --- a/CmdLineUtils/sp_tm_conv/sp_tm_conv.cpp +++ /dev/null @@ -1,620 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include // ::wxFileExists, ::wxCopyFile, etc. -#include -#include -#include // wxTextFile -#include -#include // wxTextInputStream -#include // wxFileInputStream -#include "../../ShapeOperations/DbfFile.h" - -using namespace std; // cout, cerr, clog -typedef boost::multi_array s_array_type; -typedef boost::multi_array c_ptr_array_type; - -void WriteDbfHeader(std::ofstream& out_file, const DbfFileHeader& header, - const std::vector& fd) -{ - // assumes that file is already open for reading - wxUint32 u_int32; - wxUint32* u_int32p = &u_int32; - wxUint16 u_int16; - wxUint16* u_int16p = &u_int16; - wxUint8 u_int8; - wxUint8* u_int8p = &u_int8; - char membyte; - - // byte 0 - membyte = header.version; - out_file.put(membyte); - - // byte 1 - membyte = (char) (header.year - 1900); - out_file.put(membyte); - - // byte 2 - membyte = (char) header.month; - out_file.put(membyte); - - // byte 3 - membyte = (char) header.day; - out_file.put(membyte); - - // byte 4-7 - u_int32 = header.num_records; - u_int32 = wxUINT32_SWAP_ON_BE(u_int32); - out_file.write((char*) u_int32p, 4); - - // byte 8-9 - u_int16 = header.header_length; - u_int16 = wxUINT16_SWAP_ON_BE(u_int16); - out_file.write((char*) u_int16p, 2); - - // byte 10-11 - u_int16 = header.length_each_record; - u_int16 = wxUINT16_SWAP_ON_BE(u_int16); - out_file.write((char*) u_int16p, 2); - - // byte 12-13 (0x0000) - u_int16 = 0x0; - out_file.write((char*) u_int16p, 2); - - // bytes 14-31: write 0 - membyte = 0; - for (int i=0; i<(31-14)+1; i++) out_file.put(membyte); - - // out_file now points to byte 32, which is the beginning of the list - // of fields. There must be at least one field. Each field descriptor - // is 32 bytes long with byte 0xd following the last field descriptor. - char* byte32_buff = new char[32]; - for (int i=0; i" << endl; - delete logger; - return 1; - } - // array variables: - // vector time_ids; - // list of time ids - // - // std::vector orig_fd - // list of original DBF field descriptors - // name values are converted to uppercase - // - // std::map orig_fd_nm_to_desc; - // map from original DBF field names to descriptors - // - // std::map o_nm_to_col; - // map from orininal DBF field names to col id - // - // std::vector time_fld_nms; - // list of new time field names, excluding space and time ids - // - // int tm_fld_cnt - // number of new time fields exlcuding space and time fields - // - // s_array_type sp_tm_flds; - // boost::extents[tm_fld_cnt][time_steps] - // list of list of old name time fields - // - // std::map is_in_time_tbl; - // map from orig dbf field names to boolean - // does not include space_id_name, even though it is both tables - // - // std::map tm_nm_to_col; - // std::map tm_nm_to_tm_step; - // std::map tm_nm_to_nm; - // maps every time field name from orig to a column, time_step val, - // and new column name - // excludes entries for space_id_name and time_id_name - // column mapping starts from 2 so that there is room for - // space and time columns - // - // std::map sp_nm_to_col; - // maps every non space field name from orig to a column. - // excludes entry fro space_id. space_id will always be the first - // column, so mapping starts from 1 - // - // std::vector new_sp_nm_col; - // - // - // std::vector sp_data(sp_nm_to_col.size()); - // - // c_ptr_array_type tm_data(boost::extents[time_steps][tm_nm_to_col.size()]); - // - - wxString input_dbf; - wxString output_dbf_sp; - wxString output_dbf_tm; // derived from output_dbf_sp - wxString space_id_name; - wxString time_id_name; - DbfFieldDesc space_id_desc; - DbfFieldDesc time_id_desc; - bool is_time_int = true; // otherwise, DBF date type - int time_steps = 0; - vector time_ids; - - wxString fname(argv[1]); - wxFileInputStream file_is(fname); - wxTextInputStream text_is(file_is); - wxString line; - wxString word; - bool found_input = false; - bool found_output = false; - bool found_space_id = false; - bool found_time_id = false; - while (!file_is.Eof() && !(found_input && found_output && - found_space_id && found_time_id)) { - text_is >> word; - if (word == "input:") { - text_is >> input_dbf; - cout << "input_dbf: " << input_dbf << endl; - found_input = true; - } else if (word == "output:") { - text_is >> output_dbf_sp; - output_dbf_tm = output_dbf_sp.BeforeLast('.'); - output_dbf_tm += "_time.dbf"; - cout << "output_dbf_sp: " << output_dbf_sp << endl; - cout << "output_dbf_tm: " << output_dbf_tm << endl; - found_output = true; - } else if (word == "space-id:") { - text_is >> space_id_name; - space_id_name.MakeUpper(); - cout << "space_id_name: " << space_id_name << endl; - found_space_id = true; - } else if (word == "time-id:") { - text_is >> time_id_name; - time_id_name.MakeUpper(); - text_is >> word; - is_time_int = (word.CmpNoCase("integer") == 0); - cout << "time_id_name: " << time_id_name << endl; - cout << "is_time_int: " << (is_time_int ? "true" : "false") << endl; - wxStringTokenizer tkns(text_is.ReadLine()); - // tkns contains a sequence of space-seperated ints or dates - time_steps = tkns.CountTokens(); - time_ids.resize(time_steps); - int tkn_cnt = 0; - while (tkns.HasMoreTokens()) { - long val; - tkns.GetNextToken().ToLong(&val); - time_ids[tkn_cnt++] = (int) val; - } - cout << "time_steps: " << time_steps << endl; - cout << "Time ids: "; - for (int i=0; i orig_fd = orig_reader.getFieldDescs(); - for (size_t i=0, iend=orig_fd.size(); i orig_fd_nm_to_desc; - for (int i=0, iend=orig_fd.size(); i o_nm_to_col; - bool duplicate = false; - for (size_t i=0, iend=orig_fd.size(); i time_fld_nms; - s_array_type sp_tm_flds(boost::extents[orig_header.num_fields][time_steps]); - - int tm_fld_cnt = 0; - while (!file_is.Eof()) { - text_is >> word; - if (!word.IsEmpty()) { - time_fld_nms.push_back(word.Upper()); - wxStringTokenizer tkns(text_is.ReadLine()); - // tkns contains a sequence of space-seperated field names - int tkn_cnt = 0; - while (tkns.HasMoreTokens() && tkn_cnt < time_steps) { - sp_tm_flds[tm_fld_cnt][tkn_cnt] = tkns.GetNextToken().Upper(); - if (orig_fd_nm_to_desc.find(sp_tm_flds[tm_fld_cnt][tkn_cnt]) - == orig_fd_nm_to_desc.end()) { - wxString msg; - msg << "Error, field name "; - msg << sp_tm_flds[tm_fld_cnt][tkn_cnt] << " not found "; - msg << "in input DBF file. Aborting operation."; - wxLogMessage(msg); - exit(1); - } - tkn_cnt++; - } - tm_fld_cnt++; - } - } - - sp_tm_flds.resize(boost::extents[tm_fld_cnt][time_steps]); - std::map is_in_time_tbl; - - const int MAX_NUM_FLD_LEN = 18; - time_id_desc.name = time_id_name; - time_id_desc.type = 'N'; - time_id_desc.length = MAX_NUM_FLD_LEN; - time_id_desc.decimals = 0; - - //wxLogMessage(wxString::Format("(%d, %d)", tm_fld_cnt, time_steps)); - for (int i=0; i space_fd; - std::vector time_fd; - - space_fd.push_back(space_id_desc); - time_fd.push_back(space_id_desc); - time_fd.push_back(time_id_desc); - - // map every time field name to the correct column number - std::map tm_nm_to_col; - std::map tm_nm_to_tm_step; - std::map tm_nm_to_nm; - bool field_desc_missmatch = false; - wxString missmatch_fld1; - wxString missmatch_fld2; - for (int i=0; i sp_nm_to_col; - std::vector new_sp_nm_col; - int sp_col_cnt = 1; // first column is always for space_id - for (int i=0, iend=orig_fd.size(); i sp_data(sp_nm_to_col.size() + 1); - c_ptr_array_type tm_data(boost::extents[time_steps][tm_nm_to_col.size() + 2]); - - sp_data[0] = new char[space_id_desc.length]; - for (int i=0; itm_year+1900; - space_header.month = timeinfo->tm_mon+1; - space_header.day = timeinfo->tm_mday; - space_header.num_records = orig_header.num_records; - space_header.num_fields = space_fd.size(); - space_header.header_length = 32 + space_header.num_fields*32 + 1; - space_header.length_each_record = 1; // first byte is either 0x20 or 0x2A - space_header.length_each_record += space_id_desc.length; - for (int i=0; itm_year+1900; - time_header.month = timeinfo->tm_mon+1; - time_header.day = timeinfo->tm_mday; - time_header.num_records = orig_header.num_records * time_steps; - time_header.num_fields = time_fd.size(); - time_header.header_length = 32 + time_header.num_fields*32 + 1; - time_header.length_each_record = 1; // first byte is either 0x20 or 0x2A - for (int i=0; i max_fld_len) { - max_fld_len = orig_fd[col].length; - } - } - char temp_buf[max_fld_len+1]; - - // time ids never change, so fill in now - for (int tm=0; tm. - */ - -#include - -#include -#include -#include -#include -#include -#include - -#include "../GdaConst.h" -#include "../Project.h" -#include "DataViewerAddColDlg.h" -#include "TableInterface.h" -#include "TableState.h" -#include "../logger.h" -#include "DataChangeType.h" - -using namespace std; - -BEGIN_EVENT_TABLE(DataChangeTypeFrame, TemplateFrame) - EVT_ACTIVATE(DataChangeTypeFrame::OnActivate) -END_EVENT_TABLE() - -DataChangeTypeFrame::DataChangeTypeFrame(wxFrame *parent, Project* project, - const wxString& title, const wxPoint& pos, - const wxSize& size, const long style) -: TemplateFrame(parent, project, title, pos, size, style), -table_state(project->GetTableState()), table_int(project->GetTableInt()), -from_vars(0), from_data(0), -add_var_btn(0), copy_btn(0), -to_vars(0), to_data(0), -ignore_callbacks(false) -{ - wxLogMessage("Open DataChangeTypeFrame."); - - panel = new wxPanel(this); - //panel->SetBackgroundColour(*wxWHITE); - //SetBackgroundColour(*wxWHITE); - - const int list_width = 300; - const int vars_list_height = 100; - const int data_list_height = 200; - - const int name_col_width = 160; - const int type_col_width = 60; - const int time_col_width = 60; - - const int data_id_col_width = 70; - const int data_val_col_width = 300-90; - - wxStaticText* from_title = new wxStaticText(panel, wxID_ANY, "Current Variable"); - from_vars = new wxListCtrl(panel, XRCID("ID_FROM_VARS"), wxDefaultPosition, - wxSize(list_width, vars_list_height), - wxLC_REPORT); - from_vars->AppendColumn("Name"); - from_vars->AppendColumn("Type"); - from_vars->AppendColumn("Time"); - from_vars->SetColumnWidth(NAME_COL, name_col_width); - from_vars->SetColumnWidth(TYPE_COL, type_col_width); - from_vars->SetColumnWidth(TIME_COL, time_col_width); - Connect(XRCID("ID_FROM_VARS"), wxEVT_LIST_ITEM_SELECTED, - wxListEventHandler(DataChangeTypeFrame::OnFromVarsSel)); - Connect(XRCID("ID_FROM_VARS"), wxEVT_LIST_ITEM_ACTIVATED, - wxListEventHandler(DataChangeTypeFrame::OnFromVarsSel)); - - from_data = new GdaColListCtrl(table_int, panel, XRCID("ID_FROM_DATA"), - wxDefaultPosition, - wxSize(list_width, data_list_height)); - from_data->AppendColumn("Row"); - from_data->AppendColumn("Value"); - from_data->SetColumnWidth(DATA_ID_COL, data_id_col_width); - from_data->SetColumnWidth(DATA_VAL_COL, data_val_col_width); - from_data->SetItemCount(table_int->GetNumberRows()); - Connect(XRCID("ID_FROM_DATA"), wxEVT_LIST_ITEM_SELECTED, - wxListEventHandler(DataChangeTypeFrame::OnFromDataSel)); - Connect(XRCID("ID_FROM_DATA"), wxEVT_LIST_ITEM_ACTIVATED, - wxListEventHandler(DataChangeTypeFrame::OnFromDataSel)); - - add_var_btn = new wxButton(panel, XRCID("ID_ADD_VAR_BTN"), " Add Transformed Variable", - wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT); - Connect(XRCID("ID_ADD_VAR_BTN"), wxEVT_BUTTON, - wxCommandEventHandler(DataChangeTypeFrame::OnAddVarBtn)); - - //copy_btn = new wxButton(panel, XRCID("ID_COPY_BTN"), "-> Copy ->", wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT); - //Connect(XRCID("ID_COPY_BTN"), wxEVT_BUTTON, wxCommandEventHandler(DataChangeTypeFrame::OnCopyBtn)); - - wxStaticText* to_title = new wxStaticText(panel, wxID_ANY, "Transformed Variable"); - to_vars = new wxListCtrl(panel, XRCID("ID_TO_VARS"), wxDefaultPosition, - wxSize(list_width, vars_list_height), - wxLC_REPORT); - to_vars->AppendColumn("Name"); - to_vars->AppendColumn("Type"); - to_vars->AppendColumn("Time"); - to_vars->SetColumnWidth(NAME_COL, name_col_width); - to_vars->SetColumnWidth(TYPE_COL, type_col_width); - to_vars->SetColumnWidth(TIME_COL, time_col_width); - Connect(XRCID("ID_TO_VARS"), wxEVT_LIST_ITEM_SELECTED, - wxListEventHandler(DataChangeTypeFrame::OnToVarsSel)); - Connect(XRCID("ID_TO_VARS"), wxEVT_LIST_ITEM_ACTIVATED, - wxListEventHandler(DataChangeTypeFrame::OnToVarsSel)); - - to_data = new GdaColListCtrl(table_int, panel, XRCID("ID_TO_DATA"), - wxDefaultPosition, - wxSize(list_width, data_list_height)); - to_data->AppendColumn("Row"); - to_data->AppendColumn("Value"); - to_data->SetColumnWidth(DATA_ID_COL, data_id_col_width); - to_data->SetColumnWidth(DATA_VAL_COL, data_val_col_width); - to_data->SetItemCount(table_int->GetNumberRows()); - Connect(XRCID("ID_TO_DATA"), wxEVT_LIST_ITEM_SELECTED, - wxListEventHandler(DataChangeTypeFrame::OnToDataSel)); - Connect(XRCID("ID_TO_DATA"), wxEVT_LIST_ITEM_ACTIVATED, - wxListEventHandler(DataChangeTypeFrame::OnToDataSel)); - - wxBoxSizer* from_top_vert_szr = new wxBoxSizer(wxVERTICAL); - - from_top_vert_szr->Add(from_title, 0, wxALIGN_CENTER_HORIZONTAL); - from_top_vert_szr->AddSpacer(5); - from_top_vert_szr->Add(from_vars, 1, wxEXPAND); - from_top_vert_szr->AddSpacer(5); - from_top_vert_szr->Add(from_data, 2, wxEXPAND); - - - wxBoxSizer* btns_top_vert_szr = new wxBoxSizer(wxVERTICAL); - //btns_top_vert_szr->Add(copy_btn, 0, wxALIGN_CENTER_HORIZONTAL); - //btns_top_vert_szr->AddSpacer(20); - btns_top_vert_szr->Add(add_var_btn, 0, wxALIGN_CENTER_HORIZONTAL); - - - wxBoxSizer* to_top_vert_szr = new wxBoxSizer(wxVERTICAL); - - to_top_vert_szr->Add(to_title, 0, wxALIGN_CENTER_HORIZONTAL); - to_top_vert_szr->AddSpacer(5); - to_top_vert_szr->Add(to_vars, 1, wxEXPAND); - to_top_vert_szr->AddSpacer(5); - to_top_vert_szr->Add(to_data, 2, wxEXPAND); - - - wxBoxSizer* panel_h_szr = new wxBoxSizer(wxHORIZONTAL); - panel_h_szr->Add(from_top_vert_szr, 1, wxEXPAND); - panel_h_szr->AddSpacer(10); - panel_h_szr->Add(btns_top_vert_szr, 0, wxALIGN_CENTER_VERTICAL); - panel_h_szr->AddSpacer(10); - panel_h_szr->Add(to_top_vert_szr, 1, wxEXPAND); - - wxBoxSizer* panel_v_szr = new wxBoxSizer(wxVERTICAL); - panel_v_szr->Add(panel_h_szr, 1, wxEXPAND); - - panel->SetSizer(panel_v_szr); - - // Top Sizer for Frame - wxBoxSizer* top_v_sizer = new wxBoxSizer(wxHORIZONTAL); - top_v_sizer->Add(panel, 1, wxEXPAND|wxALL, 8); - - SetSizerAndFit(top_v_sizer); - DisplayStatusBar(false); - - RefreshFromVars(); - RefreshToVars(); - UpdateButtons(); - - table_state->registerObserver(this); - Show(true); -} - -DataChangeTypeFrame::~DataChangeTypeFrame() -{ - if (HasCapture()) ReleaseMouse(); - DeregisterAsActive(); - table_state->removeObserver(this); -} - -void DataChangeTypeFrame::OnActivate(wxActivateEvent& event) -{ - if (event.GetActive()) { - wxLogMessage("In DataChangeTypeFrame::OnActivate"); - RegisterAsActive("DataChangeTypeFrame", GetTitle()); - } - if ( event.GetActive() && template_canvas ) template_canvas->SetFocus(); -} - -void DataChangeTypeFrame::OnAddVarBtn(wxCommandEvent& ev) -{ - wxLogMessage("In DataChangeTypeFrame::OnAddVarBtn"); - - if (!from_vars || !from_data || !to_vars || !to_data) - return; - - wxString from_name; - wxString from_time; - int from_col = -1; - int from_tm = 0; - GdaConst::FieldType from_type; - int from_sel = GetFromVarSel(from_name, from_time); - bool from_tm_variant = true; - - if (from_sel < 0) { - return; - } - - wxString to_name; - wxString to_time; - int to_col = -1; - int to_tm = 0; - GdaConst::FieldType to_type; - int to_sel = GetToVarSel(to_name, to_time); - bool to_tm_variant = true; - - if (to_sel < 0) { - // Add New Field - DataViewerAddColDlg dlg(project, this); - if (dlg.ShowModal() != wxID_OK) return; - wxString new_name = dlg.GetColName(); - RefreshToVars(); - long item = -1; - for (long i=0, sz = to_vars->GetItemCount(); iGetItemText(i, NAME_COL) == new_name) { - item = i; - break; - } - } - if (item != -1) { - for (long i=0, sz = to_vars->GetItemCount(); iSetItemState(i, wxLIST_STATE_SELECTED, wxLIST_STATE_SELECTED); - to_vars->EnsureVisible(i); - } else { - to_vars->SetItemState(i, 0, wxLIST_STATE_SELECTED); - } - } - } - to_sel = GetToVarSel(to_name, to_time); - } else { - wxString msg = _("Tip: clear selection on Transformed Variable list to add a new transformed variable"); - wxString ttl = wxString::Format(_("Do you want to use \"%s\" as Transformed Variable?"), to_name); - wxMessageDialog dlg (this, msg, ttl, wxYES_NO | wxNO_DEFAULT); - if (dlg.ShowModal() != wxID_YES) return; - } - - // Copy - from_col = table_int->FindColId(from_name); - from_tm_variant = table_int->IsColTimeVariant(from_col); - if (from_tm_variant) { - from_tm = table_int->GetTimeInt(from_time); - } - from_type = table_int->GetColType(from_col, from_tm); - - to_col = table_int->FindColId(to_name); - to_tm_variant = table_int->IsColTimeVariant(to_col); - if (to_tm_variant) { - to_tm = table_int->GetTimeInt(to_time); - } - to_type = table_int->GetColType(to_col, to_tm); - - if (from_col < 0 || - from_type == GdaConst::unknown_type || - from_type == GdaConst::placeholder_type || - to_col < 0 || - to_type == GdaConst::unknown_type || - to_type == GdaConst::placeholder_type) - { - wxString s = _("An unknown problem occurred. Could not copy data."); - wxMessageDialog dlg(NULL, s, _("Error"), wxOK | wxICON_ERROR); - dlg.ShowModal(); - //copy_btn->Disable(); - return; - } - - if (to_type == GdaConst::date_type || - to_type == GdaConst::time_type || - to_type == GdaConst::datetime_type) - { - wxString s = _("GeoDa does not support copying to date/time variables currently."); - wxMessageDialog dlg(NULL, s, _("Information"), wxOK | wxICON_INFORMATION); - dlg.ShowModal(); - return; - } - - int num_rows = table_int->GetNumberRows(); - - vector undefined(num_rows, false); - if (from_type == GdaConst::long64_type || - from_type == GdaConst::date_type || - from_type == GdaConst::time_type || - from_type == GdaConst::datetime_type) - { - vector data; - table_int->GetColData(from_col, from_tm, data); - table_int->GetColUndefined(from_col, from_tm, undefined); - if (to_type == GdaConst::long64_type || - to_type == GdaConst::double_type ) - { - table_int->SetColData(to_col, to_tm, data); - table_int->SetColUndefined(to_col, to_tm, undefined); - } - else if (to_type == GdaConst::string_type) - { - vector str(num_rows); - for (size_t i=0, sz=num_rows; iSetColData(to_col, to_tm, str); - table_int->SetColUndefined(to_col, to_tm, undefined); - } - } - else if (from_type == GdaConst::double_type) - { - vector data; - table_int->GetColData(from_col, from_tm, data); - table_int->GetColUndefined(from_col, from_tm, undefined); - if (to_type == GdaConst::long64_type || - to_type == GdaConst::double_type ) - { - table_int->SetColData(to_col, to_tm, data); - table_int->SetColUndefined(to_col, to_tm, undefined); - } - else if (to_type == GdaConst::string_type) - { - vector str(num_rows); - for (size_t i=0, sz=num_rows; iSetColData(to_col, to_tm, str); - table_int->SetColUndefined(to_col, to_tm, undefined); - } - } - else if (from_type == GdaConst::string_type) - { - vector data; - table_int->GetColData(from_col, from_tm, data); - if (to_type == GdaConst::long64_type) - { - vector nums(num_rows, 0); - for (size_t i=0, sz=num_rows; iSetColData(to_col, to_tm, nums); - table_int->SetColUndefined(to_col, to_tm, undefined); - } - else if (to_type == GdaConst::double_type ) - { - vector nums(num_rows, 0); - for (size_t i=0, sz=num_rows; iSetColData(to_col, to_tm, nums); - table_int->SetColUndefined(to_col, to_tm, undefined); - } - else if (to_type == GdaConst::string_type) - { - table_int->SetColData(to_col, to_tm, data); - } - } - - //UpdateButtons(); -} - -void DataChangeTypeFrame::OnCopyBtn(wxCommandEvent& ev) -{ - wxLogMessage("Entering DataChangeTypeFrame::OnCopyBtn"); - wxString from_name; - wxString from_time; - int from_col = -1; - int from_tm = 0; - GdaConst::FieldType from_type; - int from_sel = GetFromVarSel(from_name, from_time); - bool from_tm_variant = true; - - wxString to_name; - wxString to_time; - int to_col = -1; - int to_tm = 0; - GdaConst::FieldType to_type; - int to_sel = GetToVarSel(to_name, to_time); - bool to_tm_variant = true; - - if (from_sel < 0 || to_sel < 0) { - //copy_btn->Disable(); - return; - } - - from_col = table_int->FindColId(from_name); - from_tm_variant = table_int->IsColTimeVariant(from_col); - if (from_tm_variant) { - from_tm = table_int->GetTimeInt(from_time); - } - from_type = table_int->GetColType(from_col, from_tm); - - to_col = table_int->FindColId(to_name); - to_tm_variant = table_int->IsColTimeVariant(to_col); - if (to_tm_variant) { - to_tm = table_int->GetTimeInt(to_time); - } - to_type = table_int->GetColType(to_col, to_tm); - - if (from_col < 0 || - from_type == GdaConst::unknown_type || - from_type == GdaConst::placeholder_type || - to_col < 0 || - to_type == GdaConst::unknown_type || - to_type == GdaConst::placeholder_type) - { - wxString s = _("An unknown problem occurred. Could not copy data."); - wxMessageDialog dlg(NULL, s, "Error", wxOK | wxICON_ERROR); - dlg.ShowModal(); - //copy_btn->Disable(); - return; - } - - if (to_type == GdaConst::date_type || - to_type == GdaConst::time_type || - to_type == GdaConst::datetime_type) - { - wxString s = _("GeoDa does not support copying to date variables currently."); - wxMessageDialog dlg(NULL, s, "Information", wxOK | wxICON_INFORMATION); - dlg.ShowModal(); - return; - } - - int num_rows = table_int->GetNumberRows(); - vector undefined(num_rows, false); - if (from_type == GdaConst::long64_type || - from_type == GdaConst::date_type || - from_type == GdaConst::time_type || - from_type == GdaConst::datetime_type) - { - vector data; - table_int->GetColData(from_col, from_tm, data); - table_int->GetColUndefined(from_col, from_tm, undefined); - if (to_type == GdaConst::long64_type || - to_type == GdaConst::double_type ) - { - table_int->SetColData(to_col, to_tm, data); - table_int->SetColUndefined(to_col, to_tm, undefined); - } - else if (to_type == GdaConst::string_type) - { - vector str(num_rows); - for (size_t i=0, sz=num_rows; iSetColData(to_col, to_tm, str); - } - } - else if (from_type == GdaConst::double_type) - { - vector data; - table_int->GetColData(from_col, from_tm, data); - table_int->GetColUndefined(from_col, from_tm, undefined); - if (to_type == GdaConst::long64_type || - to_type == GdaConst::double_type ) - { - table_int->SetColData(to_col, to_tm, data); - table_int->SetColUndefined(to_col, to_tm, undefined); - } - else if (to_type == GdaConst::string_type) - { - vector str(num_rows); - for (size_t i=0, sz=num_rows; iSetColData(to_col, to_tm, str); - } - } - else if (from_type == GdaConst::string_type) - { - vector data; - table_int->GetColData(from_col, from_tm, data); - if (to_type == GdaConst::long64_type) - { - vector nums(num_rows, 0); - for (size_t i=0, sz=num_rows; iSetColData(to_col, to_tm, nums); - table_int->SetColUndefined(to_col, to_tm, undefined); - } - else if (to_type == GdaConst::double_type ) - { - vector nums(num_rows, 0); - for (size_t i=0, sz=num_rows; iSetColData(to_col, to_tm, nums); - table_int->SetColUndefined(to_col, to_tm, undefined); - } - else if (to_type == GdaConst::string_type) - { - table_int->SetColData(to_col, to_tm, data); - } - } -} - -void DataChangeTypeFrame::OnFromVarsSel(wxListEvent& ev) -{ - wxLogMessage("In DataChangeTypeFrame::OnFromVarsSel"); - if (!from_vars || !from_data || ignore_callbacks) return; - wxString name; - wxString time; - int sel = GetFromVarSel(name, time); - if (sel == -1) { - //LOG_MSG("GetFromVarSel returned -1"); - } - RefreshData(from_data, name, time); - UpdateButtons(); -} - -void DataChangeTypeFrame::OnFromDataSel(wxListEvent& ev) -{ - wxLogMessage("In DataChangeTypeFrame::OnFromDataSel"); - if (!from_data || ignore_callbacks) return; - int sel = ev.GetIndex(); - if (sel < 0 || sel >= from_data->GetItemCount()) return; - from_data->SetItemState(sel, 0, wxLIST_STATE_SELECTED); -} - -void DataChangeTypeFrame::OnToVarsSel(wxListEvent& ev) -{ - wxLogMessage("In DataChangeTypeFrame::OnToVarsSel"); - if (!to_vars || !to_data || ignore_callbacks) return; - wxString name; - wxString time; - int sel = GetToVarSel(name, time); - if (sel == -1) { - //LOG_MSG("GetToVarSel returned -1"); - } - RefreshData(to_data, name, time); - UpdateButtons(); -} - -void DataChangeTypeFrame::OnToDataSel(wxListEvent& ev) -{ - wxLogMessage("In DataChangeTypeFrame::OnToDataSel"); - if (!to_data || ignore_callbacks) return; - int sel = ev.GetIndex(); - if (sel < 0 || sel >= to_data->GetItemCount()) return; - to_data->SetItemState(sel, 0, wxLIST_STATE_SELECTED); -} - -/** Implementation of TableStateObserver interface */ -void DataChangeTypeFrame::update(TableState* o) -{ - RefreshFromVars(); - RefreshToVars(); - UpdateButtons(); -} - -void DataChangeTypeFrame::UpdateButtons() -{ - //if (!copy_btn) return; - if (!from_vars || !from_data || !to_vars || !to_data) { - //copy_btn->Disable(); - return; - } - wxString n, t; - //copy_btn->Enable(GetFromVarSel(n, t) >= 0 && GetToVarSel(n, t) >= 0); -} - -int DataChangeTypeFrame::GetFromVarSel(wxString& name, wxString& time) -{ - return GetVarSel(from_vars, name, time); -} - -void DataChangeTypeFrame::RefreshFromVars() -{ - RefreshVars(from_vars, from_data); -} - -int DataChangeTypeFrame::GetToVarSel(wxString& name, wxString& time) -{ - return GetVarSel(to_vars, name, time); -} - - -void DataChangeTypeFrame::RefreshToVars() -{ - RefreshVars(to_vars, to_data); -} - -int DataChangeTypeFrame::GetVarSel(wxListCtrl* vars_list, - wxString& name, wxString& time) -{ - name = ""; - time = ""; - int sel = -1; - if (!vars_list) return sel; - for (size_t i=0, sz=vars_list->GetItemCount(); iGetItemState(i, wxLIST_STATE_SELECTED) != 0) { - sel = i; - break; - } - } - if (sel >= 0) { - name = vars_list->GetItemText(sel, NAME_COL); - time = vars_list->GetItemText(sel, TIME_COL); - } - wxString s("GetVarSel: "); - s << "name = " << name << ", time = " << time << ", sel = " << sel; - return sel; -} - -void DataChangeTypeFrame::RefreshVars(wxListCtrl* vars_list, - GdaColListCtrl* data_list) -{ - if (!vars_list) - return; - - ignore_callbacks = true; - wxString name; - wxString time; - int sel = GetVarSel(vars_list, name, time); - - vars_list->DeleteAllItems(); - int num_cols = table_int->GetNumberCols(); - long item_cnt=0; - bool found_prev_sel = false; - for (int i=0; iGetColName(i); - std::vector tms; - table_int->GetColNonPlaceholderTmStrs(i, tms); - bool is_tm_variant = table_int->IsColTimeVariant(i); - for (size_t t=0; tGetColType(i, t); - long x = vars_list->InsertItem(item_cnt, wxEmptyString); - vars_list->SetItem(x, NAME_COL, i_name); - vars_list->SetItem(x, TYPE_COL, GdaConst::FieldTypeToStr(ft)); - vars_list->SetItem(x, TIME_COL, (is_tm_variant ? tms[t] : "")); - if (name == i_name && - (time == tms[t] || time == "" && t==0)) { - vars_list->SetItemState(x, wxLIST_STATE_SELECTED, - wxLIST_STATE_SELECTED); - wxString s("RefreshVars reselecting item "); - s << x; - found_prev_sel = true; - } - ++item_cnt; - } - } - if (!found_prev_sel) { - RefreshData(data_list, "", ""); - } else { - RefreshData(data_list, name, time); - } - ignore_callbacks = false; -} - -void DataChangeTypeFrame::RefreshData(GdaColListCtrl* data_list, - const wxString& name, - const wxString& time) -{ - if (!data_list) return; - int tm = 0; - int col = table_int->FindColId(name); - if (col >= 0) { - bool is_tm_variant = table_int->IsColTimeVariant(col); - if (is_tm_variant) { - tm = table_int->GetTimeInt(time); - if (tm < 0) col = -1; - } else { - if (!time.IsEmpty() && table_int->GetTimeInt(time) != 0) col = -1; - } - } - data_list->SetColNumAndTime(col, tm); - data_list->Refresh(); -} - -GdaColListCtrl::GdaColListCtrl(TableInterface* table_int_, - wxWindow* parent, wxWindowID id, - const wxPoint& pos, const wxSize& size) -: wxListCtrl(parent, id, pos, size, wxLC_VIRTUAL|wxLC_REPORT), -table_int(table_int_), col(-1), tm(0) -{ -} - -void GdaColListCtrl::SetColNumAndTime(int column, int time) -{ - col = column; - tm = time; -} - -wxString GdaColListCtrl::OnGetItemText(long item, long column) const -{ - wxString r; - if (col < 0) return ""; - if (column == DataChangeTypeFrame::DATA_ID_COL) { - r << item+1; - return r; - } - return table_int->GetCellString(item, col, tm); -} diff --git a/DataViewer/DataChangeType.h b/DataViewer/DataChangeType.h deleted file mode 100644 index 18dbbcacd..000000000 --- a/DataViewer/DataChangeType.h +++ /dev/null @@ -1,132 +0,0 @@ -/** - * GeoDa TM, Copyright (C) 2011-2015 by Luc Anselin - all rights reserved - * - * This file is part of GeoDa. - * - * GeoDa is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * GeoDa is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -#ifndef __GEODA_CENTER_DATA_CHANGE_TYPE_H__ -#define __GEODA_CENTER_DATA_CHANGE_TYPE_H__ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "../TemplateCanvas.h" -#include "../TemplateFrame.h" -#include "TableStateObserver.h" -#include "../FramesManagerObserver.h" -#include "../GenUtils.h" -#include "../GdaConst.h" - -class GdaColListCtrl; -class TableInterface; -class Project; - -class DataChangeTypeFrame : public TemplateFrame -{ -public: - DataChangeTypeFrame(wxFrame *parent, Project* project, - const wxString& title = _("Change Variable Type"), - const wxPoint& pos = wxDefaultPosition, - const wxSize& size = GdaConst::data_change_type_frame_default_size, - const long style = wxDEFAULT_FRAME_STYLE); - virtual ~DataChangeTypeFrame(); - - void OnActivate(wxActivateEvent& ev); - - void OnFromVarsSel(wxListEvent& ev); - void OnFromDataSel(wxListEvent& ev); - void OnAddVarBtn(wxCommandEvent& ev); - void OnCopyBtn(wxCommandEvent& ev); - void OnToVarsSel(wxListEvent& ev); - void OnToDataSel(wxListEvent& ev); - - /** Implementation of TableStateObserver interface */ - virtual void update(TableState* o); - virtual bool AllowTimelineChanges() { return true; } - virtual bool AllowGroupModify(const wxString& grp_nm) { return true; } - virtual bool AllowObservationAddDelete() { return true; } - - static const long DATA_ID_COL = 0; // id column - static const long DATA_VAL_COL = 1; // val column - -private: - void UpdateButtons(); - - int GetFromVarSel(wxString& name, wxString& time); - void RefreshFromVars(); - - int GetToVarSel(wxString& name, wxString& time); - void RefreshToVars(); - - int GetVarSel(wxListCtrl* vars_list, wxString& name, wxString& time); - void RefreshVars(wxListCtrl* vars_list, GdaColListCtrl* data_list); - void RefreshData(GdaColListCtrl* data_list, const wxString& name, - const wxString& time); - - wxPanel* panel; - - wxListCtrl* from_vars; // ID_FROM_VARS - GdaColListCtrl* from_data; // ID_FROM_DATA - - wxButton* add_var_btn; // ID_ADD_VAR_BTN - wxButton* copy_btn; // ID_COPY_BTN - - wxListCtrl* to_vars; // ID_TO_VARS - GdaColListCtrl* to_data; // ID_TO_DATA - - static const long NAME_COL = 0; // variable name column - static const long TYPE_COL = 1; // type column - static const long TIME_COL = 2; // time column - - TableInterface* table_int; - TableState* table_state; - - bool ignore_callbacks; - - DECLARE_EVENT_TABLE() -}; - -class GdaColListCtrl : public wxListCtrl -{ -public: - GdaColListCtrl(TableInterface* table_int, - wxWindow* parent, wxWindowID id, - const wxPoint& pos = wxDefaultPosition, - const wxSize& size = wxDefaultSize); - - virtual wxString OnGetItemText(long item, long column) const; - void SetColNumAndTime(int col, int time); - -private: - TableInterface* table_int; - - int col; - int tm; - - // once everything is intialized, call SetItemCount(long count) - // to indicate number of items in list. -}; - -#endif diff --git a/DataViewer/DataSource.cpp b/DataViewer/DataSource.cpp index 6eefd6bbf..842986225 100644 --- a/DataViewer/DataSource.cpp +++ b/DataViewer/DataSource.cpp @@ -173,9 +173,9 @@ IDataSource* IDataSource::CreateDataSource(wxString data_type_name, { if (GdaConst::datasrc_str_to_type.find(data_type_name.ToStdString()) == GdaConst::datasrc_str_to_type.end()) { - stringstream ss; - ss << _("datasource.type ") << data_type_name << _(" unknown."); - throw GdaException(ss.str().c_str()); + wxString error_msg = "datasource.type %s unknown.."; + error_msg = wxString::Format(error_msg, data_type_name); + throw GdaException(error_msg.mb_str()); } GdaConst::DataSourceType type = @@ -231,9 +231,9 @@ IDataSource* IDataSource::CreateDataSource(wxString ds_json) std::string ds_type_str = json_ds_type.get_str(); if (GdaConst::datasrc_str_to_type.find(ds_type_str) == GdaConst::datasrc_str_to_type.end()) { - stringstream ss; - ss << _("datasource.type ") << ds_type_str << _(" unknown."); - throw GdaException(ss.str().c_str()); + wxString error_msg = _("datasource.type %s unknown.."); + error_msg = wxString::Format(error_msg, ds_type_str); + throw GdaException(error_msg.mb_str()); } GdaConst::DataSourceType type = GdaConst::datasrc_str_to_type[ds_type_str]; @@ -344,22 +344,26 @@ void FileDataSource::ReadPtree(const ptree& pt, ds_type = IDataSource::FindDataSourceType(type_str); if (ds_type == GdaConst::ds_unknown) { - stringstream ss; - ss << _("datasource.type ") << type_str << _(" unknown."); - throw GdaException(ss.str().c_str()); + wxString error_msg = _("datasource.type %s unknown.."); + error_msg = wxString::Format(error_msg, type_str); + throw GdaException(error_msg.mb_str()); } - file_repository_path = pt.get("path"); + wxString tmp(pt.get("path").c_str(), wxConvUTF8); + file_repository_path = tmp; file_repository_path = GenUtils::RestorePath(proj_path, file_repository_path); + + bool file_exist_flag = false; + if (ds_type == GdaConst::ds_esri_file_geodb) + file_exist_flag = wxDirExists(file_repository_path); + else + file_exist_flag = wxFileExists(file_repository_path); - if (!wxFileExists(file_repository_path)) { - wxString msg; - msg << _("The GeoDa project file cannot find one or more associated data sources.\n\n"); - msg << _("Details: GeoDa is looking for: ") << file_repository_path; - msg << _("\n\nTip: You can open the .gda project file in a text editor to modify the path(s) of the data source associated with your project."); - - throw GdaException(msg.mb_str()); + if (file_exist_flag == false) { + wxString msg = _("The GeoDa project file cannot find one or more associated data sources.\n\nDetails: GeoDa is looking for: %s\n\nTip: You can open the .gda project file in a text editor to modify the path(s) of the data source associated with your project."); + msg = wxString::Format(msg, file_repository_path); + throw GdaException(GET_ENCODED_FILENAME(msg)); } } catch (std::exception &e) { throw GdaException(e.what()); @@ -411,8 +415,8 @@ wxString FileDataSource::GetOGRConnectStr() return file_repository_path; } - wxString error_msg; - error_msg << _("Data source (") << file_repository_path << _(") doesn't exist. Please check the project configuration file."); + wxString error_msg = _("Data source (%s) doesn't exist. Please check the project configuration file."); + error_msg = wxString::Format(error_msg, file_repository_path); throw GdaException(error_msg.mb_str()); } @@ -452,9 +456,9 @@ void WebServiceDataSource::ReadPtree(const ptree& pt, ds_type = IDataSource::FindDataSourceType(type_str); if (ds_type == GdaConst::ds_unknown) { - stringstream ss; - ss << _("datasource.type ") << type_str << _(" unknown."); - throw GdaException(ss.str().c_str()); + wxString error_msg = _("datasource.type %s unknown.."); + error_msg = wxString::Format(error_msg, type_str); + throw GdaException(error_msg.mb_str()); } webservice_url = pt.get("url"); @@ -614,9 +618,9 @@ void DBDataSource::ReadPtree(const ptree& pt, ds_type = IDataSource::FindDataSourceType(type_str); if (ds_type == GdaConst::ds_unknown) { - stringstream ss; - ss << _("datasource type ") << type_str << _(" unknown."); - throw GdaException(ss.str().c_str()); + wxString error_msg = _("datasource.type %s unknown.."); + error_msg = wxString::Format(error_msg, type_str); + throw GdaException(error_msg.mb_str()); } db_name = pt.get("db_name"); diff --git a/DataViewer/DataSource.h b/DataViewer/DataSource.h index 9f7e21514..0d4c92e03 100644 --- a/DataViewer/DataSource.h +++ b/DataViewer/DataSource.h @@ -72,6 +72,8 @@ class IDataSource : public PtreeInterface { virtual wxString ToString() = 0; + virtual void UpdateDataSource(GdaConst::DataSourceType _ds_type) = 0; + /** * Read subtree starting from passed in node pt. * @param const ptree& pt: a subtree of "datasource" node @@ -136,7 +138,7 @@ class FileDataSource : public IDataSource { bool is_writable; public: - /// implementation of IDataSource interfaces + /// implementation of IDataSource interfaces virtual wxString GetOGRConnectStr(); virtual bool IsWritable(){return is_writable;} @@ -157,6 +159,10 @@ class FileDataSource : public IDataSource { return ds_type == GdaConst::ds_sqlite || ds_type == GdaConst::ds_gpkg ? false : true; } + virtual void UpdateDataSource(GdaConst::DataSourceType _ds_type) { + ds_type = _ds_type; + } + virtual wxString GetJsonStr(); /** @@ -206,6 +212,10 @@ class WebServiceDataSource: public IDataSource{ wxString GetURL() { return webservice_url; } virtual wxString ToString(); + + virtual void UpdateDataSource(GdaConst::DataSourceType _ds_type) { + ds_type = _ds_type; + } }; @@ -255,6 +265,10 @@ class DBDataSource: public IDataSource{ wxString GetDBPort() { return db_port; } wxString GetDBUser() { return db_user; } wxString GetDBPwd() { return db_pwd; } + + virtual void UpdateDataSource(GdaConst::DataSourceType _ds_type) { + ds_type = _ds_type; + } }; diff --git a/DataViewer/DataViewerAddColDlg.cpp b/DataViewer/DataViewerAddColDlg.cpp index 4bf4c7831..413502182 100644 --- a/DataViewer/DataViewerAddColDlg.cpp +++ b/DataViewer/DataViewerAddColDlg.cpp @@ -29,7 +29,6 @@ #include "TimeState.h" #include "../Project.h" #include "../logger.h" -#include "../DbfFile.h" #include "../GeoDa.h" #include "../TemplateCanvas.h" #include "../GdaConst.h" @@ -80,8 +79,10 @@ fixed_lengths(project_s->GetTableInt()->HasFixedLengths()) table_int->FillColIdMap(col_id_map); for (int i=0, iend=table_int->GetNumberCols(); iGetColName(i).Upper()); - m_insert_pos->Append(table_int->GetColName(i).Upper()); + int actual_idx = col_id_map[i]; + wxString col_name = table_int->GetColName(actual_idx); + curr_col_labels.insert(col_name.Upper()); + m_insert_pos->Append(col_name.Upper()); } m_insert_pos->Append("after last variable"); @@ -93,6 +94,7 @@ fixed_lengths(project_s->GetTableInt()->HasFixedLengths()) void DataViewerAddColDlg::CreateControls() { + wxLogMessage("DataViewerAddColDlg::CreateControls()"); SetBackgroundColour(*wxWHITE); if (time_variant && fixed_lengths) { wxXmlResource::Get()->LoadDialog(this, GetParent(), "ID_DATA_VIEWER_ADD_COL_TIME_FIXED_DLG"); @@ -112,18 +114,7 @@ void DataViewerAddColDlg::CreateControls() name_validator.SetCharIncludes(name_chars); m_name->SetValidator(name_validator); m_name_valid = false; - - m_time_variant_no = 0; - m_time_variant_yes = 0; - if (FindWindow(XRCID("ID_TIME_VARIANT_NO"))) { - m_time_variant_no = wxDynamicCast(FindWindow(XRCID("ID_TIME_VARIANT_NO")), wxRadioButton); - m_time_variant_yes = wxDynamicCast(FindWindow(XRCID("ID_TIME_VARIANT_YES")), wxRadioButton); - m_time_variant_no->SetValue(time_variant_no_as_default); - m_time_variant_yes->SetValue(!time_variant_no_as_default); - m_time_variant_no->Enable(can_change_time_variant); - m_time_variant_yes->Enable(can_change_time_variant); - } - + m_type = wxDynamicCast(FindWindow(XRCID("ID_CHOICE_TYPE")), wxChoice); // add options for Float, Integer, String, or Date m_type->Append("real (eg 1.03, 45.7)"); @@ -134,10 +125,10 @@ void DataViewerAddColDlg::CreateControls() wxStaticText* mt = wxDynamicCast(FindWindow(XRCID("ID_STATIC_INSERT_POS")), wxStaticText); m_insert_pos = wxDynamicCast(FindWindow(XRCID("ID_CHOICE_INSERT_POS")), wxChoice); - if ( !project->IsFileDataSource()) { - mt->Disable(); - m_insert_pos->Disable(); - } + //if ( !project->IsFileDataSource()) { + // mt->Disable(); + // m_insert_pos->Disable(); + //} m_displayed_decimals_lable = wxDynamicCast(FindWindow(XRCID("ID_STATIC_DISPLAYED_DECIMALS")), wxStaticText); m_displayed_decimals = wxDynamicCast(FindWindow(XRCID("ID_DISPLAYED_DECIMALS")), wxChoice); @@ -222,6 +213,7 @@ void DataViewerAddColDlg::OnChoiceType( wxCommandEvent& ev ) void DataViewerAddColDlg::SetDefaultsByType(GdaConst::FieldType type) { + wxLogMessage("In DataViewerAddColDlg::SetDefaultsByType()"); // set some defaults first m_displayed_decimals->SetSelection(0); m_displayed_decimals->Disable(); @@ -296,23 +288,22 @@ void DataViewerAddColDlg::SetDefaultsByType(GdaConst::FieldType type) void DataViewerAddColDlg::OnOkClick( wxCommandEvent& ev ) { - wxLogMessage("Entering DataViewerAddColDlg::OnOkClick"); + wxLogMessage("DataViewerAddColDlg::OnOkClick()"); wxString colname = m_name->GetValue(); colname.Trim(true); // trim white-space from right of string colname.Trim(false); // trim white-space from left of string if (colname == wxEmptyString) { - wxString msg("Error: The table variable name is empty."); - wxMessageDialog dlg (this, msg, "Error", wxOK | wxICON_ERROR); + wxString msg = _("Error: The table variable name is empty."); + wxMessageDialog dlg (this, msg, _("Error"), wxOK | wxICON_ERROR); dlg.ShowModal(); return; } if (curr_col_labels.find(colname.Upper()) != curr_col_labels.end()) { - wxString msg; - msg += "Error: \"" + colname.Upper(); - msg += "\" already exists in Table, please specify a different name."; - wxMessageDialog dlg (this, msg, "Error", wxOK | wxICON_ERROR); + wxString msg = _("Error: \"%s\" already exists in Table, please specify a different name."); + msg = wxString::Format(msg, colname.Upper()); + wxMessageDialog dlg (this, msg, _("Error"), wxOK | wxICON_ERROR); dlg.ShowModal(); return; } @@ -320,9 +311,9 @@ void DataViewerAddColDlg::OnOkClick( wxCommandEvent& ev ) bool m_name_valid = table_int->IsValidDBColName(colname); //if ( !DbfFileUtils::isValidFieldName(colname) ) { if (!m_name_valid) { - wxString msg; - msg += "Error: \"" + colname + "\" is an invalid variable name. The first character must be alphabetic, and the remaining characters can be either alphanumeric or underscores. For DBF table, a valid variable name is between one and ten characters long."; - wxMessageDialog dlg(this, msg, "Error", wxOK | wxICON_ERROR); + wxString msg = _("Error: \"%s\" is an invalid variable name. The first character must be alphabetic, and the remaining characters can be either alphanumeric or underscores. For DBF table, a valid variable name is between one and ten characters long."); + msg = wxString::Format(msg, colname.Upper()); + wxMessageDialog dlg(this, msg, _("Error"), wxOK | wxICON_ERROR); dlg.ShowModal(); return; } @@ -341,13 +332,9 @@ void DataViewerAddColDlg::OnOkClick( wxCommandEvent& ev ) DbfFileUtils::SuggestDoubleParams(m_length_val, m_decimals_val, &suggest_len, &suggest_dec); if (m_length_val != suggest_len || m_decimals_val != suggest_dec) { - wxString m; - m << "Error: Due to restrictions on the DBF file format, the "; - m << "particular combination of length and decimals entered is "; - m << "not valid. Based on your current choices, we recommend "; - m << "length = " << suggest_len; - m << " and decimals = " << suggest_dec; - wxMessageDialog dlg(this, m, "Error", wxOK | wxICON_ERROR); + wxString m = _("Error: Due to restrictions on the DBF file format, the particular combination of length and decimals entered is not valid. Based on your current choices, we recommend length = %d and decimals = %d"); + m = wxString::Format(m, suggest_len, suggest_dec); + wxMessageDialog dlg(this, m, _("Error"), wxOK | wxICON_ERROR); dlg.ShowModal(); return; } @@ -370,11 +357,8 @@ void DataViewerAddColDlg::OnOkClick( wxCommandEvent& ev ) } int time_steps = 1; // non-space-time column by default - if (m_time_variant_yes && m_time_variant_yes->GetValue()) { - time_steps = table_int->GetTimeSteps(); - } - wxLogMessage(wxString::Format("Inserting new column %s into Table", colname.Upper())); + wxLogMessage(wxString::Format(_("Inserting new column %s into Table"), colname.Upper())); bool success; if (fixed_lengths) { @@ -388,11 +372,11 @@ void DataViewerAddColDlg::OnOkClick( wxCommandEvent& ev ) if (!success) { wxString msg = _("Could not create a new variable. Possibly a read-only data source."); - wxMessageDialog dlg(this, msg, "Error", wxOK | wxICON_ERROR ); + wxMessageDialog dlg(this, msg, _("Error"), wxOK | wxICON_ERROR ); dlg.ShowModal(); return; } - final_col_name = colname.Upper(); + final_col_name = colname.Upper(); final_col_id = col_insert_pos; @@ -417,6 +401,7 @@ void DataViewerAddColDlg::OnEditName( wxCommandEvent& ev ) void DataViewerAddColDlg::CheckName() { + wxLogMessage("DataViewerAddColDlg::CheckName()"); wxString s = m_name->GetValue(); m_name_valid = table_int->IsValidDBColName(s); if ( m_name_valid ) { @@ -474,7 +459,7 @@ void DataViewerAddColDlg::OnEditDecimals( wxCommandEvent& ev ) if (!fixed_lengths) return; - if (!cur_type == GdaConst::double_type) { + if (cur_type != GdaConst::double_type) { m_decimals_valid = true; UpdateApplyButton(); return; @@ -512,6 +497,8 @@ void DataViewerAddColDlg::OnChoiceDisplayedDecimals( wxCommandEvent& ev ) void DataViewerAddColDlg::UpdateMinMaxValues() { + wxLogMessage("DataViewerAddColDlg::UpdateMinMaxValues()"); + if (!fixed_lengths) return; m_max_val->SetLabelText(""); @@ -543,6 +530,8 @@ void DataViewerAddColDlg::UpdateMinMaxValues() void DataViewerAddColDlg::UpdateApplyButton() { + wxLogMessage("DataViewerAddColDlg::UpdateApplyButton()"); + if (fixed_lengths) { bool enable = false; if (cur_type == GdaConst::double_type) { diff --git a/DataViewer/DataViewerDeleteColDlg.cpp b/DataViewer/DataViewerDeleteColDlg.cpp index 5d8192fe0..7522e83eb 100644 --- a/DataViewer/DataViewerDeleteColDlg.cpp +++ b/DataViewer/DataViewerDeleteColDlg.cpp @@ -76,24 +76,46 @@ void DataViewerDeleteColDlg::OnDelete( wxCommandEvent& ev ) } col_id_map.clear(); table_int->FillColIdMap(col_id_map); + + // check selected variables first + bool check_success = true; + for (int i=n-1; i>=0; i--) { + int idx = selections[i]; + wxString nm = name_to_nm[m_field->GetString(idx)]; + int col = table_int->FindColId(nm); + if (col == wxNOT_FOUND) { + wxString err_msg = wxString::Format(_("Variable %s is no longer in the Table. Please close and reopen this dialog to synchronize with Table data."), nm); + wxMessageDialog dlg(NULL, err_msg, _("Error"), wxOK | wxICON_ERROR); + dlg.ShowModal(); + check_success = false; + break; + } + if (table_int->IsColTimeVariant(col)) { + wxString err_msg = wxString::Format(_("Variable %s is a time-grouped variable. Please ungroup this variable to delete."), nm); + wxMessageDialog dlg(NULL, err_msg, _("Info"), wxOK | wxICON_ERROR); + dlg.ShowModal(); + check_success = false; + break; + + } + } + if (!check_success) + return; for (int i=n-1; i>=0; i--) { int idx = selections[i]; - int col_del_pos = col_id_map[idx]; - wxString del_name; - del_name = table_int->GetColName(col_del_pos); - - wxLogMessage(del_name); + wxString nm = name_to_nm[m_field->GetString(idx)]; + int col = table_int->FindColId(nm); + wxLogMessage(nm); try{ - table_int->DeleteCol(col_del_pos); - + table_int->DeleteCol(col); m_del_button->Enable(false); } catch (GdaException e) { wxString msg; - msg << "Delete " << del_name << ". " <Clear(); - table_int->FillColIdMap(col_id_map); - items.clear(); - for (int i=0, iend=table_int->GetNumberCols(); iGetColName(col_id_map[i])); - } - m_field->InsertItems(items, 0); - + wxArrayString var_items; + table_int->FillColIdMap(col_id_map); + for (int i=0, iend=col_id_map.size(); iGetColName(id); + if (table_int->IsColTimeVariant(id)) { + wxString nm = name; + for (int t=0; tGetColTimeSteps(id); t++) { + nm << " (" << table_int->GetTimeString(t) << ")"; + } + name_to_nm[nm] = name; + var_items.Add(nm); + } else { + name_to_nm[name] = name; + var_items.Add(name); + } + } + m_field->InsertItems(var_items,0); } diff --git a/DataViewer/DataViewerDeleteColDlg.h b/DataViewer/DataViewerDeleteColDlg.h index e3d290685..219166c63 100644 --- a/DataViewer/DataViewerDeleteColDlg.h +++ b/DataViewer/DataViewerDeleteColDlg.h @@ -43,6 +43,8 @@ class DataViewerDeleteColDlg: public wxDialog wxStaticText* m_message; TableInterface* table_int; wxArrayString items; + std::map name_to_nm; + std::map name_to_tm_id; private: // a mapping from displayed col order to actual col ids in table diff --git a/DataViewer/DataViewerEditFieldPropertiesDlg.cpp b/DataViewer/DataViewerEditFieldPropertiesDlg.cpp index 69e64c5e5..fc1c7ae80 100644 --- a/DataViewer/DataViewerEditFieldPropertiesDlg.cpp +++ b/DataViewer/DataViewerEditFieldPropertiesDlg.cpp @@ -21,10 +21,11 @@ #include #include #include +#include + #include "../logger.h" #include "../Project.h" #include "../GeoDa.h" -#include "../DbfFile.h" #include "../FramesManager.h" #include "../GdaException.h" @@ -32,6 +33,9 @@ #include "TableState.h" #include "DataViewerEditFieldPropertiesDlg.h" +using namespace std; +namespace bt = boost::posix_time; + BEGIN_EVENT_TABLE( DataViewerEditFieldPropertiesDlg, wxDialog ) EVT_GRID_EDITOR_SHOWN( DataViewerEditFieldPropertiesDlg::OnCellEditorShown ) @@ -85,6 +89,7 @@ table_state(project_s->GetTableState()) DataViewerEditFieldPropertiesDlg::~DataViewerEditFieldPropertiesDlg() { + wxLogMessage("Close DataViewerEditFieldPropertiesDlg"); //frames_manager->removeObserver(this); table_state->removeObserver(this); } @@ -94,15 +99,15 @@ void DataViewerEditFieldPropertiesDlg::CreateControls() //wxBoxSizer *top_sizer = new wxBoxSizer(wxVERTICAL); field_grid = new wxGrid(this, wxID_ANY, wxDefaultPosition, wxSize(200,400)); field_grid->CreateGrid(table_int->GetNumberCols(), NUM_COLS, wxGrid::wxGridSelectRows); - if (COL_N!=-1) field_grid->SetColLabelValue(COL_N, "variable name"); - if (COL_T!=-1) field_grid->SetColLabelValue(COL_T, "type"); - if (COL_L!=-1) field_grid->SetColLabelValue(COL_L, "length"); - if (COL_D!=-1) field_grid->SetColLabelValue(COL_D, "decimal\nplaces"); - if (COL_DD!=-1) field_grid->SetColLabelValue(COL_DD, "displayed\ndecimal places"); - if (COL_PG!=-1) field_grid->SetColLabelValue(COL_PG, "parent group"); - if (COL_TM!=-1) field_grid->SetColLabelValue(COL_TM, "time"); - if (COL_MIN!=-1) field_grid->SetColLabelValue(COL_MIN, "minimum\npossible"); - if (COL_MAX!=-1) field_grid->SetColLabelValue(COL_MAX, "maximum\npossible"); + if (COL_N!=-1) field_grid->SetColLabelValue(COL_N, _("variable name")); + if (COL_T!=-1) field_grid->SetColLabelValue(COL_T, _("type")); + if (COL_L!=-1) field_grid->SetColLabelValue(COL_L, _("length")); + if (COL_D!=-1) field_grid->SetColLabelValue(COL_D, _("decimal\nplaces")); + if (COL_DD!=-1) field_grid->SetColLabelValue(COL_DD, _("displayed\ndecimal places")); + if (COL_PG!=-1) field_grid->SetColLabelValue(COL_PG, _("parent group")); + if (COL_TM!=-1) field_grid->SetColLabelValue(COL_TM, _("time")); + if (COL_MIN!=-1) field_grid->SetColLabelValue(COL_MIN, _("minimum\npossible")); + if (COL_MAX!=-1) field_grid->SetColLabelValue(COL_MAX, _("maximum\npossible")); field_grid->HideRowLabels(); field_grid->SetColLabelSize(30); @@ -407,8 +412,8 @@ void DataViewerEditFieldPropertiesDlg::OnCellChanging( wxGridEvent& ev ) } } - long min_v; - long max_v; + int min_v; + int max_v; if (col == COL_T) { if (combo_selection >=0) { @@ -429,15 +434,19 @@ void DataViewerEditFieldPropertiesDlg::OnCellChanging( wxGridEvent& ev ) } else if (new_type_str == "string") { new_type = GdaConst::string_type; + } else if (new_type_str == "date") { + new_type = GdaConst::date_type; + + } else if (new_type_str == "time") { + new_type = GdaConst::time_type; + + } else if (new_type_str == "datetime") { + new_type = GdaConst::datetime_type; } - if (new_type == GdaConst::unknown_type || - new_type_str == "date" || - new_type_str == "time" || - new_type_str == "datetime") - { + if (new_type == GdaConst::unknown_type) { wxString m = _("GeoDa can't change the variable type to DATE/TIME. Please select another type."); - wxMessageDialog dlg(this, m, "Error", wxOK | wxICON_ERROR); + wxMessageDialog dlg(this, m, _("Error"), wxOK | wxICON_ERROR); dlg.ShowModal(); combo_selection = -1; ev.Veto(); @@ -460,26 +469,39 @@ void DataViewerEditFieldPropertiesDlg::OnCellChanging( wxGridEvent& ev ) from_col = from_col + 1; int num_rows = table_int->GetNumberRows(); - if (new_type == GdaConst::long64_type || - new_type == GdaConst::date_type || - new_type == GdaConst::time_type || - new_type == GdaConst::datetime_type) + if (new_type == GdaConst::long64_type) { // get data from old vector data(num_rows); table_int->GetColData(from_col, 0, data); table_int->SetColData(to_col, 0, data); + field_grid->SetReadOnly(row, COL_DD, true); + + } else if (new_type == GdaConst::date_type || + new_type == GdaConst::time_type || + new_type == GdaConst::datetime_type) { + // get data from old + vector data(num_rows); + table_int->GetColData(from_col, 0, data); + table_int->SetColData(to_col, 0, data); + + field_grid->SetReadOnly(row, COL_DD, true); + } else if (new_type == GdaConst::double_type) { // get data from old vector data(num_rows); table_int->GetColData(from_col, 0, data); table_int->SetColData(to_col, 0, data); + field_grid->SetReadOnly(row, COL_DD, false); + } else if (new_type == GdaConst::string_type) { vector data(num_rows); table_int->GetColData(from_col, 0, data); table_int->SetColData(to_col, 0, data); + + field_grid->SetReadOnly(row, COL_DD, true); } vector undefined(num_rows, false); @@ -501,7 +523,7 @@ void DataViewerEditFieldPropertiesDlg::OnCellChanging( wxGridEvent& ev ) table_int->DeleteCol(tmp_col); } wxString m = wxString::Format(_("Change variable type for \"%s\" has failed. Please check all values are valid for conversion."), var_name); - wxMessageDialog dlg(this, m, "Error", wxOK | wxICON_ERROR); + wxMessageDialog dlg(this, m, _("Error"), wxOK | wxICON_ERROR); dlg.ShowModal(); combo_selection = -1; ev.Veto(); @@ -517,7 +539,7 @@ void DataViewerEditFieldPropertiesDlg::OnCellChanging( wxGridEvent& ev ) if (table_int->DoesNameExist(new_str, false) || !table_int->IsValidDBColName(new_str)) { wxString m = wxString::Format(_("Variable name \"%s\" is either a duplicate or is invalid. Please enter an alternative, non-duplicate variable name. The first character must be a letter, and the remaining characters can be either letters, numbers or underscores. For DBF table, a valid variable name is between one and ten characters long."), new_str); - wxMessageDialog dlg(this, m, "Error", wxOK | wxICON_ERROR); + wxMessageDialog dlg(this, m, _("Error"), wxOK | wxICON_ERROR); dlg.ShowModal(); ev.Veto(); return; @@ -534,7 +556,7 @@ void DataViewerEditFieldPropertiesDlg::OnCellChanging( wxGridEvent& ev ) if (table_int->DoesNameExist(new_str, false) || !table_int->IsValidGroupName(new_str)) { wxString m = wxString::Format(_("Variable name \"%s\" is either a duplicate or is invalid. Please enter an alternative, non-duplicate variable name."), new_str); - wxMessageDialog dlg(this, m, "Error", wxOK | wxICON_ERROR); + wxMessageDialog dlg(this, m, _("Error"), wxOK | wxICON_ERROR); dlg.ShowModal(); ev.Veto(); return; diff --git a/DataViewer/DataViewerResizeColDlg.cpp b/DataViewer/DataViewerResizeColDlg.cpp index a47005cc5..83a2785d9 100644 --- a/DataViewer/DataViewerResizeColDlg.cpp +++ b/DataViewer/DataViewerResizeColDlg.cpp @@ -64,7 +64,7 @@ void DataViewerResizeColDlg::OnOkClick( wxCommandEvent& event ) if (id < 0 || id >= grid->GetNumberCols()) { wxString msg("Error: Col ID not specified or out-of-range."); - wxMessageDialog dlg (this, msg, "Error", wxOK | wxICON_ERROR); + wxMessageDialog dlg (this, msg, _("Error"), wxOK | wxICON_ERROR); dlg.ShowModal(); return; } diff --git a/DataViewer/DbfColContainer.cpp b/DataViewer/DbfColContainer.cpp deleted file mode 100644 index 30247461a..000000000 --- a/DataViewer/DbfColContainer.cpp +++ /dev/null @@ -1,701 +0,0 @@ -/** - * GeoDa TM, Copyright (C) 2011-2015 by Luc Anselin - all rights reserved - * - * This file is part of GeoDa. - * - * GeoDa is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * GeoDa is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -#include -#include -#include -#include -#include -#include // for vector sorting -#include -#include -#include -#include -#include -#include "DbfColContainer.h" -#include "../HighlightState.h" -#include "../GdaConst.h" -#include "../GeneralWxUtils.h" -#include "../GenUtils.h" -#include "../logger.h" -#include "../ShapeOperations/CsvFileUtils.h" -#include "TableState.h" -#include "DbfColContainer.h" - - -DbfColContainer::DbfColContainer() -: size(0), undefined_initialized(false), raw_data(0), -l_vec(0), d_vec(0), s_vec(0) -{ - info.type = GdaConst::unknown_type; -} - -DbfColContainer::~DbfColContainer() -{ - if (IsRawDataAlloc()) FreeRawData(); - FreeVecData(); -} - -bool DbfColContainer::Init(int size_s, - const GdaConst::FieldInfo& field_info_s, - bool alloc_raw_data, - bool alloc_vector_data, - bool mark_all_defined) -{ - if (size_s <= 0) return false; - if (field_info_s.type == GdaConst::unknown_type || - field_info_s.type == GdaConst::placeholder_type) return false; - - info = field_info_s; - size = size_s; - - stale_min_max_val = true; - min_val = 0; - max_val = 0; - - // if mark_all_defined is true, then mark all as begin defined. - undefined.resize(size_s); - std::fill(undefined.begin(), undefined.end(), !mark_all_defined); - undefined_initialized = mark_all_defined; - - if (alloc_raw_data) AllocRawData(); - if (alloc_vector_data) AllocVecData(); - - return true; -} - -void DbfColContainer::FreeRawData() -{ - if (raw_data) delete [] raw_data; raw_data = 0; -} - -void DbfColContainer::AllocRawData() -{ - if (IsRawDataAlloc()) FreeRawData(); - if (info.type != GdaConst::unknown_type && - info.type != GdaConst::placeholder_type) { - raw_data = new char[size * (info.field_len+1)]; - } else { - raw_data = 0; - } -} - -bool DbfColContainer::IsRawDataAlloc() -{ - return (info.type != GdaConst::unknown_type && - info.type != GdaConst::placeholder_type && - raw_data); -} - -void DbfColContainer::FreeVecData() -{ - if (l_vec) delete [] l_vec; l_vec = 0; - if (d_vec) delete [] d_vec; d_vec = 0; - if (s_vec) delete [] s_vec; s_vec = 0; -} - -void DbfColContainer::AllocVecData() -{ - if (IsVecDataAlloc()) return; - if (GetType() == GdaConst::long64_type || - GetType() == GdaConst::date_type) { - l_vec = new wxInt64[size](); - } else if (GetType() == GdaConst::double_type) { - d_vec = new double[size](); - } else if (GetType() == GdaConst::string_type) { - s_vec = new wxString[size]; - } -} - -bool DbfColContainer::IsVecDataAlloc() -{ - if (GetType() == GdaConst::long64_type) { - return l_vec != 0; - } else if (GetType() == GdaConst::date_type) { - return l_vec != 0; - } else if (GetType() == GdaConst::double_type) { - return d_vec != 0; - } else if (GetType() == GdaConst::string_type) { - return s_vec != 0; - } - return false; -} - - -wxString DbfColContainer::GetName() -{ - return info.name; -} - -wxString DbfColContainer::GetDbfColName() -{ - return info.name; -} - -GdaConst::FieldType DbfColContainer::GetType() -{ - return info.type; -} - -int DbfColContainer::GetFieldLen() -{ - return info.field_len; -} - -int DbfColContainer::GetDecimals() -{ - return info.decimals; -} - -void DbfColContainer::GetMinMaxVals(double& min_v, double& max_v) -{ - UpdateMinMaxVals(); - min_v = min_val; - max_v = max_val; -} - -void DbfColContainer::UpdateMinMaxVals() -{ - if (GetType() != GdaConst::double_type && - GetType() != GdaConst::long64_type) return; - if (stale_min_max_val) { - std::vector vals; - GetVec(vals); - min_val = vals[0]; - max_val = vals[0]; - for (int i=0; i max_val) { - max_val = vals[i]; - } - } - stale_min_max_val = false; - } -} - -// Change Properties will convert data to vector format if length or -// decimals are changed. -bool DbfColContainer::ChangeProperties(int new_len, int new_dec) -{ - if (!IsRawDataAlloc() && !IsVecDataAlloc()) { - // this violates the assumption that at least either raw_data - // exists or a valid vector exists. This should never happen - return false; - } - - if (GetType() == GdaConst::string_type) { - if (new_len < GdaConst::min_dbf_string_len || - new_len > GdaConst::max_dbf_string_len) { - return false; - } - if (IsRawDataAlloc() && !IsVecDataAlloc()) { - AllocVecData(); - raw_data_to_vec(s_vec); - } - // shorten all strings as needed. - if (new_len < info.field_len) { - for (int i=0; i GdaConst::max_dbf_long_len) { - return false; - } - if (IsRawDataAlloc() && !IsVecDataAlloc()) { - AllocVecData(); - raw_data_to_vec(l_vec); - } - // limit all vector values to acceptable range - //wxInt64 max_val = DbfFileUtils::GetMaxInt(new_len); - //wxInt64 min_val = DbfFileUtils::GetMinInt(new_len); - //for (int i=0; i l_vec[i]) { - // l_vec[i] = min_val; - // } - //} - } else if (GetType() == GdaConst::double_type) { - if (new_len < GdaConst::min_dbf_double_len || - new_len > GdaConst::max_dbf_double_len || - new_dec < GdaConst::min_dbf_double_decimals || - new_dec > GdaConst::max_dbf_double_decimals) { - return false; - } - int suggest_len; - int suggest_dec; - DbfFileUtils::SuggestDoubleParams(new_len, new_dec, - &suggest_len, &suggest_dec); - if (new_len != suggest_len || new_dec != suggest_dec) { - return false; - } - if (IsRawDataAlloc() && !IsVecDataAlloc()) { - AllocVecData(); - raw_data_to_vec(d_vec); - } - // limit all vectors to acceptable range - //double max_val = DbfFileUtils::GetMaxDouble(new_len, new_dec); - //double min_val = DbfFileUtils::GetMinDouble(new_len, new_dec); - //for (int i=0, iend=size; i != iend; i++) { - // if (max_val < d_vec[i]) { - // d_vec[i] = max_val; - // } else if (min_val > d_vec[i]) { - // d_vec[i] = min_val; - // } - //} - info.decimals = new_dec; - } else { // GdaConst::date_type - // can only change field name for date_type - if (new_len != GdaConst::max_dbf_date_len) return false; - } - - if (IsRawDataAlloc()) FreeRawData(); - info.field_len = new_len; - return true; -} - - -bool DbfColContainer::ChangeName(const wxString& new_name) -{ - if (!DbfFileUtils::isValidFieldName(new_name)) return false; - info.name = new_name; - return true; -} - -bool DbfColContainer::sprintf_period_for_decimal() -{ - char buf[10]; - sprintf(buf, "%#3.1f", 2.5); - //LOG_MSG(wxString::Format("DbfColContainer::sprintf_period_for_decimal()" - // " = %s", buf[1] == '.' ? "true" : "false")); - return buf[1] == '.'; -} - -// Allow for filling of double from long64 field -void DbfColContainer::GetVec(std::vector& vec) -{ - if (GetType() != GdaConst::double_type && - GetType() != GdaConst::long64_type) return; - if (!IsVecDataAlloc() && IsRawDataAlloc()) CopyRawDataToVector(); - if (vec.size() != size) vec.resize(size); - if (GetType() == GdaConst::double_type) { - if (IsVecDataAlloc()) { - for (int i=0; i t(size); - raw_data_to_vec(t); - for (int i=0; i& vec) -{ - if (GetType() != GdaConst::double_type && - GetType() != GdaConst::long64_type && - GetType() != GdaConst::date_type ) return; - if (!IsVecDataAlloc() && IsRawDataAlloc()) CopyRawDataToVector(); - if (vec.size() != size) vec.resize(size); - if (GetType() == GdaConst::long64_type || - GetType() == GdaConst::date_type ) { - if (IsVecDataAlloc()) { - for (int i=0; i t(size); - raw_data_to_vec(t); - for (int i=0; i& vec) -{ - if (vec.size() != size) vec.resize(size); - if (IsVecDataAlloc()) { - for (int i=0; i& vec) -{ - if (vec.size() != size) return; - if (GetType() != GdaConst::long64_type && - GetType() != GdaConst::double_type) return; - if (!IsVecDataAlloc()) AllocVecData(); - if (IsRawDataAlloc()) FreeRawData(); - - CheckUndefined(); - for (int i=0; i(vec[i]); - } - undefined_initialized = true; - - if (GetType() == GdaConst::long64_type) { - for (int i=0; i& vec) -{ - if (vec.size() != size) return; - if (GetType() != GdaConst::long64_type && - GetType() != GdaConst::double_type) return; - if (!IsVecDataAlloc()) AllocVecData(); - if (IsRawDataAlloc()) FreeRawData(); - - CheckUndefined(); - for (int i=0; i& vec) -{ - if (vec.size() != size) return; - if (!IsVecDataAlloc()) AllocVecData(); - if (IsRawDataAlloc()) FreeRawData(); - - for (int i=0; i& undef_vec) -{ - if (undefined.size() != size) undefined.resize(size); - CheckUndefined(); - for (int i=0; i& undef_vec) -{ - if (undef_vec.size() != size) undef_vec.resize(size); - if (!undefined_initialized) CheckUndefined(); - for (int i=0; i(x)); - buf += inc; - } - } else { - for (int i=0; i(d_vec[i]); - } - } - } else if (GetType() == GdaConst::long64_type) { - if (IsRawDataAlloc()) { - char* buf=raw_data; - for (int i=0; i& vec) -{ - if (vec.size() != size) { - vec.resize(size); - std::fill(vec.begin(), vec.end(), 0); - } - if (GetType() == GdaConst::unknown_type || - GetType() == GdaConst::placeholder_type) return; - CheckUndefined(); - const int inc = info.field_len+1; - char* buf=raw_data; - for (int i=0; i(vec[i])); - buf += inc; - } -} - -void DbfColContainer::raw_data_to_vec(double* vec) -{ - if (!vec) return; - if (GetType() == GdaConst::unknown_type || - GetType() == GdaConst::placeholder_type) return; - CheckUndefined(); - const int inc = info.field_len+1; - char* buf=raw_data; - for (int i=0; i(vec[i])); - buf += inc; - } -} - -void DbfColContainer::raw_data_to_vec(std::vector& vec) -{ - if (vec.size() != size) { - vec.resize(size); - std::fill(vec.begin(), vec.end(), 0); - } - if (GetType() == GdaConst::unknown_type || - GetType() == GdaConst::placeholder_type) return; - CheckUndefined(); - const int inc = info.field_len+1; - char* buf=raw_data; - for (int i=0; i& vec) -{ - if (vec.size() != size) vec.resize(size); - if (GetType() == GdaConst::unknown_type || - GetType() == GdaConst::placeholder_type) return; - CheckUndefined(); - const int inc = info.field_len+1; - char* buf=raw_data; - for (int i=0; i(d_vec[i])) { - // the number is either NaN (not a number) or +/- infinity - undefined[i] = true; - } - if (undefined[i]) { - for (int j=0; j((const char*)s_vec[i].mb_str()))); - for (int j=0; j. - */ - -#ifndef __GEODA_CENTER_DBF_COL_CONTAINER_H__ -#define __GEODA_CENTER_DBF_COL_CONTAINER_H__ - -#include -#include -#include -#include -#include "TableStateObserver.h" -#include "../GdaConst.h" -#include "../HighlightStateObserver.h" -#include "../DbfFile.h" - -/** - DbfColContainer notes: when a DBF file is read from disk, we initially - just read its data into the raw_data array in raw form to minimize table - loading time. The corrseponding data vector d_vec, l_vec or s_vec are - not filled. When a new column is created, only d_vec, l_vec, or s_vec are - created and raw_data is left as empty. When data is written out to disk, - the data in d_vec, l_vec, s_vec is converted into raw_data unless only - raw_data only exists. - - So, let's allow both raw_data and the vector data to potentially exist - together. When a cell is written, it is written to both. When - an entire column is written, it is only written into to the vector, and - raw_data is deleted. When an entire column is read in (for example by - Scatter Plot), then we must first create the vector if it doesn't already - exist. - - So, in summary, whenever both raw_data and corresponding vector exist, - single cell updates are written to both, but entire column updates - only go to the vector and the raw_data is deleted. When data is - written to disk, the raw_data is created once again. At any given time - it is therefore possible to have just the raw_data, just the vector, or - both raw_data and vector. When providing values to wxGrid, we will - always pull the value from vector first, and then raw_data. In either - case, we must check the undefined flag. When writing a column of data, - we will likely also pass in an optional boolean vector of undefined flags. - - For d_vec and l_vec, we might want the potential to specify empty or - undefined values. The IEEE double standard gives us several special - values for this purpose, but for integers, there are no special reserved - values. We must therefore provide some sort of integer status flags. - Perhaps for both we can just specify defined or undefined? Then it - would be sufficient to maintain a common bit-vector called to flag - empty values (either because no value was provided, or because the value - was undefined). - */ -class DbfColContainer -{ -public: - DbfColContainer(); - virtual ~DbfColContainer(); - bool Init(int size, - const GdaConst::FieldInfo& field_info, - bool alloc_raw_data, - bool alloc_vector_data, - bool mark_all_defined); - - int size; // number of rows - - void AllocRawData(); - bool IsRawDataAlloc(); - void FreeRawData(); - - void AllocVecData(); - bool IsVecDataAlloc(); - void FreeVecData(); - - // raw character data directly from the DBF file but with null-terminated - // strings. If raw_data is valid, then the pointer is non-null, - // otherwise it is set to zero. - char* raw_data; - double* d_vec; - wxInt64* l_vec; - wxString* s_vec; - // for use by d_vec and l_vec to denote either empty or undefined values. - std::vector undefined; - // when reading in a large DBF file, we do not take the time to - // check that all numbers are valid. When a data column is read - // for the first time, we will take the time to properly set the - // undefined vector. If the vector has not been initialized, then - // TableInterface::GetValue should not rely the values in the - // undefined vector. - bool undefined_initialized; - - wxString GetName(); - wxString GetDbfColName(); - GdaConst::FieldType GetType(); - int GetFieldLen(); - int GetDecimals(); - - void GetMinMaxVals(double& min_val, double& max_val); - - // Function to change properties. - bool ChangeProperties(int new_len, int new_dec=0); - bool ChangeName(const wxString& new_name); - - void GetVec(std::vector& vec); - void GetVec(std::vector& vec); - void GetVec(std::vector& vec); - - // note: the following two functions only have an - // effect on numeric fields currently. - void SetFromVec(const std::vector& vec); - void SetFromVec(const std::vector& vec); - void SetFromVec(const std::vector& vec); - void CheckUndefined(); - void SetUndefined(const std::vector& undef_vec); - void GetUndefined(std::vector& undef_vec); - - void CopyRawDataToVector(); - void CopyVectorToRawData(); - - void UpdateMinMaxVals(); - bool stale_min_max_val; - -private: - GdaConst::FieldInfo info; - - double min_val; - double max_val; - - void raw_data_to_vec(std::vector& vec); - void raw_data_to_vec(double* vec); - void raw_data_to_vec(std::vector& vec); - void raw_data_to_vec(wxInt64* vec); - void raw_data_to_vec(std::vector& vec); - void raw_data_to_vec(wxString* vec); - - void d_vec_to_raw_data(); - void l_vec_to_raw_data(); - void s_vec_to_raw_data(); - -public: - static bool sprintf_period_for_decimal(); -}; - - -#endif diff --git a/DataViewer/MergeTableDlg.cpp b/DataViewer/MergeTableDlg.cpp index 1edb671d3..807220109 100644 --- a/DataViewer/MergeTableDlg.cpp +++ b/DataViewer/MergeTableDlg.cpp @@ -28,48 +28,49 @@ #include #include "MergeTableDlg.h" #include "DataSource.h" -#include "DbfColContainer.h" #include "TableBase.h" #include "TableInterface.h" #include "../FramesManagerObserver.h" #include "../FramesManager.h" -#include "../DbfFile.h" #include "../ShapeOperations/OGRLayerProxy.h" #include "../ShapeOperations/OGRDataAdapter.h" #include "../DialogTools/ConnectDatasourceDlg.h" #include "../DialogTools/FieldNameCorrectionDlg.h" +#include "../DialogTools/ExportDataDlg.h" #include "../logger.h" +#include "../GeneralWxUtils.h" +#include "../Project.h" BEGIN_EVENT_TABLE( MergeTableDlg, wxDialog ) + EVT_RADIOBUTTON( XRCID("ID_KEY_VAL_RB"), MergeTableDlg::OnKeyValRB ) EVT_RADIOBUTTON( XRCID("ID_REC_ORDER_RB"), MergeTableDlg::OnRecOrderRB ) EVT_BUTTON( XRCID("ID_OPEN_BUTTON"), MergeTableDlg::OnOpenClick ) EVT_BUTTON( XRCID("ID_INC_ALL_BUTTON"), MergeTableDlg::OnIncAllClick ) EVT_BUTTON( XRCID("ID_INC_ONE_BUTTON"), MergeTableDlg::OnIncOneClick ) - EVT_LISTBOX_DCLICK( XRCID("ID_INCLUDE_LIST"), - MergeTableDlg::OnIncListDClick ) + EVT_LISTBOX_DCLICK( XRCID("ID_INCLUDE_LIST"), MergeTableDlg::OnIncListDClick ) EVT_BUTTON( XRCID("ID_EXCL_ALL_BUTTON"), MergeTableDlg::OnExclAllClick ) EVT_BUTTON( XRCID("ID_EXCL_ONE_BUTTON"), MergeTableDlg::OnExclOneClick ) - EVT_LISTBOX_DCLICK( XRCID("ID_EXCLUDE_LIST"), - MergeTableDlg::OnExclListDClick ) + EVT_LISTBOX_DCLICK( XRCID("ID_EXCLUDE_LIST"), MergeTableDlg::OnExclListDClick ) EVT_CHOICE( XRCID("ID_CURRENT_KEY_CHOICE"), MergeTableDlg::OnKeyChoice ) EVT_CHOICE( XRCID("ID_IMPORT_KEY_CHOICE"), MergeTableDlg::OnKeyChoice ) - EVT_BUTTON( XRCID("wxID_OK"), MergeTableDlg::OnMergeClick ) + EVT_BUTTON( XRCID("wxID_MERGE"), MergeTableDlg::OnMergeClick ) EVT_BUTTON( XRCID("wxID_CLOSE"), MergeTableDlg::OnCloseClick ) EVT_CLOSE( MergeTableDlg::OnClose ) END_EVENT_TABLE() using namespace std; -MergeTableDlg::MergeTableDlg(wxWindow* parent, - TableInterface* _table_int, - FramesManager* frames_manager_, - const wxPoint& pos) -: table_int(_table_int), connect_dlg(NULL), frames_manager(frames_manager_) +MergeTableDlg::MergeTableDlg(wxWindow* parent, Project* _project_s, const wxPoint& pos) +: merge_datasource_proxy(NULL), project_s(_project_s) { wxLogMessage("Open MergeTableDlg."); SetParent(parent); + //table_int->FillColIdMap(col_id_map); + table_int = project_s->GetTableInt(), + frames_manager = project_s->GetFramesManager(), + CreateControls(); Init(); wxString nm; @@ -82,9 +83,12 @@ MergeTableDlg::MergeTableDlg(wxWindow* parent, MergeTableDlg::~MergeTableDlg() { - //delete merge_datasource_proxy; - //merge_datasource_proxy = NULL; - frames_manager->removeObserver(this); + if (merge_datasource_proxy) { + delete merge_datasource_proxy; + merge_datasource_proxy = NULL; + } + + frames_manager->removeObserver(this); } void MergeTableDlg::update(FramesManager* o) @@ -94,24 +98,64 @@ void MergeTableDlg::update(FramesManager* o) void MergeTableDlg::CreateControls() { wxXmlResource::Get()->LoadDialog(this, GetParent(), "ID_MERGE_TABLE_DLG"); - m_input_file_name = wxDynamicCast(FindWindow(XRCID("ID_INPUT_FILE_TEXT")), - wxTextCtrl); - m_key_val_rb = wxDynamicCast(FindWindow(XRCID("ID_KEY_VAL_RB")), - wxRadioButton); - m_rec_order_rb = wxDynamicCast(FindWindow(XRCID("ID_REC_ORDER_RB")), - wxRadioButton); - m_current_key = wxDynamicCast(FindWindow(XRCID("ID_CURRENT_KEY_CHOICE")), - wxChoice); - m_import_key = wxDynamicCast(FindWindow(XRCID("ID_IMPORT_KEY_CHOICE")), - wxChoice); - m_exclude_list = wxDynamicCast(FindWindow(XRCID("ID_EXCLUDE_LIST")), - wxListBox); - m_include_list = wxDynamicCast(FindWindow(XRCID("ID_INCLUDE_LIST")), - wxListBox); + m_input_file_name = wxDynamicCast(FindWindow(XRCID("ID_INPUT_FILE_TEXT")), wxTextCtrl); + m_key_val_rb = wxDynamicCast(FindWindow(XRCID("ID_KEY_VAL_RB")), wxRadioButton); + m_rec_order_rb = wxDynamicCast(FindWindow(XRCID("ID_REC_ORDER_RB")), wxRadioButton); + m_current_key = wxDynamicCast(FindWindow(XRCID("ID_CURRENT_KEY_CHOICE")), wxChoice); + m_import_key = wxDynamicCast(FindWindow(XRCID("ID_IMPORT_KEY_CHOICE")), wxChoice); + m_exclude_list = wxDynamicCast(FindWindow(XRCID("ID_EXCLUDE_LIST")), wxListBox); + m_include_list = wxDynamicCast(FindWindow(XRCID("ID_INCLUDE_LIST")), wxListBox); + m_left_join = wxDynamicCast(FindWindow(XRCID("ID_MERGE_LEFT_JOIN")), wxRadioButton); + m_outer_join = wxDynamicCast(FindWindow(XRCID("ID_MERGE_OUTER_JOIN")), wxRadioButton); + m_overwrite_field = wxDynamicCast(FindWindow(XRCID("ID_MERGE_OVERWRITE_SAME_FIELD")), wxCheckBox); + + m_left_join->Bind(wxEVT_RADIOBUTTON, &MergeTableDlg::OnLeftJoinClick, this); + m_outer_join->Bind(wxEVT_RADIOBUTTON, &MergeTableDlg::OnOuterJoinClick, this); + + m_left_join->Disable(); + m_outer_join->Disable(); + m_key_val_rb->Disable(); + m_rec_order_rb->Disable(); + m_current_key->Disable(); + m_import_key->Disable(); + m_exclude_list->Disable(); + m_include_list->Disable(); + m_overwrite_field->Disable(); +} + +void MergeTableDlg::OnLeftJoinClick(wxCommandEvent& ev) +{ + m_overwrite_field->Disable(); + m_overwrite_field->SetValue(false); + m_rec_order_rb->SetValue(false); + m_key_val_rb->SetValue(true); +} + +void MergeTableDlg::OnOuterJoinClick(wxCommandEvent& ev) +{ + m_overwrite_field->Enable(); + m_overwrite_field->SetValue(true); + m_rec_order_rb->SetValue(true); + m_key_val_rb->SetValue(false); } void MergeTableDlg::Init() { + m_input_file_name->SetValue(wxEmptyString); + m_import_key->Clear(); + m_current_key->Clear(); + m_include_list->Clear(); + m_exclude_list->Clear(); + + m_left_join->Disable(); + m_outer_join->Disable(); + m_key_val_rb->Disable(); + m_rec_order_rb->Disable(); + m_current_key->Disable(); + m_import_key->Disable(); + m_exclude_list->Disable(); + m_include_list->Disable(); + vector col_names; table_fnames.clear(); // get the field names from table interface @@ -158,22 +202,9 @@ void MergeTableDlg::OnOpenClick( wxCommandEvent& ev ) wxSize sz = GetSize(); pos.x += sz.GetWidth(); - int dialog_type = 1; - wxWindowList::compatibility_iterator node = wxTopLevelWindows.GetFirst(); - while (node) { - wxWindow* win = node->GetData(); - if (ConnectDatasourceDlg* w = dynamic_cast(win)) { - if (w->GetType() == dialog_type) { - w->Show(true); - w->Maximize(false); - w->Raise(); - return; - } - } - node = node->GetNext(); - } - - ConnectDatasourceDlg connect_dlg(this, pos, wxDefaultSize, showCsvConfigure, false, dialog_type); + int dialog_type = 1; // no gda is allowed + bool showRecentPanel = false; + ConnectDatasourceDlg connect_dlg(this, pos, wxDefaultSize, showCsvConfigure, showRecentPanel, dialog_type); if (connect_dlg.ShowModal() != wxID_OK) { return; @@ -185,10 +216,14 @@ void MergeTableDlg::OnOpenClick( wxCommandEvent& ev ) wxString datasource_name = datasource->GetOGRConnectStr(); GdaConst::DataSourceType ds_type = datasource->GetType(); - wxLogMessage(_("ds:") + datasource_name + _(" layer") + layer_name); + wxLogMessage("ds:" + datasource_name + " layer: " + layer_name); + if (merge_datasource_proxy != NULL) { + delete merge_datasource_proxy; + merge_datasource_proxy = NULL; + } merge_datasource_proxy = new OGRDatasourceProxy(datasource_name, ds_type, true); - merge_layer_proxy = merge_datasource_proxy->GetLayerProxy(layer_name.ToStdString()); + merge_layer_proxy = merge_datasource_proxy->GetLayerProxy(layer_name); merge_layer_proxy->ReadData(); m_input_file_name->SetValue(layer_name); @@ -196,6 +231,12 @@ void MergeTableDlg::OnOpenClick( wxCommandEvent& ev ) map dbf_fn_freq; dups.clear(); dedup_to_id.clear(); + + //m_input_file_name->SetValue(wxEmptyString); + m_import_key->Clear(); + m_include_list->Clear(); + m_exclude_list->Clear(); + for (int i=0, iend=merge_layer_proxy->GetNumFields(); iGetFieldType(i); wxString name = merge_layer_proxy->GetFieldName(i); @@ -215,6 +256,15 @@ void MergeTableDlg::OnOpenClick( wxCommandEvent& ev ) m_exclude_list->Append(dedup_name); } + m_left_join->Enable(); + m_outer_join->Enable(); + m_key_val_rb->Enable(); + m_rec_order_rb->Enable(); + m_current_key->Enable(); + m_import_key->Enable(); + m_exclude_list->Enable(); + m_include_list->Enable(); + }catch(GdaException& e) { wxMessageDialog dlg (this, e.what(), _("Error"), wxOK | wxICON_ERROR); dlg.ShowModal(); @@ -276,38 +326,43 @@ void MergeTableDlg::OnExclListDClick( wxCommandEvent& ev) OnIncOneClick(ev); } - -void MergeTableDlg::CheckKeys(wxString key_name, vector& key_vec, +bool MergeTableDlg::CheckKeys(wxString key_name, vector& key_vec, map& key_map) { - map::iterator it; - map dupKeys; + std::map > dup_dict; // value:[] for (int i=0, iend=key_vec.size(); i ids; + dup_dict[tmpK] = ids; } + dup_dict[tmpK].push_back(i); } - if (key_vec.size() != key_map.size()) { - wxString msg = wxString::Format(_("Your table cannot be merged because the key field %s is not unique. \nIt contains undefined or duplicate values with these IDs:\n"), key_name); - int count = 0; - for (it=dupKeys.begin(); it!=dupKeys.end();it++) { - msg << it->first << "\n"; - count++; - if (count > 5) - break; + if (key_vec.size() != dup_dict.size()) { + wxString msg = wxString::Format(_("Your table cannot be merged because the key field \"%s\" is not unique. \nIt contains undefined or duplicate values.\n\nDetails:"), key_name); + + wxString details = "value, row\n"; + std::map >::iterator it; + for (it=dup_dict.begin(); it!=dup_dict.end(); it++) { + wxString val = it->first; + std::vector& ids = it->second; + if (ids.size() > 1) { + for (int i=0; i 5) - msg << "..."; - throw GdaException(msg.mb_str()); + + ScrolledDetailMsgDialog *dlg = new ScrolledDetailMsgDialog(_("Warning"), msg, details); + dlg->Show(true); + return false; } + return true; } vector MergeTableDlg:: @@ -354,7 +409,303 @@ GetSelectedFieldNames(map& merged_fnames_dict) void MergeTableDlg::OnMergeClick( wxCommandEvent& ev ) { wxLogMessage("In MergeTableDlg::OnMergeClick()"); + if (m_left_join->GetValue()) { + LeftJoinMerge(); + } else { + OuterJoinMerge(); + } + ev.Skip(); +} + +OGRColumn* MergeTableDlg::CreateNewOGRColumn(int new_rows, TableInterface* table_int, vector& undefs, int idx, int t) +{ + wxString f_name = table_int->GetColName(idx, t); + int f_length = table_int->GetColLength(idx, t); + int f_decimal = table_int->GetColDecimals(idx, t); + GdaConst::FieldType f_type = table_int->GetColType(idx, t); + OGRColumn* _col; + if (f_type == GdaConst::long64_type) { + _col = new OGRColumnInteger(f_name, f_length, f_decimal, new_rows); + _col->SetUndefinedMarkers(undefs); + vector vals; + table_int->GetColData(idx, t, vals); + for(int i=0; iSetValueAt(i, vals[i]); + } else if (f_type == GdaConst::double_type) { + _col = new OGRColumnDouble(f_name, f_length, f_decimal, new_rows); + _col->SetUndefinedMarkers(undefs); + vector vals; + table_int->GetColData(idx, t, vals); + for(int i=0; iSetValueAt(i, vals[i]); + } else { + _col = new OGRColumnString(f_name, f_length, f_decimal, new_rows); + _col->SetUndefinedMarkers(undefs); + vector vals; + table_int->GetColData(idx, t, vals); + for(int i=0; iSetValueAt(i, vals[i]); + } + return _col; +} + +OGRColumn* MergeTableDlg::CreateNewOGRColumn(int new_rows, OGRLayerProxy* layer_proxy, vector& undefs, wxString f_name, map& idx2_dict) +{ + int col_idx = layer_proxy->GetFieldPos(f_name); + GdaConst::FieldType f_type = layer_proxy->GetFieldType(col_idx); + int f_length = layer_proxy->GetFieldLength(col_idx); + int f_decimal = layer_proxy->GetFieldDecimals(col_idx); + int n_rows = layer_proxy->n_rows; + + OGRColumn* _col; + if (f_type == GdaConst::long64_type) { + _col = new OGRColumnInteger(f_name, f_length, f_decimal, new_rows); + _col->SetUndefinedMarkers(undefs); + for (int i=0; iGetFeatureAt(i); + wxInt64 val = feat->GetFieldAsInteger64(col_idx); + _col->SetValueAt(idx2_dict[i], val); + } + } else if (f_type == GdaConst::double_type) { + _col = new OGRColumnDouble(f_name, f_length, f_decimal, new_rows); + _col->SetUndefinedMarkers(undefs); + for (int i=0; iGetFeatureAt(i); + double val = feat->GetFieldAsDouble(col_idx); + _col->SetValueAt(idx2_dict[i], val); + } + } else { + _col = new OGRColumnString(f_name, f_length, f_decimal, new_rows); + _col->SetUndefinedMarkers(undefs); + for (int i=0; iGetValueAt(i, col_idx); + _col->SetValueAt(idx2_dict[i], val); + } + } + return _col; +} + +void MergeTableDlg::UpdateOGRColumn(OGRColumn* _col, OGRLayerProxy* layer_proxy, wxString f_name, map& idx2_dict) +{ + int col_idx = layer_proxy->GetFieldPos(f_name); + GdaConst::FieldType f_type = layer_proxy->GetFieldType(col_idx); + int f_length = layer_proxy->GetFieldLength(col_idx); + int f_decimal = layer_proxy->GetFieldDecimals(col_idx); + int n_rows = layer_proxy->n_rows; + + if (f_type == GdaConst::long64_type) { + for (int i=0; iGetFeatureAt(i); + wxInt64 val = feat->GetFieldAsInteger64(col_idx); + _col->SetValueAt(idx2_dict[i], val); + } + } else if (f_type == GdaConst::double_type) { + for (int i=0; iGetFeatureAt(i); + double val = feat->GetFieldAsDouble(col_idx); + _col->SetValueAt(idx2_dict[i], val); + } + } else { + for (int i=0; iGetValueAt(i, col_idx); + _col->SetValueAt(idx2_dict[i], val); + } + } +} + +void MergeTableDlg::OuterJoinMerge() +{ + try { + wxString error_msg; + + // get selected field names from merging table + vector merged_field_names; + for (int i=0, iend=m_include_list->GetCount(); iGetString(i); + merged_field_names.push_back(inc_n); + } + if (merged_field_names.empty()) + return; + + int n_rows = table_int->GetNumberRows(); + int n_merge_field = merged_field_names.size(); + + map rowid_map; + + vector key1_vec; + map key1_map; + vector key2_vec; + + if (m_key_val_rb->GetValue()==1) { // check merge by key/record order + // get and check keys from original table + int key1_id = m_current_key->GetSelection(); + wxString key1_name = m_current_key->GetString(key1_id); + int col1_id = table_int->FindColId(key1_name); + if (table_int->IsColTimeVariant(col1_id)) { + error_msg = wxString::Format(_("Chosen key field '%s' s a time variant. Please choose a non-time variant field as key."), key1_name); + throw GdaException(error_msg.mb_str()); + } + + vector key1_l_vec; + + if (table_int->GetColType(col1_id, 0) == GdaConst::string_type) { + table_int->GetColData(col1_id, 0, key1_vec); + }else if (table_int->GetColType(col1_id,0)==GdaConst::long64_type){ + table_int->GetColData(col1_id, 0, key1_l_vec); + } + + if (key1_vec.empty()) { // convert everything (key) to wxString + for( int i=0; i< key1_l_vec.size(); i++){ + wxString tmp; + tmp << key1_l_vec[i]; + key1_vec.push_back(tmp); + } + } + if (CheckKeys(key1_name, key1_vec, key1_map) == false) + return; + + // get and check keys from import table + int key2_id = m_import_key->GetSelection(); + wxString key2_name = m_import_key->GetString(key2_id); + int col2_id = merge_layer_proxy->GetFieldPos(key2_name); + int n_merge_rows = merge_layer_proxy->GetNumRecords(); + map key2_map; + for (int i=0; i < n_merge_rows; i++) { + wxString tmp; + tmp << merge_layer_proxy->GetValueAt(i, col2_id); + key2_vec.push_back(tmp); + } + if (CheckKeys(key2_name, key2_vec, key2_map) == false) + return; + + } else if (m_rec_order_rb->GetValue() == 1) { // merge by order sequence, just append + + for (int i=0; iGetNumRecords(); + for (int i=0; i < n_merge_rows; i++) { + wxString tmp; + tmp << i; + key2_vec.push_back(tmp); + } + } + + std::vector geoms; + OGRSpatialReference* spatial_ref = project_s->GetSpatialReference(); + Shapefile::ShapeType shape_type = project_s->GetGdaGeometries(geoms); + + std::vector in_geoms; + OGRSpatialReference* in_spatial_ref = merge_layer_proxy->GetSpatialReference(); + + OGRCoordinateTransformation *poCT = NULL; + if (spatial_ref !=NULL && in_spatial_ref != NULL) { + if (!spatial_ref->IsSame(in_spatial_ref) ) { + // convert geometry with original projection if needed + poCT = OGRCreateCoordinateTransformation(in_spatial_ref, spatial_ref); + merge_layer_proxy->ApplyProjection(poCT); + } + } + Shapefile::ShapeType in_shape_type=merge_layer_proxy->GetGdaGeometries(in_geoms); + if (shape_type != in_shape_type) { + error_msg = _("Merge error: Geometric type of selected datasource has to be the same with current datasource."); + throw GdaException(error_msg.mb_str()); + } + + std::vector new_geoms = geoms; + + vector new_key_vec = key1_vec; + map idx2_dict; + int idx2 = key1_vec.size(); + for (int i=0; i undefs(new_rows, true); + + map new_fields_dict; + vector new_fields; + // all columns from table + int time_steps = table_int->GetTimeSteps(); + for ( int id=0; id < table_int->GetNumberCols(); id++ ) { + OGRColumn* col; + if (table_int->IsColTimeVariant(id)) { + for ( int t=0; t < time_steps; t++ ) { + col = CreateNewOGRColumn(new_rows, table_int, undefs, id, t); + new_fields_dict[col->GetName()] = col; + new_fields.push_back(col->GetName()); + } + } else { + col = CreateNewOGRColumn(new_rows, table_int, undefs, id); + new_fields_dict[col->GetName()] = col; + new_fields.push_back(col->GetName()); + } + } + // all columns from datasource + int in_cols = merged_field_names.size(); + bool overwrite_field = m_overwrite_field->IsChecked(); + + for (int i=0; iRename(fname); + new_fields_dict[fname] = col; + new_fields.push_back(fname); + } + } else { + // new field + OGRColumn* col = CreateNewOGRColumn(new_rows, merge_layer_proxy, undefs, fname, idx2_dict); + new_fields_dict[fname] = col; + new_fields.push_back(fname); + } + } + + for (int i=0; iAddOGRColumn(new_fields_dict[new_fields[i]]); + } + + ExportDataDlg export_dlg(this, shape_type, new_geoms, spatial_ref, mem_table); + if (export_dlg.ShowModal() == wxID_OK) { + wxMessageDialog dlg(this, _("File merged into Table successfully."), _("Success"), wxOK); + dlg.ShowModal(); + } + + delete mem_table; + // see ExportDataDlg.cpp line:620 + //for (int i=0; i merged_field_names = - GetSelectedFieldNames(merged_fnames_dict); + vector merged_field_names = GetSelectedFieldNames(merged_fnames_dict); if (merged_field_names.empty()) return; @@ -374,8 +724,7 @@ void MergeTableDlg::OnMergeClick( wxCommandEvent& ev ) int n_merge_field = merged_field_names.size(); map rowid_map; - // check merge by key/record order - if (m_key_val_rb->GetValue()==1) { + if (m_key_val_rb->GetValue()==1) { // check merge by key/record order // get and check keys from original table int key1_id = m_current_key->GetSelection(); wxString key1_name = m_current_key->GetString(key1_id); @@ -402,7 +751,8 @@ void MergeTableDlg::OnMergeClick( wxCommandEvent& ev ) key1_vec.push_back(tmp); } } - CheckKeys(key1_name, key1_vec, key1_map); + if (CheckKeys(key1_name, key1_vec, key1_map) == false) + return; // get and check keys from import table int key2_id = m_import_key->GetSelection(); @@ -414,7 +764,8 @@ void MergeTableDlg::OnMergeClick( wxCommandEvent& ev ) for (int i=0; i < n_merge_rows; i++) { key2_vec.push_back(merge_layer_proxy->GetValueAt(i, col2_id)); } - CheckKeys(key2_name, key2_vec, key2_map); + if (CheckKeys(key2_name, key2_vec, key2_map) == false) + return; // make sure key1 <= key2, and store their mappings int n_matches = 0; @@ -463,8 +814,7 @@ void MergeTableDlg::OnMergeClick( wxCommandEvent& ev ) wxMessageDialog dlg(this, _("File merged into Table successfully."), _("Success"), wxOK ); dlg.ShowModal(); - ev.Skip(); - EndDialog(wxID_OK); + EndDialog(wxID_OK); } void MergeTableDlg::AppendNewField(wxString field_name, @@ -559,26 +909,12 @@ void MergeTableDlg::AppendNewField(wxString field_name, void MergeTableDlg::OnCloseClick( wxCommandEvent& ev ) { wxLogMessage("In MergeTableDlg::OnCloseClick()"); - //ev.Skip(); - int dialog_type = 1; - wxWindowList::compatibility_iterator node = wxTopLevelWindows.GetFirst(); - while (node) { - wxWindow* win = node->GetData(); - if (ConnectDatasourceDlg* w = dynamic_cast(win)) { - if (w->GetType() == dialog_type) { - w->EndDialog(); - w->Close(true); - break; - } - } - node = node->GetNext(); - } - EndDialog(wxID_CLOSE); } void MergeTableDlg::OnClose( wxCloseEvent& ev) { + wxLogMessage("In MergeTableDlg::OnClose()"); Destroy(); } @@ -595,5 +931,5 @@ void MergeTableDlg::UpdateMergeButton() (m_key_val_rb->GetValue()==1 && m_current_key->GetSelection() != wxNOT_FOUND && m_import_key->GetSelection() != wxNOT_FOUND))); - FindWindow(XRCID("wxID_OK"))->Enable(enable); + FindWindow(XRCID("wxID_MERGE"))->Enable(enable); } diff --git a/DataViewer/MergeTableDlg.h b/DataViewer/MergeTableDlg.h index b8d633252..4dea261d7 100644 --- a/DataViewer/MergeTableDlg.h +++ b/DataViewer/MergeTableDlg.h @@ -39,13 +39,15 @@ class ConnectDatasourceDlg; class FramesManager; +class Project; +class ExportDataDlg; +class OGRColumn; class MergeTableDlg: public wxDialog, public FramesManagerObserver { public: MergeTableDlg(wxWindow* parent, - TableInterface* _table_int, - FramesManager* frames_manager, + Project* project_p, const wxPoint& pos = wxDefaultPosition); virtual ~MergeTableDlg(); @@ -68,9 +70,15 @@ class MergeTableDlg: public wxDialog, public FramesManagerObserver void OnKeyChoice( wxCommandEvent& ev ); void OnCloseClick( wxCommandEvent& ev ); void OnClose( wxCloseEvent& ev); + void OnLeftJoinClick( wxCommandEvent& ev ); + void OnOuterJoinClick( wxCommandEvent& ev ); void UpdateMergeButton(); //void RemoveDbfReader(); //void UpdateIncListItems(); + + void LeftJoinMerge(); + void OuterJoinMerge(); + wxTextCtrl* m_input_file_name; wxRadioButton* m_key_val_rb; @@ -79,15 +87,17 @@ class MergeTableDlg: public wxDialog, public FramesManagerObserver wxChoice* m_import_key; wxListBox* m_exclude_list; wxListBox* m_include_list; - - //TableBase* table_base; + wxRadioButton* m_left_join; + wxRadioButton* m_outer_join; + wxCheckBox* m_overwrite_field; + + Project* project_s; TableInterface* table_int; OGRLayerProxy* merge_layer_proxy; OGRDatasourceProxy* merge_datasource_proxy; std::set table_fnames; private: - ConnectDatasourceDlg* connect_dlg; FramesManager* frames_manager; std::map dedup_to_id; @@ -99,16 +109,19 @@ class MergeTableDlg: public wxDialog, public FramesManagerObserver // 0->2, 1->1, 2->0, 3->5, 4->3, 5->4 //std::vector col_id_map; -private: - void CheckKeys(wxString key_name, std::vector& key_vec, + bool CheckKeys(wxString key_name, std::vector& key_vec, std::map& key_map); - vector - GetSelectedFieldNames(map& merged_fnames_dict); + vector GetSelectedFieldNames(map& merged_fnames_dict); void AppendNewField(wxString field_name, wxString real_field_name, int n_rows, std::map& rowid_map); + OGRColumn* CreateNewOGRColumn(int new_rows, TableInterface* table_int, vector& undefs, int idx, int t=0); + + OGRColumn* CreateNewOGRColumn(int new_rows, OGRLayerProxy* layer_proxy, vector& undefs, wxString col_name, map& idx2_dict); + + void UpdateOGRColumn(OGRColumn* _col, OGRLayerProxy* layer_proxy, wxString f_name, map& idx2_dict); DECLARE_EVENT_TABLE() }; diff --git a/DataViewer/OGRColumn.cpp b/DataViewer/OGRColumn.cpp index f301ced7c..e380964e6 100644 --- a/DataViewer/OGRColumn.cpp +++ b/DataViewer/OGRColumn.cpp @@ -18,11 +18,13 @@ */ #include +#include #include #include #include #include #include +#include #include #include #include @@ -36,6 +38,7 @@ #include "VarOrderMapper.h" using namespace std; +namespace bt = boost::posix_time; OGRColumn::OGRColumn(wxString name, int field_length, int decimals, int n_rows) : name(name), length(field_length), decimals(decimals), is_new(true), is_deleted(false), rows(n_rows) @@ -50,12 +53,13 @@ is_new(true), is_deleted(false) rows = ogr_layer->GetNumRecords(); } -OGRColumn::OGRColumn(OGRLayerProxy* _ogr_layer, int idx) +OGRColumn::OGRColumn(OGRLayerProxy* _ogr_layer, int _idx) { // note: idx is only valid when create a OGRColumn. It's value could be // updated when delete columns in OGRLayer. Therefore, return current // column index will always dynamically fetch from GetColIndex() by using // the column name. + idx = _idx; is_new = false; is_deleted = false; ogr_layer = _ogr_layer; @@ -67,8 +71,13 @@ OGRColumn::OGRColumn(OGRLayerProxy* _ogr_layer, int idx) int OGRColumn::GetColIndex() { - if (is_new) return -1; - return ogr_layer->GetFieldPos(name); + if (is_new) + return -1; + + if (name == ogr_layer->GetFieldName(idx)) + return idx; + else + return ogr_layer->GetFieldPos(name); } int OGRColumn::GetLength() @@ -150,6 +159,12 @@ void OGRColumn::UpdateData(const vector &data) } +void OGRColumn::UpdateData(const vector &data) +{ + wxString msg = "Internal error: UpdateData(wxString) not implemented."; + throw GdaException(msg.mb_str()); +} + void OGRColumn::UpdateData(const vector &data, const vector& undef_markers_) { @@ -171,6 +186,13 @@ void OGRColumn::UpdateData(const vector &data, undef_markers = undef_markers_; } +void OGRColumn::UpdateData(const vector &data, + const vector& undef_markers_) +{ + UpdateData(data); + undef_markers = undef_markers_; +} + void OGRColumn::FillData(vector& data) { wxString msg = "Internal error: FillData(double) not implemented."; @@ -189,9 +211,14 @@ void OGRColumn::FillData(vector& data) { wxString msg = "Internal error: FillData(wxString) not implemented."; throw GdaException(msg.mb_str()); - } +void OGRColumn::FillData(vector& data) +{ + wxString msg = "Internal error: FillData(date) not implemented."; + throw GdaException(msg.mb_str()); + +} void OGRColumn::FillData(vector &data, vector& undef_markers_) @@ -214,6 +241,12 @@ void OGRColumn::FillData(vector &data, undef_markers_ = undef_markers; } +void OGRColumn::FillData(vector &data, + vector& undef_markers_) +{ + FillData(data); + undef_markers_ = undef_markers; +} bool OGRColumn::GetCellValue(int row, wxInt64& val) { @@ -242,6 +275,8 @@ void OGRColumn::UpdateNullMarkers(const vector& undef_markers_) undef_markers = undef_markers_; } + + //////////////////////////////////////////////////////////////////////////////// // OGRColumnInteger::OGRColumnInteger(wxString name, int field_length, int decimals, int n_rows) @@ -327,12 +362,12 @@ void OGRColumnInteger::FillData(vector &data) { if (is_new) { for (int i=0; idata[i]->GetFieldAsInteger64(col_idx)); } } @@ -443,6 +478,20 @@ void OGRColumnInteger::SetValueAt(int row_idx, const wxString &value) } } +void OGRColumnInteger::SetValueAt(int row_idx, wxInt64 l_val) +{ + int col_idx = GetColIndex(); + + if (is_new) { + new_data[row_idx] = l_val; + } else { + if (col_idx == -1) + return; + ogr_layer->data[row_idx]->SetField(col_idx, (GIntBig)l_val); + } + undef_markers[row_idx] = false; +} + //////////////////////////////////////////////////////////////////////////////// // OGRColumnDouble::OGRColumnDouble(wxString name, int field_length, @@ -473,7 +522,7 @@ OGRColumnDouble::OGRColumnDouble(OGRLayerProxy* ogr_layer, wxString name, undef_markers.resize(rows); for (int i=0; i& data) if (is_new) { for (int i=0; idata[row_idx]->UnsetField(row_idx); + int col_idx = GetColIndex(); + ogr_layer->data[row_idx]->UnsetField(col_idx); } return; } @@ -662,6 +713,16 @@ void OGRColumnDouble::SetValueAt(int row_idx, const wxString &value) } } +void OGRColumnDouble::SetValueAt(int row_idx, double d_val) +{ + if (is_new) { + new_data[row_idx] = d_val; + } else { + int col_idx = GetColIndex(); + ogr_layer->data[row_idx]->SetField(col_idx, d_val); + } + undef_markers[row_idx] = false; +} //////////////////////////////////////////////////////////////////////////////// // OGRColumnString::OGRColumnString(wxString name, int field_length, @@ -847,6 +908,50 @@ void OGRColumnString::FillData(vector &data) } } +// for date/time +void OGRColumnString::FillData(vector& data) +{ + if (is_new) { + wxString test_s = new_data[0]; + vector date_items; + wxString pattern = Gda::DetectDateFormat(test_s, date_items); + if (pattern.IsEmpty()) { + wxString error_msg = wxString::Format("Fill data error: can't convert '%s' to date/time.", test_s); + throw GdaException(error_msg.mb_str()); + } + wxRegEx regex(pattern); + if (!regex.IsValid()){ + wxString error_msg = wxString::Format("Fill data error: can't convert '%s' to date/time.", test_s); + throw GdaException(error_msg.mb_str()); + } + for (int i=0; idata[0]->GetFieldAsString(col_idx); + vector date_items; + wxString pattern = Gda::DetectDateFormat(test_s, date_items); + + if (pattern.IsEmpty()) { + wxString error_msg = wxString::Format("Fill data error: can't convert '%s' to date/time.", test_s); + throw GdaException(error_msg.mb_str()); + } + + wxRegEx regex(pattern); + if (!regex.IsValid()){ + wxString error_msg = wxString::Format("Fill data error: can't convert '%s' to date/time.", test_s); + throw GdaException(error_msg.mb_str()); + } + + for (int i=0; idata[i]->GetFieldAsString(col_idx); + unsigned long long val = Gda::DateToNumber(s, regex, date_items); + data[i] = val; + } + } +} + // vector -> this column void OGRColumnString::UpdateData(const vector& data) { @@ -963,6 +1068,18 @@ void OGRColumnString::SetValueAt(int row_idx, const wxString &value) //////////////////////////////////////////////////////////////////////////////// // XXX current GeoDa don't support adding new date column // +OGRColumnDate::OGRColumnDate(OGRLayerProxy* ogr_layer, wxString name, int field_length, int decimals) +: OGRColumn(ogr_layer, name, field_length, decimals) +{ + // a new string column + is_new = true; + new_data.resize(rows); + undef_markers.resize(rows); + for (int i=0; i &data) { if (is_new) { - wxString msg = "Internal error: GeoDa doesn't support new date column."; - throw GdaException(msg.mb_str()); + for (int i=0; i &data) } } -void OGRColumnDate::FillData(vector &data) +void OGRColumnDate::FillData(vector &data) { if (is_new) { - wxString msg = "Internal error: GeoDa doesn't support new date column."; - throw GdaException(msg.mb_str()); + for (int i=0; i &data) int minute = 0; int second = 0; int tzflag = 0; + + int col_idx = GetColIndex(); + ogr_layer->data[i]->GetFieldAsDateTime(col_idx, &year, &month, &day,&hour, &minute, &second, &tzflag); + + unsigned long long ldatetime = year * 10000000000 + month * 100000000 + day * 1000000 + hour * 10000 + minute * 100 + second; + data[i] = ldatetime; + } + } +} + +void OGRColumnDate::FillData(vector &data) +{ + int year, month, day, hour, minute, second, tzflag; + if (is_new) { + for (int i=0; i0 && month > 0 && day > 0) { + tmp << wxString::Format("%i-%i-%i", year, month, day); + } + + int hms = new_data[i] % 1000000; + if (hms > 0) { + hour = (new_data[i] % 1000000) / 10000; + minute = (new_data[i] % 10000) / 100; + second = new_data[i] % 100; + if (hour >0 || minute > 0 || second > 0) { + if (!tmp.IsEmpty()) tmp << " "; + tmp << wxString::Format("%i:%i:%i", hour, minute, second); + } + } + data[i] = tmp; + } + } else { + int col_idx = GetColIndex(); + for (int i=0; idata[i]->GetFieldAsDateTime(col_idx, &year, &month, - &day,&hour,&minute, - &second, &tzflag); - data[i] = ogr_layer->data[i]->GetFieldAsString(col_idx); + &day,&hour,&minute, + &second, &tzflag); + wxString tmp; + if (year >0 && month > 0 && day > 0) { + tmp << wxString::Format("%i-%i-%i", year, month, day); + } + if (hour >0 || minute > 0 || second > 0) { + if (!tmp.IsEmpty()) tmp << " "; + tmp << wxString::Format("%i:%i:%i", hour, minute, second); + } + data[i] = tmp; } } } +void OGRColumnDate::UpdateData(const vector &data) +{ + if (is_new) { + for (int i=0; idata[i]->SetField(col_idx, l_year, l_month, l_day, l_hour, l_minute, l_second, 0); // last TZFlag + } + } +} bool OGRColumnDate::GetCellValue(int row, wxInt64& val) { if (undef_markers[row] == true) { @@ -1058,8 +1252,8 @@ bool OGRColumnDate::GetCellValue(int row, wxInt64& val) int second = 0; int tzflag = 0; ogr_layer->data[row]->GetFieldAsDateTime(col_idx, &year, &month, - &day,&hour,&minute, - &second, &tzflag); + &day,&hour,&minute, + &second, &tzflag); val = year * 10000000000 + month * 100000000 + day * 1000000 + hour * 10000 + minute * 100 + second; } else { val = new_data[row]; @@ -1075,9 +1269,9 @@ wxString OGRColumnDate::GetValueAt(int row_idx, int disp_decimals, int month = 0; int day = 0; int hour = 0; - int minute = 0; - int second = 0; - int tzflag = 0; + int minute = -1; + int second = -1; + int tzflag = -1; if (new_data.empty()) { int col_idx = GetColIndex(); @@ -1085,7 +1279,12 @@ wxString OGRColumnDate::GetValueAt(int row_idx, int disp_decimals, &day,&hour,&minute, &second, &tzflag); } else { - //val = new_data[row_idx]; + year = new_data[row_idx] / 10000000000; + month = (new_data[row_idx] % 10000000000) / 100000000; + day = (new_data[row_idx] % 100000000) / 1000000; + hour = (new_data[row_idx] % 1000000) / 10000; + minute = (new_data[row_idx] % 10000) / 100; + second = new_data[row_idx] % 100; } wxString sDateTime; @@ -1094,143 +1293,50 @@ wxString OGRColumnDate::GetValueAt(int row_idx, int disp_decimals, sDateTime << wxString::Format("%i-%i-%i", year, month, day); } - if (hour >0 || minute > 0 || second > 0) { - if (!sDateTime.IsEmpty()) sDateTime << " "; - sDateTime << wxString::Format("%i:%i:%i", hour, minute, second); - } - return sDateTime; } void OGRColumnDate::SetValueAt(int row_idx, const wxString &value) { + int col_idx = GetColIndex(); + if (value.IsEmpty()) { + undef_markers[row_idx] = true; + ogr_layer->data[row_idx]->UnsetField(col_idx); + return; + } + vector date_items; + wxString pattern = Gda::DetectDateFormat(value, date_items); wxRegEx regex; - - wxString date_regex_str = "([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})"; - - wxString _year, _month, _day, _hour, _minute, _second; - - regex.Compile(date_regex_str); - if (regex.Matches(value)) { - //wxString _all = regex.GetMatch(value,0); - _year = regex.GetMatch(value,1); - _month = regex.GetMatch(value,2); - _day = regex.GetMatch(value,3); - } - + regex.Compile(pattern); + unsigned long long val = Gda::DateToNumber(value, regex, date_items); long _l_year =0, _l_month=0, _l_day=0, _l_hour=0, _l_minute=0, _l_second=0; - - _year.ToLong(&_l_year); - _month.ToLong(&_l_month); - _day.ToLong(&_l_day); - - wxInt64 val = _l_year * 10000000000 + _l_month * 100000000 + _l_day * 1000000 + _l_hour * 10000 + _l_minute * 100 + _l_second; - if (is_new) { new_data[row_idx] = val; } else { - int col_idx = GetColIndex(); + _l_year = val / 10000000000; + _l_month = (val % 10000000000) / 100000000; + _l_day = (val % 100000000) / 1000000; + _l_hour = (val % 1000000) / 10000; + _l_minute = (val % 10000) / 100; + _l_second = val % 100; ogr_layer->data[row_idx]->SetField(col_idx, _l_year, _l_month, _l_day, _l_hour, _l_minute, _l_second, 0); // last TZFlag } } //////////////////////////////////////////////////////////////////////////////// // OGRColumnTime - - OGRColumnTime::OGRColumnTime(OGRLayerProxy* ogr_layer, int idx) -:OGRColumn(ogr_layer, idx) +:OGRColumnDate(ogr_layer, idx) { - is_new = false; - - undef_markers.resize(rows); - for (int i=0; idata[i]->IsFieldSet(idx) ) - undef_markers[i] = false; - else - undef_markers[i] = true; - } -} - -OGRColumnTime::~OGRColumnTime() -{ - if (new_data.size() > 0 ) new_data.clear(); -} - -void OGRColumnTime::FillData(vector &data) -{ - if (is_new) { - wxString msg = "Internal error: GeoDa doesn't support new date column."; - throw GdaException(msg.mb_str()); - } else { - int col_idx = GetColIndex(); - for (int i=0; idata[i]->GetFieldAsDateTime(col_idx, &year, &month, &day,&hour, &minute, &second, &tzflag); - - wxInt64 ldatetime = year * 10000000000 + month * 100000000 + day * 1000000 + hour * 10000 + minute * 100 + second; - - data[i] = ldatetime; - } - } } -void OGRColumnTime::FillData(vector &data) +OGRColumnTime::OGRColumnTime(OGRLayerProxy* ogr_layer, wxString name, int field_length, int decimals) +:OGRColumnDate(ogr_layer, name, field_length, decimals) { - if (is_new) { - wxString msg = "Internal error: GeoDa doesn't support new Time column."; - throw GdaException(msg.mb_str()); - } else { - int col_idx = GetColIndex(); - for (int i=0; idata[i]->GetFieldAsDateTime(col_idx, &year, &month, - &day,&hour,&minute, - &second, &tzflag); - data[i] = ogr_layer->data[i]->GetFieldAsString(col_idx); - } - } } -bool OGRColumnTime::GetCellValue(int row, wxInt64& val) +OGRColumnTime::~OGRColumnTime() { - if (undef_markers[row] == true) { - val = 0; - return false; - } - /* - if (new_data.empty()) { - int col_idx = GetColIndex(); - int year = 0; - int month = 0; - int day = 0; - int hour = 0; - int minute = 0; - int second = 0; - int tzflag = 0; - ogr_layer->data[row]->GetFieldAsDateTime(col_idx, &year, &month, - &day,&hour,&minute, - &second, &tzflag); - //val = year * 10000000000 + month * 100000000 + day * 1000000 + hour * 10000 + minute * 100 + second; - } else { - //val = new_data[row]; - } - */ - return true; } wxString OGRColumnTime::GetValueAt(int row_idx, int disp_decimals, @@ -1239,10 +1345,10 @@ wxString OGRColumnTime::GetValueAt(int row_idx, int disp_decimals, int year = 0; int month = 0; int day = 0; - int hour = 0; - int minute = 0; - int second = 0; - int tzflag = 0; + int hour = -1; + int minute = -1; + int second = -1; + int tzflag = -1; if (new_data.empty()) { int col_idx = GetColIndex(); @@ -1250,12 +1356,15 @@ wxString OGRColumnTime::GetValueAt(int row_idx, int disp_decimals, &day,&hour,&minute, &second, &tzflag); } else { - //val = new_data[row_idx]; + hour = (new_data[row_idx] % 1000000) / 10000; + minute = (new_data[row_idx] % 10000) / 100; + second = new_data[row_idx] % 100; } wxString sDateTime; - if (hour >0 || minute > 0 || second > 0) { + if (hour >=0 || minute >= 0 || second >= 0) { + if (!sDateTime.IsEmpty()) sDateTime << " "; sDateTime << wxString::Format("%i:%i:%i", hour, minute, second); } @@ -1264,133 +1373,45 @@ wxString OGRColumnTime::GetValueAt(int row_idx, int disp_decimals, void OGRColumnTime::SetValueAt(int row_idx, const wxString &value) { - wxRegEx regex; - - wxString time_regex_str = "([0-9]{2}):([0-9]{2}):([0-9]{2})"; - - wxString _hour, _minute, _second; - - regex.Compile(time_regex_str); - if (regex.Matches(value)) { - _hour = regex.GetMatch(value,1); - _minute = regex.GetMatch(value,2); - _second = regex.GetMatch(value,3); - + int col_idx = GetColIndex(); + if (value.IsEmpty()) { + undef_markers[row_idx] = true; + ogr_layer->data[row_idx]->UnsetField(col_idx); + return; } - + vector date_items; + wxString pattern = Gda::DetectDateFormat(value, date_items); + wxRegEx regex; + regex.Compile(pattern); + unsigned long long val = Gda::DateToNumber(value, regex, date_items); long _l_year =0, _l_month=0, _l_day=0, _l_hour=0, _l_minute=0, _l_second=0; - - _hour.ToLong(&_l_hour); - _minute.ToLong(&_l_minute); - _second.ToLong(&_l_second); - - wxInt64 val = _l_year * 10000000000 + _l_month * 100000000 + _l_day * 1000000 + _l_hour * 10000 + _l_minute * 100 + _l_second; - if (is_new) { new_data[row_idx] = val; } else { - int col_idx = GetColIndex(); + _l_year = val / 10000000000; + _l_month = (val % 10000000000) / 100000000; + _l_day = (val % 100000000) / 1000000; + _l_hour = (val % 1000000) / 10000; + _l_minute = (val % 10000) / 100; + _l_second = val % 100; ogr_layer->data[row_idx]->SetField(col_idx, _l_year, _l_month, _l_day, _l_hour, _l_minute, _l_second, 0); // last TZFlag } } //////////////////////////////////////////////////////////////////////////////// //OGRColumnDateTime - OGRColumnDateTime::OGRColumnDateTime(OGRLayerProxy* ogr_layer, int idx) -:OGRColumn(ogr_layer, idx) -{ - is_new = false; - - undef_markers.resize(rows); - for (int i=0; idata[i]->IsFieldSet(idx) ) - undef_markers[i] = false; - else - undef_markers[i] = true; - } -} - -OGRColumnDateTime::~OGRColumnDateTime() -{ - if (new_data.size() > 0 ) new_data.clear(); -} - -void OGRColumnDateTime::FillData(vector &data) +:OGRColumnDate(ogr_layer, idx) { - if (is_new) { - wxString msg = "Internal error: GeoDa doesn't support new date column."; - throw GdaException(msg.mb_str()); - } else { - int col_idx = GetColIndex(); - for (int i=0; idata[i]->GetFieldAsDateTime(col_idx, &year, &month, &day,&hour, &minute, &second, &tzflag); - - wxInt64 ldatetime = year * 10000000000 + month * 100000000 + day * 1000000 + hour * 10000 + minute * 100 + second; - - data[i] = ldatetime; - } - } } - -void OGRColumnDateTime::FillData(vector& data) +OGRColumnDateTime::OGRColumnDateTime(OGRLayerProxy* ogr_layer, wxString name, int field_length, int decimals) +:OGRColumnDate(ogr_layer, name, field_length, decimals) { - if (is_new) { - wxString msg = "Internal error: GeoDa doesn't support new date column."; - throw GdaException(msg.mb_str()); - } else { - int col_idx = GetColIndex(); - for (int i=0; idata[i]->GetFieldAsDateTime(col_idx, &year, &month, - &day,&hour,&minute, - &second, &tzflag); - data[i] = ogr_layer->data[i]->GetFieldAsString(col_idx); - } - } } -bool OGRColumnDateTime::GetCellValue(int row, wxInt64& val) +OGRColumnDateTime::~OGRColumnDateTime() { - if (undef_markers[row] == true) { - val = 0; - return false; - } - - if (new_data.empty()) { - int col_idx = GetColIndex(); - int year = 0; - int month = 0; - int day = 0; - int hour = 0; - int minute = 0; - int second = 0; - int tzflag = 0; - ogr_layer->data[row]->GetFieldAsDateTime(col_idx, &year, &month, - &day,&hour,&minute, - &second, &tzflag); - val = year * 10000000000 + month * 100000000 + day * 1000000 + hour * 10000 + minute * 100 + second; - } else { - val = new_data[row]; - } - - return true; } wxString OGRColumnDateTime::GetValueAt(int row_idx, int disp_decimals, @@ -1399,10 +1420,10 @@ wxString OGRColumnDateTime::GetValueAt(int row_idx, int disp_decimals, int year = 0; int month = 0; int day = 0; - int hour = 0; - int minute = 0; - int second = 0; - int tzflag = 0; + int hour = -1; + int minute = -1; + int second = -1; + int tzflag = -1; if (new_data.empty()) { int col_idx = GetColIndex(); @@ -1410,7 +1431,12 @@ wxString OGRColumnDateTime::GetValueAt(int row_idx, int disp_decimals, &day,&hour,&minute, &second, &tzflag); } else { - //val = new_data[row_idx]; + year = new_data[row_idx] / 10000000000; + month = (new_data[row_idx] % 10000000000) / 100000000; + day = (new_data[row_idx] % 100000000) / 1000000; + hour = (new_data[row_idx] % 1000000) / 10000; + minute = (new_data[row_idx] % 10000) / 100; + second = new_data[row_idx] % 100; } wxString sDateTime; @@ -1419,7 +1445,7 @@ wxString OGRColumnDateTime::GetValueAt(int row_idx, int disp_decimals, sDateTime << wxString::Format("%i-%i-%i", year, month, day); } - if (hour >0 || minute > 0 || second > 0) { + if (hour >=0 || minute >= 0 || second >= 0) { if (!sDateTime.IsEmpty()) sDateTime << " "; sDateTime << wxString::Format("%i:%i:%i", hour, minute, second); } @@ -1429,58 +1455,27 @@ wxString OGRColumnDateTime::GetValueAt(int row_idx, int disp_decimals, void OGRColumnDateTime::SetValueAt(int row_idx, const wxString &value) { - wxRegEx regex; - - wxString time_regex_str = "([0-9]{2}):([0-9]{2}):([0-9]{2})"; - wxString date_regex_str = "([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})"; - wxString datetime_regex_str = "([0-9]{4})-([0-9]{1,2})-([0-9]{1,2}) ([0-9]{2}):([0-9]{2}):([0-9]{2})"; - - wxString _year, _month, _day, _hour, _minute, _second; - - regex.Compile(time_regex_str); - if (regex.Matches(value)) { - _hour = regex.GetMatch(value,1); - _minute = regex.GetMatch(value,2); - _second = regex.GetMatch(value,3); - - } else { - - regex.Compile(date_regex_str); - if (regex.Matches(value)) { - //wxString _all = regex.GetMatch(value,0); - _year = regex.GetMatch(value,1); - _month = regex.GetMatch(value,2); - _day = regex.GetMatch(value,3); - - } else { - - regex.Compile(datetime_regex_str); - if (regex.Matches(value)) { - _year = regex.GetMatch(value,1); - _month = regex.GetMatch(value,2); - _day = regex.GetMatch(value,3); - _hour = regex.GetMatch(value,4); - _minute = regex.GetMatch(value,5); - _second = regex.GetMatch(value,6); - } - } + int col_idx = GetColIndex(); + if (value.IsEmpty()) { + undef_markers[row_idx] = true; + ogr_layer->data[row_idx]->UnsetField(col_idx); + return; } - + vector date_items; + wxString pattern = Gda::DetectDateFormat(value, date_items); + wxRegEx regex; + regex.Compile(pattern); + unsigned long long val = Gda::DateToNumber(value, regex, date_items); long _l_year =0, _l_month=0, _l_day=0, _l_hour=0, _l_minute=0, _l_second=0; - - _year.ToLong(&_l_year); - _month.ToLong(&_l_month); - _day.ToLong(&_l_day); - _hour.ToLong(&_l_hour); - _minute.ToLong(&_l_minute); - _second.ToLong(&_l_second); - - wxInt64 val = _l_year * 10000000000 + _l_month * 100000000 + _l_day * 1000000 + _l_hour * 10000 + _l_minute * 100 + _l_second; - if (is_new) { new_data[row_idx] = val; } else { - int col_idx = GetColIndex(); + _l_year = val / 10000000000; + _l_month = (val % 10000000000) / 100000000; + _l_day = (val % 100000000) / 1000000; + _l_hour = (val % 1000000) / 10000; + _l_minute = (val % 10000) / 100; + _l_second = val % 100; ogr_layer->data[row_idx]->SetField(col_idx, _l_year, _l_month, _l_day, _l_hour, _l_minute, _l_second, 0); // last TZFlag } } diff --git a/DataViewer/OGRColumn.h b/DataViewer/OGRColumn.h index e1602a758..a480aae04 100644 --- a/DataViewer/OGRColumn.h +++ b/DataViewer/OGRColumn.h @@ -22,6 +22,8 @@ #include #include +#include +#include #include "../GdaConst.h" #include "../DataViewer/VarOrderPtree.h" @@ -29,6 +31,7 @@ #include "../ShapeOperations/OGRLayerProxy.h" using namespace std; +namespace bt = boost::posix_time; /** * @@ -37,6 +40,7 @@ class OGRColumn { protected: wxString name; + int idx; // idx in ogr_layer int length; int decimals; bool is_new; @@ -45,6 +49,8 @@ class OGRColumn OGRLayerProxy* ogr_layer; // markers for a new column if the cell has ben assigned a value vector undef_markers; + + int get_date_format(std::string& s); public: // Constructor for in-memory column @@ -56,11 +62,13 @@ class OGRColumn // Get column index from loaded ogr_layer int GetColIndex(); - + + void SetUndefinedMarkers(vector& undefs) {undef_markers = undefs;} vector GetUndefinedMarkers() { return undef_markers;} // When SaveAs current datasource to a new datasource, the underneath OGRLayer will be replaced. void UpdateOGRLayer(OGRLayerProxy* new_ogr_layer); + OGRLayerProxy* GetOGRLayerProxy() { return ogr_layer;} bool IsNewColumn() { return is_new;} @@ -95,6 +103,7 @@ class OGRColumn virtual void UpdateData(const vector& data); virtual void UpdateData(const vector& data); virtual void UpdateData(const vector& data); + virtual void UpdateData(const vector& data); // following UpdateData will be used for any undefined/null values virtual void UpdateData(const vector& data, @@ -103,6 +112,8 @@ class OGRColumn const vector& undef_markers); virtual void UpdateData(const vector& data, const vector& undef_markers); + virtual void UpdateData(const vector& data, + const vector& undef_markers); // Should return true, unless if a undefined value is found virtual bool GetCellValue(int row, wxInt64& val); @@ -115,6 +126,7 @@ class OGRColumn virtual void FillData(vector& data); virtual void FillData(vector& data); virtual void FillData(vector& data); + virtual void FillData(vector& data); virtual void FillData(vector& data, vector& undef_markers); @@ -122,11 +134,15 @@ class OGRColumn vector& undef_markers); virtual void FillData(vector& datam, vector& undef_markers); + virtual void FillData(vector& datam, + vector& undef_markers); virtual wxString GetValueAt(int row_idx, int disp_decimals=0, wxCSConv* m_wx_encoding=NULL) = 0; virtual void SetValueAt(int row_idx, const wxString& value) = 0; + virtual void SetValueAt(int row_idx, wxInt64 value){} + virtual void SetValueAt(int row_idx, double value){} }; /** @@ -167,6 +183,7 @@ class OGRColumnInteger : public OGRColumn wxCSConv* m_wx_encoding=NULL); virtual void SetValueAt(int row_idx, const wxString& value); + void SetValueAt(int row_idx, wxInt64 value); }; @@ -208,6 +225,7 @@ class OGRColumnDouble : public OGRColumn wxCSConv* m_wx_encoding=NULL); virtual void SetValueAt(int row_idx, const wxString& value); + void SetValueAt(int row_idx, double value); }; @@ -221,6 +239,7 @@ class OGRColumnString : public OGRColumn void InitMemoryData(); + public: OGRColumnString(wxString name, int field_length, int decimals, int n_rows); @@ -239,6 +258,8 @@ class OGRColumnString : public OGRColumn virtual void FillData(vector& data); + virtual void FillData(vector& data); + virtual void UpdateData(const vector& data); virtual void UpdateData(const vector& data); @@ -259,21 +280,24 @@ class OGRColumnString : public OGRColumn */ class OGRColumnDate: public OGRColumn { -private: - vector new_data; +protected: + vector new_data; void InitMemoryData(); - public: - // XXX: don't support add new date column yet //OGRColumnDate(int rows); OGRColumnDate(OGRLayerProxy* ogr_layer, int idx); - ~OGRColumnDate(); + OGRColumnDate(OGRLayerProxy* ogr_layer, wxString name, int field_length, int decimals); + virtual ~OGRColumnDate(); virtual void FillData(vector& data); virtual void FillData(vector& data); + virtual void FillData(vector& data); + + virtual void UpdateData(const vector& data); + virtual GdaConst::FieldType GetType() {return GdaConst::date_type;} virtual bool GetCellValue(int row, wxInt64& val); @@ -285,57 +309,35 @@ class OGRColumnDate: public OGRColumn virtual void SetValueAt(int row_idx, const wxString& value); }; -class OGRColumnTime: public OGRColumn +class OGRColumnTime: public OGRColumnDate { -private: - vector new_data; - void InitMemoryData(); - public: - // XXX: don't support add new date column yet - //OGRColumnTime(int rows); OGRColumnTime(OGRLayerProxy* ogr_layer, int idx); - ~OGRColumnTime(); - - virtual void FillData(vector& data); - - virtual void FillData(vector& data); + OGRColumnTime(OGRLayerProxy* ogr_layer, wxString name, int field_length, int decimals); + virtual ~OGRColumnTime(); virtual GdaConst::FieldType GetType() {return GdaConst::time_type;} - virtual bool GetCellValue(int row, wxInt64& val); - virtual wxString GetValueAt(int row_idx, - int disp_decimals=0, wxCSConv* m_wx_encoding=NULL); - + int disp_decimals=0, + wxCSConv* m_wx_encoding=NULL); + virtual void SetValueAt(int row_idx, const wxString& value); }; -class OGRColumnDateTime: public OGRColumn +class OGRColumnDateTime: public OGRColumnDate { -private: - vector new_data; - void InitMemoryData(); - public: - // XXX: don't support add new date column yet - //OGRColumnDateTime(int rows); OGRColumnDateTime(OGRLayerProxy* ogr_layer, int idx); - ~OGRColumnDateTime(); - - virtual void FillData(vector& data); - - virtual void FillData(vector& data); + OGRColumnDateTime(OGRLayerProxy* ogr_layer, wxString name, int field_length, int decimals); + virtual ~OGRColumnDateTime(); virtual GdaConst::FieldType GetType() {return GdaConst::datetime_type;} - virtual bool GetCellValue(int row, wxInt64& val); - virtual wxString GetValueAt(int row_idx, int disp_decimals=0, wxCSConv* m_wx_encoding=NULL); virtual void SetValueAt(int row_idx, const wxString& value); }; - #endif diff --git a/DataViewer/OGRTable.cpp b/DataViewer/OGRTable.cpp index fc831a3f6..7c06b8779 100644 --- a/DataViewer/OGRTable.cpp +++ b/DataViewer/OGRTable.cpp @@ -23,6 +23,7 @@ #include #include #include +#include #include #include #include @@ -58,38 +59,14 @@ OGRTable::OGRTable(OGRLayerProxy* _ogr_layer, : TableInterface(table_state, time_state), ogr_layer(_ogr_layer), var_order(var_order_ptree), datasource_type(ds_type) { - LOG_MSG("Entering OGRTable::OGRTable"); + wxLogMessage("Entering OGRTable::OGRTable"); encoding_type = wxFONTENCODING_UTF8; m_wx_encoding = new wxCSConv(wxFONTENCODING_UTF8); - // create in memory OGRColumns, read var_map for (size_t i=0; ifields.size(); ++i) { AddOGRColumn(ogr_layer, i); - // deprecated in 1.8 - //var_map[columns[i]->GetName()] = i; - org_var_names.push_back(columns[i]->GetName()); } - /* - // If displayed decimals attribute in var_order is set to - // default, then set displayed decimals to decimals - for (int i=0, num_grps=var_order.GetNumVarGroups(); i var_names; - g.GetVarNames(var_names); - int decimals = 0; - for (int j=0; jGetField(var_name)->GetDecimals() > decimals) { - decimals = ogr_layer->GetField(var_name)->GetDecimals(); - } - } - if ( decimals > 0) { - var_order.SetDisplayedDecimals(i, decimals); - } - } - */ - rows = ogr_layer->n_rows; time_state->SetTimeIds(var_order.GetTimeIdsRef()); changed_since_last_save = false; @@ -97,7 +74,6 @@ ogr_layer(_ogr_layer), var_order(var_order_ptree), datasource_type(ds_type) is_valid = true; table_state->registerObserver(this); - } OGRTable::~OGRTable() @@ -109,21 +85,8 @@ OGRTable::~OGRTable() if (m_wx_encoding) { delete m_wx_encoding; } - LOG_MSG("In OGRTable::~OGRTable"); -} - -/* -void OGRTable::ChangeOGRLayer(OGRLayerProxy* new_ogr_layer) -{ - // When SaveAs current datasource to a new datasource, the underneath - // OGRLayer will be replaced. - ogr_layer = new_ogr_layer; - bool is_new_layer = true; - for (size_t i=0; ifields.size(); ++i) { - columns[i]->UpdateOGRLayer(new_ogr_layer); - } + wxLogMessage("In OGRTable::~OGRTable"); } -*/ void OGRTable::Update(const VarOrderPtree& var_order_ptree) { @@ -215,10 +178,11 @@ void OGRTable::AddOGRColumn(OGRLayerProxy* ogr_layer_proxy, int idx) ogr_col = new OGRColumnDateTime(ogr_layer_proxy,idx); } else { - wxString msg = "Add OGR column error. Field type is unknown."; + wxString msg = _("Add OGR column error. Field type is unknown."); throw GdaException(msg.mb_str()); } columns.push_back(ogr_col); + org_var_names.push_back(ogr_col->GetName()); } // Following 2 functions are for in-memory OGRTable @@ -228,15 +192,10 @@ void OGRTable::AddOGRColumn(OGRColumn* ogr_col) VarGroup g(ogr_col->GetName(), ogr_col->GetDecimals()); var_order.InsertVarGroup(g, pos); - columns.push_back(ogr_col); - - // deprecated in 1.8 - //var_map[ogr_col->GetName()] = pos; org_var_names.push_back(ogr_col->GetName()); } - OGRColumn* OGRTable::GetOGRColumn(int idx) { return columns[idx]; @@ -284,8 +243,6 @@ int OGRTable::GetTimeInt(const wxString& tm_string) bool OGRTable::IsTimeVariant() { - //return var_order.GetNumTms() > 1; - int n_vargrp = var_order.GetNumVarGroups(); for (int i=0; iExport."; + err_msg << _("GeoDa can't save changes to this datasource. Please try to use File->Export."); return false; } // clean Operations @@ -344,17 +301,13 @@ bool OGRTable::Save(wxString& err_msg) } // if it's readonly, it can be and will be exported.So we set no "Change" SetChangedSinceLastSave(false); - wxString msg = "GeoDa can't save changes to this datasource. Please try to use File->Export."; + wxString msg = _("GeoDa can't save changes to this datasource. Please try to use File->Export."); throw GdaException(msg.mb_str(), GdaException::NORMAL); return false; } bool OGRTable::IsReadOnly() { - //if (datasource_type == GdaConst::ds_dbf || - // datasource_type == GdaConst::ds_shapefile) { - // return true; - //} return !ogr_layer->is_writable; } @@ -384,24 +337,14 @@ int OGRTable::GetColIdx(const wxString& name, bool ignore_case) // update it if different in real data. E.g. user may create a column // with name in lowercase, however, it is forced to uppercase in real table - // or in postgresql, all table name will be created in lower case + // or in postgresql, which all table name will be created in lower case - /* - // deprecated in 1.8.8 - std::map::iterator i; - if ( (i=var_map.find(name)) != var_map.end() || - (i=var_map.find(name.Upper())) != var_map.end() || - (i=var_map.find(name.Lower())) != var_map.end() ) { - return i->second; - } - */ for (size_t i=0; i& col_map) } } +void OGRTable::FillStringColIdMap(std::vector& col_map) +{ + std::vector t; + FillColIdMap(t); + int string_cnt = 0; + for (int i=0, iend=t.size(); i& col_map) +{ + std::vector t; + FillColIdMap(t); + int numeric_cnt = 0; + for (int i=0, iend=t.size(); i& num_names) } } +//FillStringColIdMap +void OGRTable::FillStringNameList(std::vector& num_names) +{ + std::vector t; + FillStringColIdMap(t); + num_names.resize(t.size()); + int cnt=0; + for (int i=0, iend=t.size(); i& data) ogr_col->FillData(data); } +void OGRTable::GetDirectColData(int col, std::vector& data) +{ + // using underneath columns[] + if (col < 0 || col >= columns.size()) + return; + + OGRColumn* ogr_col = columns[col]; + if (ogr_col == NULL) return; + data.resize(rows); + ogr_col->FillData(data); +} + void OGRTable::GetColData(int col, int time, std::vector& data) { //if (!IsColNumeric(col)) return; @@ -823,6 +827,16 @@ void OGRTable::GetColData(int col, int time, std::vector& data) ogr_col->FillData(data); } +void OGRTable::GetColData(int col, int time, std::vector& data) +{ + wxString nm(var_order.GetSimpleColName(col, time)); + if (nm.IsEmpty()) return; + OGRColumn* ogr_col = FindOGRColumn(nm); + if (ogr_col == NULL) return; + data.resize(rows); + ogr_col->FillData(data); +} + bool OGRTable::GetColUndefined(int col, b_array_type& undefined) { if (col < 0 || col >= var_order.GetNumVarGroups()) @@ -945,26 +959,32 @@ void OGRTable::GetMinMaxVals(int col, vector& min_vals, if ( tmp_min_val > tmp ) tmp_min_val = tmp; if ( tmp_max_val < tmp ) tmp_max_val = tmp; } - min_vals.push_back(tmp_min_val); - max_vals.push_back(tmp_max_val); + if (has_init) { + min_vals.push_back(tmp_min_val); + max_vals.push_back(tmp_max_val); + } } } } -void OGRTable::GetMinMaxVals(int col, int time, +bool OGRTable::GetMinMaxVals(int col, int time, double& min_val, double& max_val) { min_val = 0; max_val = 0; - if (col < 0 || col >= GetNumberCols()) return; - if (!IsColNumeric(col)) return; - if (time < 0 || time > GetColTimeSteps(col)) return; + if (col < 0 || col >= GetNumberCols()) return false; + if (!IsColNumeric(col)) return false; + if (time < 0 || time > GetColTimeSteps(col)) return false; std::vector t_min; std::vector t_max; - GetMinMaxVals(col, t_min, t_max); - min_val = t_min[time]; - max_val = t_max[time]; + GetMinMaxVals(col, t_min, t_max); + if (t_min.empty() || t_max.empty()) { + return false; + } + min_val = t_min[time]; + max_val = t_max[time]; + return true; } void OGRTable::SetColData(int col, int time, @@ -1015,6 +1035,21 @@ void OGRTable::SetColData(int col, int time, SetChangedSinceLastSave(true); } +void OGRTable::SetColData(int col, int time, + const std::vector& data) +{ + if (col < 0 || col >= GetNumberCols()) return; + int ogr_col_id = FindOGRColId(col, time); + if (ogr_col_id == wxNOT_FOUND) return; + + OGRColumn* ogr_col = columns[ogr_col_id]; + operations_queue.push(new OGRTableOpUpdateColumn(ogr_col, data)); + ogr_col->UpdateData(data); + table_state->SetColDataChangeEvtTyp(ogr_col->GetName(), col); + table_state->notifyObservers(); + SetChangedSinceLastSave(true); +} + void OGRTable::SetColUndefined(int col, int time, const std::vector& undefs) { @@ -1195,10 +1230,7 @@ int OGRTable::InsertCol(GdaConst::FieldType type, // don't support the following column type if (type == GdaConst::placeholder_type || - type == GdaConst::unknown_type || - type == GdaConst::date_type|| - type == GdaConst::time_type|| - type == GdaConst::datetime_type) + type == GdaConst::unknown_type) { return -1; } @@ -1248,9 +1280,17 @@ int OGRTable::InsertCol(GdaConst::FieldType type, } else if (type==GdaConst::string_type){ ogr_col = new OGRColumnString(ogr_layer, names[t], field_len, decimals); + } else if (type==GdaConst::date_type){ + ogr_col = new OGRColumnDate(ogr_layer, names[t], field_len, decimals); + + } else if (type==GdaConst::time_type){ + ogr_col = new OGRColumnTime(ogr_layer, names[t], field_len, decimals); + + } else if (type==GdaConst::datetime_type){ + ogr_col = new OGRColumnDateTime(ogr_layer, names[t], field_len, decimals); + } else { - wxString msg = "Add OGR column error. Field type is unknown " - "or not supported."; + wxString msg = _("Add OGR column error. Field type is unknown or not supported."); throw GdaException(msg.mb_str()); } columns.insert(columns.begin()+pos, ogr_col); @@ -1292,8 +1332,8 @@ int OGRTable::InsertCol(GdaConst::FieldType type, bool OGRTable::DeleteCol(int pos) { - LOG_MSG("Inside OGRTable::DeleteCol"); - LOG_MSG(wxString::Format("Deleting column from table at postion %d", pos)); + wxLogMessage("Inside OGRTable::DeleteCol"); + wxLogMessage(wxString::Format("Deleting column from table at postion %d", pos)); if (pos < 0 || pos >= var_order.GetNumVarGroups() || var_order.GetNumVarGroups() == 0) @@ -1301,37 +1341,28 @@ bool OGRTable::DeleteCol(int pos) return false; } - // Must remove all items from var_map first - VarGroup vg = var_order.FindVarGroup(pos); - vector col_nms; - vg.GetVarNames(col_nms); - BOOST_FOREACH(const wxString& s, col_nms) { - if (s != "") { - for( size_t i=0; iGetName().CmpNoCase(s) == 0) { - operations_queue.push(new OGRTableOpDeleteColumn(columns[i])); - columns.erase(columns.begin()+i); - break; - } + wxString col_name = var_order.GetGroupName(pos); + if (!col_name.IsEmpty()) { + for( size_t i=0; iGetName().CmpNoCase(col_name) == 0) { + operations_queue.push(new OGRTableOpDeleteColumn(columns[i])); + columns.erase(columns.begin()+i); + break; } - } + } } - /* - // depcrecated in 1.8.8 - var_map.clear(); - for (int i=0; iGetName()] = i; + for (size_t i=0; i::iterator iter = org_var_names.begin() + pos; - org_var_names.erase(iter); - - wxString name = var_order.GetGroupName(pos); + var_order.RemoveVarGroup(pos); TableDeltaList_type tdl; - TableDeltaEntry tde(name, false, pos); + TableDeltaEntry tde(col_name, false, pos); tde.change_to_db = true; tdl.push_back(tde); table_state->SetColsDeltaEvtTyp(tdl); @@ -1344,7 +1375,7 @@ bool OGRTable::DeleteCol(int pos) void OGRTable::UngroupCol(int col) { - LOG_MSG("Inside OGRTable::UngroupCol"); + wxLogMessage("Inside OGRTable::UngroupCol"); if (col < 0 || col >= var_order.GetNumVarGroups()) return; if (GetColTimeSteps(col) <= 1) return; @@ -1353,7 +1384,8 @@ void OGRTable::UngroupCol(int col) GdaConst::FieldInfo fi; fi.type = GetColType(col, t); if (fi.type == GdaConst::placeholder_type || - fi.type == GdaConst::unknown_type) continue; + fi.type == GdaConst::unknown_type) + continue; fi.field_len = GetColLength(col, t); fi.decimals = GetColDecimals(col, t); nm_to_fi[GetColName(col, t)] = fi; @@ -1365,7 +1397,8 @@ void OGRTable::UngroupCol(int col) // Add missing information to tdl entries. for (TableDeltaList_type::iterator i=tdl.begin(); i!=tdl.end(); ++i) { - if (!i->insert) continue; + if (!i->insert) + continue; GdaConst::FieldInfo& fi = nm_to_fi[i->group_name]; i->type = fi.type; i->decimals = fi.decimals; @@ -1382,7 +1415,7 @@ void OGRTable::UngroupCol(int col) void OGRTable::GroupCols(const std::vector& cols, const wxString& name, int pos) { - LOG_MSG("Inside OGRTable::GroupCols"); + wxLogMessage("Inside OGRTable::GroupCols"); if (pos < 0 || pos > var_order.GetNumVarGroups()) return; if (cols.size() <= 1) return; if (GetTimeSteps() > 1 && cols.size() != GetTimeSteps()) return; @@ -1406,8 +1439,10 @@ void OGRTable::GroupCols(const std::vector& cols, GdaConst::FieldType type = GdaConst::unknown_type; bool found_nonplaceholder = false; for (size_t i=0; i= 0 && GetColType(cols[i]) != GdaConst::unknown_type - && GetColType(cols[i]) != GdaConst::placeholder_type) { + if (cols[i] >= 0 && + GetColType(cols[i]) != GdaConst::unknown_type && + GetColType(cols[i]) != GdaConst::placeholder_type) + { decimals = GetColDecimals(cols[i]); displayed_decimals = GetColDecimals(cols[i]); length = GetColLength(cols[i]); @@ -1515,20 +1550,11 @@ int OGRTable::FindOGRColId(int wxgrid_col_pos, int time) int OGRTable::FindOGRColId(const wxString& name) { for (size_t i=0; i < org_var_names.size(); i++ ) { - if (name == org_var_names[i]) { + if (name == org_var_names[i] ) { return i; } } return -1; - /* - // deprecated in 1.8.8 - std::map::iterator i = var_map.find(name); - if ( i == var_map.end()) i = var_map.find(name.Upper()); - if ( i == var_map.end()) i = var_map.find(name.Lower()); - if ( i == var_map.end()) return -1; - - return i->second; - */ } OGRColumn* OGRTable::FindOGRColumn(int col, int time) @@ -1543,20 +1569,11 @@ OGRColumn* OGRTable::FindOGRColumn(const wxString& name) if (name.IsEmpty()) return NULL; for (size_t i=0; i::iterator i =var_map.find(name); - if ( i == var_map.end()) i = var_map.find(name.Upper()); - if ( i == var_map.end()) i = var_map.find(name.Lower()); - if ( i == var_map.end()) return NULL; - - return columns[i->second]; - */ } bool OGRTable::IsValidDBColName(const wxString& col_nm, @@ -1567,8 +1584,7 @@ bool OGRTable::IsValidDBColName(const wxString& col_nm, { // no valid entry in datasrc_field_lens, could be a unwritable ds if ( fld_warn_msg ) { - *fld_warn_msg = "This datasource is not supported. Please export\n" - "to other datasource that GeoDa supports first."; + *fld_warn_msg = _("This datasource is not supported. Please export to other datasource that GeoDa supports first."); } return false; } @@ -1576,9 +1592,8 @@ bool OGRTable::IsValidDBColName(const wxString& col_nm, int field_len = GdaConst::datasrc_field_lens[datasource_type]; if ( field_len < col_nm.length() ) { if ( fld_warn_msg ) { - *fld_warn_msg = "The length of field name should be between 1 and "; - *fld_warn_msg << field_len << ".\n" - << "Current field length (" << col_nm.length() << ") is not valid."; + *fld_warn_msg = _("The length of field name should be between 1 and %d.\nCurrent field length (%d) is not valid"); + *fld_warn_msg = wxString::Format(*fld_warn_msg, field_len, col_nm.length()); } return false; } diff --git a/DataViewer/OGRTable.h b/DataViewer/OGRTable.h index fcbf159f2..62badc14c 100644 --- a/DataViewer/OGRTable.h +++ b/DataViewer/OGRTable.h @@ -24,6 +24,7 @@ #include #include #include +#include #include #include "OGRColumn.h" @@ -34,6 +35,7 @@ #include "../ShapeOperations/OGRLayerProxy.h" using namespace std; +namespace bt = boost::posix_time; class OGRTable : public TableInterface, TableStateObserver { @@ -52,20 +54,15 @@ class OGRTable : public TableInterface, TableStateObserver vector columns; VarOrderMapper var_order; - // var_map will be deprecate in 1.8.8, and replace by _var_names - map var_map; vector org_var_names; - vector new_var_names; - + // queues of table operations queue operations_queue; stack completed_stack; -private: void AddTimeIDs(int n); int FindOGRColId(int wxgrid_col_pos, int time); int FindOGRColId(const wxString& name); - OGRColumn* FindOGRColumn(int col, int time=0); OGRColumn* FindOGRColumn(const wxString& name); void AddOGRColumn(OGRLayerProxy* ogr_layer_proxy, int idx); @@ -81,12 +78,12 @@ class OGRTable : public TableInterface, TableStateObserver OGRLayerProxy* GetOGRLayer() { return ogr_layer; } //void ChangeOGRLayer(OGRLayerProxy* new_ogr_layer); -public: + OGRColumn* FindOGRColumn(int col, int time=0); + // These functions for in-memory table void AddOGRColumn(OGRColumn* ogr_col); OGRColumn* GetOGRColumn(int idx); - // Implementation of TableInterface pure virtual methods virtual void Update(const VarOrderPtree& var_order_ptree); @@ -114,8 +111,11 @@ class OGRTable : public TableInterface, TableStateObserver virtual int FindColId(const wxString& name); virtual int GetColIdx(const wxString& name, bool ignore_case=false); virtual void FillColIdMap(std::vector& col_map); + virtual void FillStringColIdMap(std::vector& col_map); virtual void FillNumericColIdMap(std::vector& col_map); + virtual void FillDateTimeColIdMap(std::vector& col_map); virtual void FillIntegerColIdMap(std::vector& col_map); + virtual void FillStringNameList(std::vector& num_names); virtual void FillNumericNameList(std::vector& num_names); virtual int GetNumberCols(); virtual int GetNumberRows(); @@ -138,10 +138,12 @@ class OGRTable : public TableInterface, TableStateObserver virtual void GetColData(int col, int time, std::vector& data); virtual void GetColData(int col, int time, std::vector& data); virtual void GetColData(int col, int time, std::vector& data); + virtual void GetColData(int col, int time, std::vector& data); virtual void GetDirectColData(int col, std::vector& data); virtual void GetDirectColData(int col, std::vector& data); virtual void GetDirectColData(int col, std::vector& data); + virtual void GetDirectColData(int col, std::vector& data); virtual bool GetDirectColUndefined(int col, std::vector& undefined); virtual bool GetColUndefined(int col, b_array_type& undefined); @@ -149,7 +151,7 @@ class OGRTable : public TableInterface, TableStateObserver std::vector& undefined); virtual void GetMinMaxVals(int col, std::vector& min_vals, std::vector& max_vals); - virtual void GetMinMaxVals(int col, int time, + virtual bool GetMinMaxVals(int col, int time, double& min_val, double& max_val); virtual void SetColData(int col, int time, const std::vector& data); @@ -157,6 +159,8 @@ class OGRTable : public TableInterface, TableStateObserver const std::vector& data); virtual void SetColData(int col, int time, const std::vector& data); + virtual void SetColData(int col, int time, + const std::vector& data); virtual void SetColUndefined(int col, int time, const std::vector& undefined); virtual bool ColChangeProperties(int col, int time, diff --git a/DataViewer/OGRTableOperation.cpp b/DataViewer/OGRTableOperation.cpp index b5219cfff..5f377b048 100644 --- a/DataViewer/OGRTableOperation.cpp +++ b/DataViewer/OGRTableOperation.cpp @@ -20,6 +20,10 @@ #include "OGRColumn.h" #include "OGRTableOperation.h" #include "../ShapeOperations/OGRLayerProxy.h" +#include + +namespace bt = boost::posix_time; + OGRTableOperation::OGRTableOperation(OGRColumn* col) { @@ -42,7 +46,8 @@ void OGRTableOpInsertColumn::Commit() // insert ogr column is only applied for appending new column if (ogr_col->IsNewColumn()) { int pos = ogr_layer->AddField(ogr_col->GetName().ToStdString(), - ogr_col->GetType(),ogr_col->GetLength(), + ogr_col->GetType(), + ogr_col->GetLength(), ogr_col->GetDecimals()); // column content will be done in OGRTableUpdateColumn } @@ -179,7 +184,7 @@ OGRTableOpRenameColumn::OGRTableOpRenameColumn( OGRColumn* col, : OGRTableOperation(col) { old_col_name = old_name; - new_col_name = new_name; + new_col_name = new_name; } void OGRTableOpRenameColumn::Commit() @@ -201,6 +206,17 @@ void OGRTableOpRenameColumn::Rollback() } //////////////////////////////////////////////////////////////////////////////// +OGRTableOpUpdateColumn::OGRTableOpUpdateColumn(OGRColumn* col, + const std::vector& new_data) +: OGRTableOperation(col) +{ + int n_rows = ogr_col->GetNumRows(); + t_old_data.resize(n_rows); + undef_old_data.resize(n_rows); + ogr_col->FillData(t_old_data, undef_old_data); + t_new_data = new_data; +} + OGRTableOpUpdateColumn::OGRTableOpUpdateColumn(OGRColumn* col, const std::vector& new_data) : OGRTableOperation(col) @@ -288,7 +304,7 @@ void OGRTableOpUpdateColumn::Rollback() //////////////////////////////////////////////////////////////////////////////// OGRTableOpUpdateCell::OGRTableOpUpdateCell(OGRColumn* col, int row_idx, double new_val) -: OGRTableOperation(col), d_new_value(0.0), d_old_value(0.0) +: OGRTableOperation(col), d_new_value(0.0), d_old_value(0.0), undef_old_value(false), undef_new_value(false) { // this if for adding new Double column this->row_idx = row_idx; @@ -300,7 +316,7 @@ OGRTableOpUpdateCell::OGRTableOpUpdateCell(OGRColumn* col, int row_idx, OGRTableOpUpdateCell::OGRTableOpUpdateCell(OGRColumn* col, int row_idx, wxInt64 new_val) -: OGRTableOperation(col), d_new_value(0.0), d_old_value(0.0) +: OGRTableOperation(col), d_new_value(0.0), d_old_value(0.0), undef_old_value(false), undef_new_value(false) { // this if for adding new Integer column this->row_idx = row_idx; @@ -312,7 +328,7 @@ OGRTableOpUpdateCell::OGRTableOpUpdateCell(OGRColumn* col, int row_idx, OGRTableOpUpdateCell::OGRTableOpUpdateCell(OGRColumn* col, int row_idx, wxString new_val) -: OGRTableOperation(col), d_new_value(0.0), d_old_value(0.0) +: OGRTableOperation(col), d_new_value(0.0), d_old_value(0.0), undef_old_value(false), undef_new_value(false) { // this is for user editing cell value and save to table, so the // wxString(new_val) could be any data type. Here converts new_val @@ -320,13 +336,15 @@ OGRTableOpUpdateCell::OGRTableOpUpdateCell(OGRColumn* col, int row_idx, this->row_idx = row_idx; wxString col_name = ogr_col->GetName(); GdaConst::FieldType type = ogr_col->GetType(); + if ( type == GdaConst::long64_type) { - new_val.ToLongLong(&l_new_value); + undef_new_value = !new_val.ToLongLong(&l_new_value); } else if (type == GdaConst::double_type) { - new_val.ToDouble(&d_new_value); + undef_new_value = !new_val.ToDouble(&d_new_value); } else if (type == GdaConst::string_type) { s_new_value = new_val; } + GetOriginalCellValue(); } @@ -349,9 +367,9 @@ void OGRTableOpUpdateCell::GetOriginalCellValue() if (col_idx < 0) s_old_value = wxEmptyString; else - s_old_value = - wxString(ogr_layer->data[row_idx]->GetFieldAsString(col_idx)); + s_old_value = wxString(ogr_layer->data[row_idx]->GetFieldAsString(col_idx)); } + undef_old_value = !ogr_layer->data[row_idx]->IsFieldSet(col_idx); } void OGRTableOpUpdateCell::Commit() @@ -362,7 +380,7 @@ void OGRTableOpUpdateCell::Commit() wxString col_name = ogr_col->GetName(); int col_idx = ogr_layer->GetFieldPos(col_name); if (col_idx < 0) { - wxString msg = "Internal Error: can't update an in-memory cell."; + wxString msg = _("Internal Error: can't update an in-memory cell."); throw GdaException(msg.mb_str()); } @@ -370,15 +388,16 @@ void OGRTableOpUpdateCell::Commit() if ( type == GdaConst::long64_type) { if ( ogr_col->IsCellUpdated(row_idx) || (l_new_value != l_old_value) ) { - ogr_layer->SetValueAt(row_idx, col_idx, (GIntBig)l_new_value); + // undef = s_new_value.IsEmpty() + ogr_layer->SetValueAt(row_idx, col_idx, (GIntBig)l_new_value, undef_new_value); } } else if (type == GdaConst::double_type) { if ( ogr_col->IsCellUpdated(row_idx) || (d_new_value != d_old_value) ) { - ogr_layer->SetValueAt(row_idx, col_idx, d_new_value); + ogr_layer->SetValueAt(row_idx, col_idx, d_new_value, undef_new_value); } } else if (type == GdaConst::string_type) { if ( ogr_col->IsCellUpdated(row_idx) || (s_new_value != s_old_value) ) { - ogr_layer->SetValueAt(row_idx, col_idx, s_new_value); + ogr_layer->SetValueAt(row_idx, col_idx, s_new_value, undef_new_value); } } } @@ -397,15 +416,15 @@ void OGRTableOpUpdateCell::Rollback() if ( type == GdaConst::long64_type) { if ( ogr_col->IsCellUpdated(row_idx) || (l_new_value != l_old_value) ) { - ogr_layer->SetValueAt(row_idx, col_idx, (GIntBig)l_new_value); + ogr_layer->SetValueAt(row_idx, col_idx, (GIntBig)l_new_value, undef_old_value); } } else if (type == GdaConst::double_type) { if ( ogr_col->IsCellUpdated(row_idx) || (d_new_value != d_old_value) ) { - ogr_layer->SetValueAt(row_idx, col_idx, d_new_value); + ogr_layer->SetValueAt(row_idx, col_idx, d_new_value, undef_old_value); } } else if (type == GdaConst::string_type) { if ( ogr_col->IsCellUpdated(row_idx) || (s_new_value != s_old_value) ) { - ogr_layer->SetValueAt(row_idx, col_idx, s_new_value); + ogr_layer->SetValueAt(row_idx, col_idx, s_new_value, undef_old_value); } } -} \ No newline at end of file +} diff --git a/DataViewer/OGRTableOperation.h b/DataViewer/OGRTableOperation.h index 8895f23a5..746eb8270 100644 --- a/DataViewer/OGRTableOperation.h +++ b/DataViewer/OGRTableOperation.h @@ -22,6 +22,9 @@ #include #include "OGRColumn.h" +#include + +namespace bt = boost::posix_time; using namespace std; @@ -122,11 +125,13 @@ class OGRTableOpUpdateColumn : public OGRTableOperation vector d_old_data, d_new_data; vector l_old_data, l_new_data; vector s_old_data, s_new_data; + vector t_old_data, t_new_data; public: OGRTableOpUpdateColumn(OGRColumn* col, const vector& new_data); OGRTableOpUpdateColumn(OGRColumn* col, const vector& new_data); OGRTableOpUpdateColumn(OGRColumn* col, const vector& new_data); + OGRTableOpUpdateColumn(OGRColumn* col, const vector& new_data); ~OGRTableOpUpdateColumn(){} virtual void Commit(); @@ -144,6 +149,7 @@ class OGRTableOpUpdateCell : public OGRTableOperation double d_old_value, d_new_value; wxInt64 l_old_value, l_new_value; wxString s_old_value, s_new_value; + bool undef_old_value, undef_new_value; void GetOriginalCellValue(); public: @@ -156,4 +162,4 @@ class OGRTableOpUpdateCell : public OGRTableOperation virtual void Rollback(); }; -#endif \ No newline at end of file +#endif diff --git a/DataViewer/TableBase.cpp b/DataViewer/TableBase.cpp index fbdae7821..8433042c2 100644 --- a/DataViewer/TableBase.cpp +++ b/DataViewer/TableBase.cpp @@ -128,9 +128,9 @@ void TableBase::UpdateStatusBar() wxStatusBar* sb = template_frame->GetStatusBar(); if (!sb) return; wxString s; - s << "#obs=" << project->GetNumRecords() << " "; + s << _("#row=") << project->GetNumRecords() << " "; if (highlight_state->GetTotalHighlighted()> 0) { - s << "#selected=" << highlight_state->GetTotalHighlighted() << " "; + s << _("#selected=") << highlight_state->GetTotalHighlighted() << " "; } sb->SetStatusText(s); @@ -265,6 +265,53 @@ class index_pair } }; +std::vector TableBase::GetRowOrder() +{ + return row_order; +} + +template +void TableBase::SortColumn(int col, int tm, bool ascending) +{ + std::vector temp; + table_int->GetColData(col, tm, temp); + std::vector undefs; + table_int->GetColUndefined(col, tm, undefs); + std::vector undef_ids; + for (int i=0; i > sort_col(rows - undef_ids.size()); + int j = 0; + for (int i=0; i::less_than); + for (int i=0; i::greater_than); + for (int i=0; i temp; - table_int->GetColData(col, tm, temp); - std::vector< index_pair > sort_col(rows); - for (int i=0; i::less_than); - } else { - sort(sort_col.begin(), sort_col.end(), - index_pair::greater_than); - } - for (int i=0, iend=rows; i(col, tm, ascending); } break; case GdaConst::double_type: { - std::vector temp; - table_int->GetColData(col, tm, temp); - std::vector< index_pair > sort_col(rows); - for (int i=0; i::less_than); - } else { - sort(sort_col.begin(), sort_col.end(), - index_pair::greater_than); - } - for (int i=0, iend=rows; i(col, tm, ascending); } break; case GdaConst::string_type: { - std::vector temp; - table_int->GetColData(col, tm, temp); - std::vector< index_pair > sort_col(rows); - for (int i=0; i::less_than); - } else { - sort(sort_col.begin(), sort_col.end(), - index_pair::greater_than); - } - for (int i=0, iend=rows; i(col, tm, ascending); } break; default: @@ -373,16 +372,19 @@ void TableBase::MoveSelectedToTop() bool TableBase::FromGridIsSelectedCol(int col) { + if (hs_col.size() -1 SetColFormatFloat(e.pos_final, -1, - GenUtils::min(e.decimals, dd)); + std::min(e.decimals, dd)); } else { // leave as a string } diff --git a/DataViewer/TableBase.h b/DataViewer/TableBase.h index 1ce8fe96e..c9760f035 100644 --- a/DataViewer/TableBase.h +++ b/DataViewer/TableBase.h @@ -88,8 +88,13 @@ public HighlightStateObserver, public wxGridTableBase virtual TableInterface* GetTableInt(); void UpdateStatusBar(); + + template + void SortColumn(int col, int tm, bool ascending); -private: + std::vector GetRowOrder(); + +protected: HighlightState* highlight_state; std::vector& hs; //shortcut to HighlightState::highlight, read only! std::vector hs_col; diff --git a/DataViewer/TableFrame.cpp b/DataViewer/TableFrame.cpp index b52477fbb..48039379e 100644 --- a/DataViewer/TableFrame.cpp +++ b/DataViewer/TableFrame.cpp @@ -107,7 +107,7 @@ popup_col(-1) } - int sample = GenUtils::min(table_base->GetNumberRows(), 10); + int sample = std::min(table_base->GetNumberRows(), 10); for (int i=0, iend=table_base->GetNumberCols(); iGetColSize(i); @@ -140,9 +140,9 @@ popup_col(-1) } } - if (!project->IsFileDataSource()) { - grid->DisableDragColMove(); - } + //if (!project->IsFileDataSource()) { + // grid->DisableDragColMove(); + //} //grid->SetMargins(0 - wxSYS_VSCROLL_X, 0); grid->ForceRefresh(); @@ -173,7 +173,7 @@ void TableFrame::OnMouseEvent(wxMouseEvent& event) TableInterface* ti = table_base->GetTableInt(); SetEncodingCheckmarks(optMenu, ti->GetFontEncoding()); - PopupMenu(optMenu, event.GetPosition()); + PopupMenu(optMenu); } } @@ -215,6 +215,11 @@ void TableFrame::OnClose(wxCloseEvent& event) } } +std::vector TableFrame::GetRowOrder() +{ + return table_base->GetRowOrder(); +} + void TableFrame::OnMenuClose(wxCommandEvent& event) { Hide(); @@ -225,8 +230,7 @@ void TableFrame::MapMenus() // Map Default Options Menus //wxMenu* optMenu=wxXmlResource::Get()->LoadMenu("ID_DEFAULT_MENU_OPTIONS"); wxMenu* optMenu=wxXmlResource::Get()->LoadMenu("ID_TABLE_VIEW_MENU_CONTEXT"); - GeneralWxUtils::ReplaceMenu(GdaFrame::GetGdaFrame()->GetMenuBar(), - "Options", optMenu); + GeneralWxUtils::ReplaceMenu(GdaFrame::GetGdaFrame()->GetMenuBar(), _("Options"), optMenu); } void TableFrame::DisplayPopupMenu( wxGridEvent& ev ) @@ -545,7 +549,7 @@ void TableFrame::OnCellChanged( wxGridEvent& ev ) wxLogMessage("In TableFrame::OnCellChanged()"); TableInterface* ti = table_base->GetTableInt(); if (ti->IsSetCellFromStringFail()) { - wxMessageDialog dlg(this, ti->GetSetCellFromStringFailMsg(), "Warning", + wxMessageDialog dlg(this, ti->GetSetCellFromStringFailMsg(), _("Warning"), wxOK | wxICON_INFORMATION); dlg.ShowModal(); ev.Veto(); @@ -595,7 +599,7 @@ void TableFrame::OnGroupVariables( wxCommandEvent& event) if (ti->GetTimeSteps() == 1 && sel_cols.size() > 1) { if (table_state->GetNumDisallowTimelineChanges() > 0) { wxString msg = table_state->GetDisallowTimelineChangesMsg(); - wxMessageDialog dlg (this, msg, "Warning", + wxMessageDialog dlg (this, msg, _("Warning"), wxOK | wxICON_INFORMATION); dlg.ShowModal(); return; diff --git a/DataViewer/TableFrame.h b/DataViewer/TableFrame.h index 74d309282..a59e5e359 100644 --- a/DataViewer/TableFrame.h +++ b/DataViewer/TableFrame.h @@ -49,7 +49,8 @@ class TableFrame : public TemplateFrame void OnCellChanged( wxGridEvent& ev ); void OnMouseEvent(wxMouseEvent& event); - + + std::vector GetRowOrder(); TableBase* GetTableBase() { return table_base; } /** Implementation of TimeStateObserver interface */ diff --git a/DataViewer/TableInterface.cpp b/DataViewer/TableInterface.cpp index e35f2dbfd..b0f93de7b 100644 --- a/DataViewer/TableInterface.cpp +++ b/DataViewer/TableInterface.cpp @@ -16,11 +16,14 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ +#include #include "../GenUtils.h" #include "../logger.h" #include "TableInterface.h" -#include "../DbfFile.h" + +namespace bt = boost::posix_time; + TableInterface::TableInterface(TableState* table_state_s, TimeState* time_state_s) @@ -147,7 +150,9 @@ std::vector TableInterface::SuggestDBColNames(wxString new_grp_name, w wxString TableInterface::GetUniqueGroupName(wxString grp_nm) const { const int MAX_TRIES = 100000; - if (grp_nm.IsEmpty()) grp_nm = "Group"; + if (grp_nm.IsEmpty()) { + grp_nm = "Group"; + } wxString u(grp_nm); for (int i=0; i TableInterface::GetUniqueColNames(wxString col_nm, return ret; const int MAX_TRIES = 100000; - if (col_nm.IsEmpty()) col_nm = "VAR"; + if (col_nm.IsEmpty()) { + col_nm = "VAR"; + } if (col_nm.length() > cols_max_length) { col_nm = col_nm.substr(0, cols_max_length); } @@ -238,6 +245,14 @@ void TableInterface::SetColData(int col, int time, SetColUndefined(col, time, undefs); } +void TableInterface::SetColData(int col, int time, + const std::vector& data, + const std::vector& undefs) +{ + SetColData(col, time, data); + SetColUndefined(col, time, undefs); +} + void TableInterface::GetColData(int col, int time, std::vector& data, std::vector& undefs) { @@ -258,3 +273,10 @@ void TableInterface::GetColData(int col, int time, std::vector& data, GetColData(col, time, data); GetColUndefined(col, time, undefs); } + +void TableInterface::GetColData(int col, int time, std::vector& data, + std::vector& undefs) +{ + GetColData(col, time, data); + GetColUndefined(col, time, undefs); +} diff --git a/DataViewer/TableInterface.h b/DataViewer/TableInterface.h index 8c495226c..6f10d416d 100644 --- a/DataViewer/TableInterface.h +++ b/DataViewer/TableInterface.h @@ -25,6 +25,8 @@ #include #include #include +#include + #include "TableState.h" #include "TimeState.h" #include "TableStateObserver.h" @@ -32,6 +34,8 @@ #include "../GdaConst.h" #include "../VarCalc/GdaFlexValue.h" +namespace bt = boost::posix_time; + class TimeState; class VarOrderPtree; @@ -108,9 +112,12 @@ class TableInterface virtual int FindColId(const wxString& name) = 0; virtual void FillColIdMap(std::vector& col_map) = 0; + virtual void FillDateTimeColIdMap(std::vector& col_map) = 0; virtual void FillNumericColIdMap(std::vector& col_map) = 0; + virtual void FillStringColIdMap(std::vector& col_map) = 0; virtual void FillIntegerColIdMap(std::vector& col_map) = 0; virtual void FillNumericNameList(std::vector& num_names) = 0; + virtual void FillStringNameList(std::vector& num_names) = 0; virtual int GetNumberCols() = 0; virtual int GetNumberRows() = 0; @@ -148,6 +155,7 @@ class TableInterface virtual void GetColData(int col, int time, std::vector& data) = 0; virtual void GetColData(int col, int time, std::vector& data) = 0; virtual void GetColData(int col, int time, std::vector& data) = 0; + virtual void GetColData(int col, int time, std::vector& data) = 0; virtual void GetColData(int col, int time, std::vector& data, std::vector& undefs); @@ -155,6 +163,8 @@ class TableInterface std::vector& undefs); virtual void GetColData(int col, int time, std::vector& data, std::vector& undefs); + virtual void GetColData(int col, int time, std::vector& data, + std::vector& undefs); virtual bool GetColUndefined(int col, b_array_type& undefined) = 0; virtual bool GetColUndefined(int col, int time, @@ -164,11 +174,12 @@ class TableInterface virtual void GetDirectColData(int col, std::vector& data) =0; virtual void GetDirectColData(int col, std::vector& data)=0; virtual void GetDirectColData(int col, std::vector& data)=0; + virtual void GetDirectColData(int col, std::vector& data)=0; virtual bool GetDirectColUndefined(int col, std::vector& undefs)=0; virtual void GetMinMaxVals(int col, std::vector& min_vals, std::vector& max_vals) = 0; - virtual void GetMinMaxVals(int col, int time, + virtual bool GetMinMaxVals(int col, int time, double& min_val, double& max_val) = 0; virtual void SetColData(int col, int time, @@ -177,6 +188,8 @@ class TableInterface const std::vector& data) = 0; virtual void SetColData(int col, int time, const std::vector& data) = 0; + virtual void SetColData(int col, int time, + const std::vector& data) = 0; virtual void SetColData(int col, int time, const std::vector& data, @@ -187,6 +200,9 @@ class TableInterface virtual void SetColData(int col, int time, const std::vector& data, const std::vector& undefs); + virtual void SetColData(int col, int time, + const std::vector& data, + const std::vector& undefs); virtual void SetColUndefined(int col, int time, const std::vector& undefined) = 0; diff --git a/DataViewer/VarGroup.cpp b/DataViewer/VarGroup.cpp index 02837cd29..76f837449 100644 --- a/DataViewer/VarGroup.cpp +++ b/DataViewer/VarGroup.cpp @@ -75,6 +75,19 @@ bool VarGroup::IsAllPlaceholders() const return true; } +bool VarGroup::IsAnyPlaceholders() const +{ + if (IsEmpty()) return true; + if (IsSimple()) return false; + BOOST_FOREACH(const wxString& v, vars) if (v.IsEmpty()) return true; + return false; +} + +int VarGroup::GetNumVars() const +{ + return vars.size(); +} + int VarGroup::GetNumTms() const { if (IsEmpty()) return 0; diff --git a/DataViewer/VarGroup.h b/DataViewer/VarGroup.h index 5907b5dd2..d36ed4c41 100644 --- a/DataViewer/VarGroup.h +++ b/DataViewer/VarGroup.h @@ -38,7 +38,9 @@ struct VarGroup { void Append(const VarGroup& e); void AppendPlaceholder(); bool IsAllPlaceholders() const; + bool IsAnyPlaceholders() const; int GetNumTms() const; + int GetNumVars() const; void GetVarNames(std::vector& var_nms) const; wxString GetNameByTime(int time) const; wxString GetGroupName() const; diff --git a/DataViewer/VarOrderMapper.cpp b/DataViewer/VarOrderMapper.cpp index 8c2d6621e..bc0bd0185 100644 --- a/DataViewer/VarOrderMapper.cpp +++ b/DataViewer/VarOrderMapper.cpp @@ -306,7 +306,8 @@ void VarOrderMapper::Ungroup(int grp_pos, TableDeltaList_type& tdl) for (size_t i=0; i #include #include +#include + #include "../GdaException.h" #include "../logger.h" #include "VarOrderPtree.h" @@ -73,43 +75,54 @@ void VarOrderPtree::ReadPtree(const boost::property_tree::ptree& pt, wxString key = v.first.data(); if (key == "var") { VarGroup ent; - ent.name = v.second.data(); + wxString tmp(v.second.data().c_str(), wxConvUTF8); + ent.name = tmp; //var_order.push_back(v.second.data()); var_grps.push_back(ent); } else if (key == "time_ids") { BOOST_FOREACH(const ptree::value_type &v, v.second) { - wxString key = v.first.data(); - time_ids.push_back(v.second.data()); + wxString tmp(v.first.data(), wxConvUTF8); + wxString key = tmp; + wxString val(v.second.data().c_str(), wxConvUTF8); + time_ids.push_back(val); } } else if (key == "group") { + bool valid_group = true; VarGroup ent; BOOST_FOREACH(const ptree::value_type &v, v.second) { - wxString key = v.first.data(); + wxString tmp(v.first.data(), wxConvUTF8); + wxString key = tmp; if (key == "name") { - ent.name = v.second.data(); + wxString tmp1(v.second.data().c_str(), wxConvUTF8); + ent.name = tmp1; } else if (key == "var") { - ent.vars.push_back(v.second.data()); + wxString tmp1(v.second.data().c_str(), wxConvUTF8); + ent.vars.push_back(tmp1); } else if (key == "placeholder") { ent.vars.push_back(""); + valid_group = false; } else if (key == "displayed_decimals") { - wxString vs(v.second.data()); + wxString vs(v.second.data().c_str(), wxConvUTF8); long dd; if (!vs.ToLong(&dd)) dd = -1; ent.displayed_decimals = dd; - } + } else { + valid_group = false; + } } if (ent.name.empty()) { - wxString msg = "space-time variable found with no name"; + wxString msg = _("space-time variable found with no name"); throw GdaException(msg.mb_str()); } if (grp_set.find(ent.name) != grp_set.end()) { - wxString ss; - ss << "Space-time variables with duplicate name \""; - ss << ent.name << "\" found."; + wxString ss = _("Space-time variables with duplicate name \"%s\" found."); + ss = wxString::Format(ss, ent.name); throw GdaException(ss.mb_str()); } - var_grps.push_back(ent); - grp_set.insert(ent.name); + if (valid_group) { + var_grps.push_back(ent); + grp_set.insert(ent.name); + } } } } catch (std::exception &e) { diff --git a/DbfFile.cpp b/DbfFile.cpp deleted file mode 100644 index ae6f2932c..000000000 --- a/DbfFile.cpp +++ /dev/null @@ -1,893 +0,0 @@ -/** - * GeoDa TM, Copyright (C) 2011-2015 by Luc Anselin - all rights reserved - * - * This file is part of GeoDa. - * - * GeoDa is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * GeoDa is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -#include -#include -#include -#include -#include -//#include // for random number generator -#include // for random number generator and atoi -#include "GdaConst.h" -#include "logger.h" -#include "DbfFile.h" -#include "GenUtils.h" - -// dBaseIII+ is only 128, but many others are much higher. Some people -// have imperically discovered that 2046 is OK in practice for many -// implementations. -const int DbfFileReader::MAX_NUMBER_FIELDS = 2046; - -DbfFileReader::DbfFileReader(const wxString& filename) : - fname(filename), read_success(false) -{ - file.open(fname.fn_str(), std::ios::in | std::ios::binary); - if (!(file.is_open() && file.good())) { - read_success = false; - return; - } - if (populateHeader() && populateFieldDescs()) read_success = true; - if (file.is_open()) file.close(); -} - -DbfFileReader::~DbfFileReader() -{ - if (file.is_open()) file.close(); -} - -DbfFileHeader DbfFileReader::getFileHeader() -{ - return header; -} - -std::vector DbfFileReader::getFieldDescs() -{ - return fields; -} - -void DbfFileReader::getFieldTypes( - std::map& field_type_map) -{ - field_type_map.clear(); - for (int i=0, ie=fields.size(); i 0) { - field_type_map[name] = GdaConst::double_type; - } else { - field_type_map[name] = GdaConst::long64_type; - } - } else if (type == 'D') { - field_type_map[name] = GdaConst::date_type; - } else { - // assume (type == 'C') - field_type_map[name] = GdaConst::string_type; - } - } -} - -void DbfFileReader::getFieldList(std::vector& field_list) -{ - field_list.resize(fields.size()); - for (int i=0, ie=fields.size(); i= 0 && field < (int) fields.size()); -} - -bool DbfFileReader::isFieldExists(const wxString& f_name) -{ - for (int i=0; i< (int) fields.size(); i++) - if (f_name == fields[i].name) return true; - return false; -} - -DbfFieldDesc DbfFileReader::getFieldDesc(int field) -{ - if (field >= 0 && field < (int) fields.size()) - return fields[field]; - else - return DbfFieldDesc(); -} - -DbfFieldDesc DbfFileReader::getFieldDesc(const wxString& f_name) -{ - for (int i=0; i< (int) fields.size(); i++) - if (f_name == fields[i].name) return fields[i]; - return DbfFieldDesc(); -} - -bool DbfFileReader::isFieldValUnique(const wxString& f_name) -{ - for (int i=0; i< (int) fields.size(); i++) { - if (f_name == fields[i].name) - return isFieldValUnique(i); - } - return false; -} - -WX_DECLARE_HASH_SET( wxString, wxStringHash, wxStringEqual, StringSet); - -bool DbfFileReader::isFieldValUnique(int field) -{ - bool all_unique = false; - read_success = false; - if (!file.is_open()) - file.open(fname.fn_str(), std::ios::in | std::ios::binary); - if (!(file.is_open() && file.good())) return false; - - if (field >= (int) fields.size()) { - return false; - } - - // calculate field offset - int record_offset = 1; // the record deletion flag - for (int i=0; i> 5 = " - << ((header.header_length - 33) >> 5) << endl; -} - -void DbfFileReader::printFieldDesc(int field, wxTextOutputStream& outstrm) -{ - outstrm << "name: " << fields[field].name; - outstrm << ", type: " << wxChar(fields[field].type); - outstrm << ", length: " << fields[field].length; - outstrm << ", decimals: " << fields[field].decimals << endl; -} - -bool DbfFileReader::getFieldValsLong(const wxString& f_name, - std::vector& vals) -{ - for (int i=0; i< (int) fields.size(); i++) { - if (f_name == fields[i].name) - return getFieldValsLong(i, vals); - } - return false; -} - -bool DbfFileReader::getFieldValsLong(int field, std::vector& vals) -{ - if (field < 0 || field >= (int) fields.size()) return false; - if (vals.size() != header.num_records) return false; - - if (!file.is_open()) - file.open(fname.fn_str(), std::ios::in | std::ios::binary); - if (!(file.is_open() && file.good())) return false; - - // calculate field offset - int record_offset = 1; // the record deletion flag - for (int i=0; i& vals) -{ - for (int i=0; i< (int) fields.size(); i++) { - if (f_name == fields[i].name) - return getFieldValsDouble(i, vals); - } - return false; -} - -bool DbfFileReader::getFieldValsDouble(int field, std::vector& vals) -{ - if (field < 0 || field >= (int) fields.size()) return false; - if (vals.size() != header.num_records) return false; - - if (!file.is_open()) - file.open(fname.fn_str(), std::ios::in | std::ios::binary); - if (!(file.is_open() && file.good())) return false; - - // calculate field offset - int record_offset = 1; // the record deletion flag - for (int i=0; i& vals) -{ - if (field < 0 || field >= (int) fields.size()) return false; - if (vals.size() != header.num_records) return false; - - if (!file.is_open()) - file.open(fname.fn_str(), std::ios::in | std::ios::binary); - if (!(file.is_open() && file.good())) return false; - - // calculate field offset - int record_offset = 1; // the record deletion flag - for (int i=0; i= (int) fields.size()) { - outstrm << "Error: field does not exist: field = " - << field << ", fields.size() = " << (int) fields.size() - << endl; - return; - } - // calculate field offset - int record_offset = 1; // the record deletion flag - for (int i=0; i fields; - DbfFileReader* reader_ptr = new DbfFileReader(in_fname); - header = reader_ptr->getFileHeader(); - fields = reader_ptr->getFieldDescs(); - bool file_valid = reader_ptr->isDbfReadSuccess(); - delete reader_ptr; - if (!file_valid) { - err_msg += "Error: could not read \"" + in_fname + "\""; - return false; - } - - std::ifstream in_file; - in_file.open(in_fname.fn_str(), std::ios::in | std::ios::binary); - - if (!(in_file.is_open() && in_file.good())) { - err_msg += "Error: Problem opening \"" + in_fname + "\""; - return false; - } - - std::ofstream out_file; - wxString temp_out_fname = out_fname; - if (in_fname == out_fname) { - wxFileName fn(out_fname); - wxString just_name = fn.GetName(); - fn.SetName("1-_" + just_name); - temp_out_fname = fn.GetPathWithSep() + fn.GetFullName(); - } - //out_file.open(temp_out_fname.fn_str(),std::ios::out | std::ios::binary); - out_file.open(GET_ENCODED_FILENAME(temp_out_fname), std::ios::out | std::ios::binary); - - if (!(out_file.is_open() && out_file.good())) { - err_msg += "Error: Problem opening \"" + temp_out_fname + "\""; - return false; - } - - //if (header.num_fields == DbfFileReader::MAX_NUMBER_FIELDS) { - // err_msg += "Error: adding a new field will exceed "; - // err_msg << DbfFileReader::MAX_NUMBER_FIELDS; - // err_msg += " field max "; - // err_msg += "for a DBF file."; - // return false; - //} - - // make sure the new id_fld_pos is valid: - if (id_fld_pos < 0) id_fld_pos = 0; - if (id_fld_pos > header.num_fields) id_fld_pos = header.num_fields; - if (id_fld_name.length() > 10) { - err_msg += "Error: the new field name is greater than 10 characters "; - err_msg += "in length."; - return false; - } - - wxUint32 u_int32; - wxUint32* u_int32p = &u_int32; - wxUint16 u_int16; - wxUint16* u_int16p = &u_int16; - wxUint8 u_int8; - wxUint8* u_int8p = &u_int8; - char membyte; - - // byte 0 - membyte = header.version; - out_file.put(membyte); - - // byte 1 - membyte = (char) (header.year - 1900); - out_file.put(membyte); - - // byte 2 - membyte = (char) header.month; - out_file.put(membyte); - - // byte 3 - membyte = (char) header.day; - out_file.put(membyte); - - // byte 4-7 - u_int32 = header.num_records; - u_int32 = wxUINT32_SWAP_ON_BE(u_int32); - out_file.write((char*) u_int32p, 4); - - // byte 8-9 - // Since we are adding a new field, the header length grows by 32 bytes. - u_int16 = header.header_length + 32; - u_int16 = wxUINT16_SWAP_ON_BE(u_int16); - out_file.write((char*) u_int16p, 2); - - // byte 10-11 - // Since we are adding a new field of size 10, the length of each record - // grows by 10 bytes. - u_int16 = header.length_each_record + 10; - u_int16 = wxUINT16_SWAP_ON_BE(u_int16); - out_file.write((char*) u_int16p, 2); - - // byte 12-13 (0x0000) - u_int16 = 0x0; - out_file.write((char*) u_int16p, 2); - - // copy whatever is in source for - // bytes 14 through 31. - in_file.seekg(14, std::ios::beg); - for (int i=0; i< (31-14)+1; i++) { - in_file.get(membyte); - out_file.put(membyte); - } - - // in_file and out_file now both point to byte 32, which is the beginning of - // the list of fields. There must be at least one field. Each field - // descriptor is 32 bytes long with byte 0xd following the last field - // descriptor. We will insert our new field at the head of the list and - // then copy the in_file field descriptors after that. - - char* byte32_buff = new char[32]; - for (int i=0; i 10 ) return false; - if ( !isAlphabetic(n.Mid(0,1)) || n.Mid(0,1) == "_" ) return false; - for (int i=0, iend=n.size(); i 18) length = 18; - wxInt64 r=0; - for (int i=0; i 19) length = 19; - return -GetMaxInt(length-1); -} - -wxString DbfFileUtils::GetMinIntString(int length) -{ - return wxString::Format("%lld", GetMinInt(length)); -} - -void DbfFileUtils::SuggestDoubleParams(int length, int decimals, - int* suggest_len, int* suggest_dec) -{ - // doubles have 52 bits for the mantissa, so we can allow at most - // floor(log(2^52)) = 15 digits of precision. - // We require that there length-2 >= decimals to allow for "x." . when - // writing to disk, and when decimals = 15, require length >= 17 to - // allow for "0." prefex. If length-2 == decimals, then negative numbers - // are not allowed since there is not room for the "-0." prefix. - if (GdaConst::max_dbf_double_len < length) { - length = GdaConst::max_dbf_double_len; - } - if (length < 3) length = 3; - if (decimals < 1) decimals = 1; - if (decimals > 15) decimals = 15; - if (length-2 < decimals) length = decimals + 2; - - *suggest_len = length; - *suggest_dec = decimals; -} - -double DbfFileUtils::GetMaxDouble(int length, int decimals, - int* suggest_len, int* suggest_dec) -{ - // make sure that length and decimals have legal values - SuggestDoubleParams(length, decimals, &length, &decimals); - - int len_inter = length - (1+decimals); - if (len_inter + decimals > 15) len_inter = 15-decimals; - double r = 0; - for (int i=0; i. - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "GdaConst.h" - -#ifndef __GEODA_CENTER_DBF_FILE_H__ -#define __GEODA_CENTER_DBF_FILE_H__ - -struct DbfFieldDesc -{ - wxString name; // 10 ASCII character string (with 11th char as 0x00). - char type; // either C, D, F or N - int length; // unsigned 8-bit <= 255 - int decimals; // unsigned 8-bit <= 15 -}; - -struct DbfFileHeader -{ - char version; // 8-bit bitmask in DBF - int year; // unsigned 8 bits little endian in DBF (-1900) - int month; // unsigned 8 bits little endian in DBF - int day; // unsigned 8 bits little endian in DBF - wxUint32 num_records; // unsigned 32 bits little endian in DBF - int header_length; // unsigned 16 bits little endian in DBF - int length_each_record; // unsigned 16 bits little endian in DBF - int num_fields; // calculated -}; - -class DbfFileReader -{ - public: - DbfFileReader(const wxString& filename); - virtual ~DbfFileReader(); - bool isDbfReadSuccess(); - DbfFileHeader getFileHeader(); - std::vector getFieldDescs(); - DbfFieldDesc getFieldDesc(int field); - DbfFieldDesc getFieldDesc(const wxString& f_name); - void getFieldTypes(std::map& field_type_map); - void getFieldList(std::vector& field_list); - bool getFieldValsLong(int field, std::vector& vals); - bool getFieldValsLong(const wxString& f_name, std::vector& vals); - bool getFieldValsDouble(int field, std::vector& vals); - bool getFieldValsDouble(const wxString& f_name, std::vector& vals); - bool getFieldValsString(int field, std::vector& vals); - int getNumFields() const { return header.num_fields; } - int getNumRecords() const { return header.num_records; } - void printFileHeader(wxTextOutputStream& outstrm); - void printFieldDesc(int field, wxTextOutputStream& outstrm); - void printFieldValues(int field, wxTextOutputStream& outstrm); - bool isFieldExists(int field); - bool isFieldExists(const wxString& f_name); - bool isFieldValUnique(int field); - bool isFieldValUnique(const wxString& f_name); - wxString getFileName() { return fname; } - -private: - bool populateHeader(); - bool populateFieldDescs(); - bool read_success; - -public: - std::ifstream file; - wxString fname; - std::vector fields; - DbfFileHeader header; - static const int MAX_NUMBER_FIELDS; -}; - -namespace DbfFileUtils -{ - bool insertIdFieldDbf(const wxString& in_fname, - const wxString& out_fname, - const wxString& id_fld_name, - int id_fld_pos, - wxString& err_msg); - bool isValidFieldName(const wxString& n); - bool isAlphabetic(const wxString& n); // looks at first char in string - bool isDigit(const wxString& n); // looks at first char in string - bool isAlphaNum(const wxString& n); // looks at first char in string - int getNumRecords(const wxString& fname); - int getNumFields(const wxString& fname); - wxInt64 GetMaxInt(int length); - wxString GetMaxIntString(int length); - wxInt64 GetMinInt(int length); - wxString GetMinIntString(int length); - void SuggestDoubleParams(int length, int decimals, - int* suggest_len, int* suggest_dec); - double GetMaxDouble(int length, int decimals, - int* suggest_len=0, int* suggest_dec=0); - wxString GetMaxDoubleString(int length, int decimals); - double GetMinDouble(int length, int decimals, - int* suggest_len=0, int* suggest_dec=0); - wxString GetMinDoubleString(int length, int decimals); - void strToInt64(const char *str, wxInt64 *val); -} - -#endif diff --git a/DialogTools/3DControlPan.cpp b/DialogTools/3DControlPan.cpp index dd162a918..cd2d256c0 100644 --- a/DialogTools/3DControlPan.cpp +++ b/DialogTools/3DControlPan.cpp @@ -127,7 +127,7 @@ void C3DControlPan::CreateControls() m_select = XRCCTRL(*this, "IDC_SELECT", wxCheckBox); if ( GeneralWxUtils::isMac() ) { // change "CTRL" in label to "CMD" in label. - m_select->SetLabel("Select, hold CMD for brushing"); + m_select->SetLabel(_("Select, hold CMD for brushing")); } m_static_text_x = XRCCTRL(*this, "ID_3D_STATICTEXT_X", wxStaticText); m_static_text_y = XRCCTRL(*this, "ID_3D_STATICTEXT_Y", wxStaticText); diff --git a/DialogTools/ASC2SHPDlg.cpp b/DialogTools/ASC2SHPDlg.cpp deleted file mode 100644 index d249faef9..000000000 --- a/DialogTools/ASC2SHPDlg.cpp +++ /dev/null @@ -1,481 +0,0 @@ -/** - * GeoDa TM, Copyright (C) 2011-2015 by Luc Anselin - all rights reserved - * - * This file is part of GeoDa. - * - * GeoDa is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * GeoDa is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -#include -// For compilers that support precompilation, includes . -#include - -#ifndef WX_PRECOMP -#include -#endif - -#include -#include "../GenUtils.h" -#include "../ShapeOperations/AbstractShape.h" -#include "../ShapeOperations/SimplePoint.h" -#include "../ShapeOperations/ShapeFileTriplet.h" -#include "ASC2SHPDlg.h" - -typedef struct dpoint_stru { - double x,y; -} DPOINT; - -typedef struct Box_stru { - DPOINT p1; - DPOINT p2; -} myBox; - -bool CreatePointShapeFile(char* otfl, // Target File name - const int nPoint, // Number of point or records - double *x, // x-coordinates vector - double *y) // y-ccordinates vector - -{ - - //Do we really need this code? - DPOINT pp1, pp2; - double min1_x, min1_y, max1_x, max1_y; - min1_x = 1e255; - min1_y = 1e255; - max1_x = -1e255; - max1_y = -1e255; - - double xv,yv; - - for(int rec1=0; rec1 max1_x) - max1_x = xv; - if(yv > max1_y) - max1_y = yv; - } - - pp1.x = min1_x; - pp1.y = min1_y; - pp2.x = max1_x; - pp2.y = max1_y; - - myBox myfBox; - myfBox.p1 = pp1; - myfBox.p2 = pp2; - //////////////////////////////// - // Declare the bounding box as Box class object - BasePoint p1(myfBox.p1.x,myfBox.p1.y); - BasePoint p2(myfBox.p2.x,myfBox.p2.y); - Box xoBox(p1,p2); - - // Declare the triplet (the .shp, .shx, .dbf) as oShapeFileTriplet class object - oShapeFileTriplet Triple(otfl,xoBox, "POLY", ShapeFileTypes::SPOINT); - // Allocate a pointer of AbstractShape to manage the point Shapefile - AbstractShape* shape = new SimplePoint; - - // store the point dataset into the triplet and - // at the same time re-evaluate the bounding box according to - // the dataset - - double max_x=x[0], max_y=y[0], min_x=x[0], min_y=y[0]; - - for (long rec=0; rec < nPoint; rec++) { - shape->AssignPointData(x[rec],y[rec]); - Triple << *shape; - if (max_x < x[rec]) max_x = x[rec]; - if (min_x > x[rec]) min_x = x[rec]; - if (max_y < y[rec]) max_y = y[rec]; - if (min_y > y[rec]) min_y = y[rec]; - } - - // Update (to make wider) the bounding box by delta_x and and delta_y - double delta_x = (max_x - min_x)/20; - double delta_y = (max_y - min_y)/20; - - min_x = min_x - delta_x; - min_y = min_y - delta_y; - max_x = max_x + delta_x; - max_y = max_y + delta_y; - - BasePoint a(min_x,min_y); - BasePoint b(max_x,max_y); - Box fBox(a,b); - - // Update the bounding box - Triple.SetFileBox(fBox); - Triple.CloseTriplet(); - - delete shape; - shape = NULL; - - return true; -} - - -BEGIN_EVENT_TABLE( ASC2SHPDlg, wxDialog ) - EVT_BUTTON( XRCID("IDOK_ADD"), ASC2SHPDlg::OnOkAddClick ) - EVT_BUTTON( XRCID("IDC_OPEN_IASC"), ASC2SHPDlg::OnCOpenIascClick ) - EVT_BUTTON( XRCID("IDC_OPEN_OSHP"), ASC2SHPDlg::OnCOpenOshpClick ) - EVT_BUTTON( XRCID("IDCANCEL"), ASC2SHPDlg::OnCancelClick ) -END_EVENT_TABLE() - -ASC2SHPDlg::ASC2SHPDlg( ) -{ -} - -ASC2SHPDlg::ASC2SHPDlg( wxWindow* parent, wxWindowID id, - const wxString& caption, const wxPoint& pos, - const wxSize& size, long style ) -{ - Create(parent, id, caption, pos, size, style); - - FindWindow(XRCID("IDC_OPEN_OSHP"))->Enable(false); - FindWindow(XRCID("IDC_FIELD_SHP"))->Enable(false); - FindWindow(XRCID("IDC_KEYVAR"))->Enable(false); - FindWindow(XRCID("IDC_KEYVAR2"))->Enable(false); - FindWindow(XRCID("IDOK_ADD"))->Enable(false); -} - -bool ASC2SHPDlg::Create( wxWindow* parent, wxWindowID id, - const wxString& caption, const wxPoint& pos, - const wxSize& size, long style ) -{ - SetParent(parent); - CreateControls(); - Centre(); - - return true; -} - -void ASC2SHPDlg::CreateControls() -{ - wxXmlResource::Get()->LoadDialog(this, GetParent(), "IDD_CONVERT_ASC2SHP"); - m_inputfile = XRCCTRL(*this, "IDC_FIELD_ASC", wxTextCtrl); - m_inputfile->SetMaxLength(0); - m_outputfile = XRCCTRL(*this, "IDC_FIELD_SHP", wxTextCtrl); - m_outputfile->SetMaxLength(0); - m_X = XRCCTRL(*this, "IDC_KEYVAR", wxChoice); - m_Y = XRCCTRL(*this, "IDC_KEYVAR2", wxChoice); -} - -void ASC2SHPDlg::OnOkAddClick( wxCommandEvent& event ) -{ - wxLogMessage("In ASC2SHPDlg::OnOkAddClick()"); - - wxString m_iASC = m_inputfile->GetValue(); - wxString m_oSHP = m_outputfile->GetValue(); - int idx_x = m_X->GetSelection(); - int idx_y = m_Y->GetSelection(); - std::ifstream ias; - ias.open(GET_ENCODED_FILENAME(m_iASC)); - int n_recs; - int n_fields; - - // FORMAT: Line-1 - char name[10000]; - ias.getline(name,100); - sscanf(name,"%d,%d",&n_recs, &n_fields); - - if( (n_recs <= 0) || (n_fields < 2) ) { - wxString msg = _("Number of columns has to be more than 2. \nAt least it includes ID,X-Coord, and Y-Coord!"); - wxMessageBox(msg); - return; - } - - // FORMAT: Line-2 - ias.getline(name,10000); - - wxString tok = wxString(name, wxConvUTF8); - //wxString tok = wxString::Format("%10000",name); - wxString t; - - - DBF_descr *dbfdesc; - dbfdesc = new DBF_descr [n_fields]; - //char* tok_c; - - int i = 0, j = 0; - for(i=0; i= 0) - { - wxString tok_left = tok.Left(pos); - j = tok_left.Find('\"'); - while (j >= 0) - { - t = tok_left.Left(j); - tok_left = t + tok_left.Right(tok_left.Length() - j - 1); - j = tok_left.Find('\"'); - } - - dbfdesc[i] = new DBF_field(tok_left, 'N', 20, 9); - tok = tok.Right(tok.Length()-pos-1); - } - else - { - wxString msg = _("Error: there was a problem reading the field names from the text file."); - wxMessageBox(msg); - return; - } - } - j = tok.Find('\"'); - while (j >= 0) - { - t = tok.Left(j); - tok = t + tok.Right(tok.Length() - j - 1); - j = tok.Find('\"'); - } - - dbfdesc[i] = new DBF_field(tok, 'N', 20, 9); - dbfdesc[0]->Precision = 0; - - double *x,*y; - x = new double[n_recs]; - y = new double[n_recs]; - - double *buff; - buff = new double[n_recs*n_fields]; - - int row = 0, col = 0; - for(row=0; row = 0) - { - wxString tok_left = tok.Left(pos); - if(idx_x == col) - { - tok.ToCDouble(&x[row]); - } - if(idx_y == col) - { - tok.ToCDouble(&y[row]); - } - tok.ToCDouble(&buff[row*n_fields+col]); - - tok = tok.Right(tok.Length()-pos-1); - } - else - { - wxMessageBox(_("Error: Wrong format.")); - delete [] x; x = NULL; - delete [] y; y = NULL; - delete [] buff; buff = NULL; - delete [] dbfdesc; dbfdesc = NULL; - return; - } - } - - if(idx_x == n_fields-1) - { - tok.ToCDouble(&x[row]); - } - if(idx_y == n_fields-1) - { - tok.ToCDouble(&y[row]); - } - tok.ToCDouble(&buff[row*n_fields+col]); - - } - - char buf[512]; - strcpy( buf, (const char*)m_oSHP.mb_str(wxConvUTF8) ); - - CreatePointShapeFile(buf, n_recs, x, y); - - wxString strResult = m_oSHP; - wxString DirName; - - int pos = strResult.Find('.', true); - if (pos >= 0) - DirName = strResult.Left(pos); - else - DirName = strResult; - - DirName = DirName+ ".dbf"; - - oDBF odbf(DirName, dbfdesc, n_recs, n_fields); - - if(odbf.fail) - { - wxMessageBox(_("Can't open output file!")); - - delete [] x; - x = NULL; - delete [] y; - y = NULL; - delete [] buff; - buff = NULL; - delete [] dbfdesc; - dbfdesc = NULL; - return; - } - - for(row=0; rowSetValue(InFile); - wxString m_iASC = m_path; - - fn = dlg.GetFilename(); - int pos = fn.Find('.', true); - if (pos >= 0) fn = fn.Left(pos); - - m_X->Clear(); - m_Y->Clear(); - - ifstream ias; - ias.open(GET_ENCODED_FILENAME(m_iASC)); - - int n_recs; - int n_fields; - - char name[1000]; - - ias.getline(name,100); - sscanf(name,"%d,%d",&n_recs, &n_fields); - - if( (n_recs <= 0) ) { - wxString msg = _("Error: number of records must be > 0."); - wxMessageBox(msg); - } - - if( (n_fields <= 2) ) { - wxString msg = _("Error: number of fields must be > 2."); - wxMessageBox(msg); - } - - ias.getline(name,1000); - - wxString tok, t, k; - tok = wxString(name, wxConvUTF8); - int i = 0, j = 0; - for(i=0; i= 0) - { - t = tok.Left(pos); - j = t.Find('\"'); - while (j >= 0) - { - k = t.Left(j); - t = k + t.Right(t.Length() - j - 1); - j = t.Find('\"'); - } - m_X->Append(t); - m_Y->Append(t); - tok = tok.Right(tok.Length()-pos-1); - } - else - { - m_X->Clear(); - m_Y->Clear(); - wxMessageBox(_("Error: field names listed in wrong format.")); - return; - } - } - - t = tok; - j = t.Find('\"'); - while (j >= 0) - { - k = t.Left(j); - t = k + t.Right(t.Length() - j - 1); - j = t.Find('\"'); - } - m_X->Append(t); - m_Y->Append(t); - - m_X->SetSelection(0); - m_Y->SetSelection(0); - - FindWindow(XRCID("IDC_OPEN_OSHP"))->Enable(true); - FindWindow(XRCID("IDC_FIELD_SHP"))->Enable(true); - FindWindow(XRCID("IDC_KEYVAR"))->Enable(true); - FindWindow(XRCID("IDC_KEYVAR2"))->Enable(true); - } -} - -void ASC2SHPDlg::OnCOpenOshpClick( wxCommandEvent& event ) -{ - wxLogMessage("In ASC2SHPDlg::OnCOpenOshpClick()"); - wxFileDialog dlg(this, _("Output Shp file"), wxEmptyString, fn + ".shp", - "Shp files (*.shp)|*.shp", - wxFD_SAVE | wxFD_OVERWRITE_PROMPT); - - - wxString m_path = wxEmptyString; - - if (dlg.ShowModal() == wxID_OK) { - m_path = dlg.GetPath(); - wxString OutFile = m_path; - m_outputfile->SetValue(OutFile); - FindWindow(XRCID("IDOK_ADD"))->Enable(true); - } -} - -void ASC2SHPDlg::OnCancelClick( wxCommandEvent& event ) -{ - wxLogMessage("In ASC2SHPDlg::OnCancelClick()"); - event.Skip(); - EndDialog(wxID_CANCEL); -} diff --git a/DialogTools/ASC2SHPDlg.h b/DialogTools/ASC2SHPDlg.h deleted file mode 100644 index ebc3fdcee..000000000 --- a/DialogTools/ASC2SHPDlg.h +++ /dev/null @@ -1,55 +0,0 @@ -/** - * GeoDa TM, Copyright (C) 2011-2015 by Luc Anselin - all rights reserved - * - * This file is part of GeoDa. - * - * GeoDa is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * GeoDa is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -#ifndef __GEODA_CENTER_ASC2SHP_DLG_H__ -#define __GEODA_CENTER_ASC2SHP_DLG_H__ - -class ASC2SHPDlg: public wxDialog -{ - DECLARE_EVENT_TABLE() - -public: - ASC2SHPDlg( ); - ASC2SHPDlg( wxWindow* parent, wxWindowID id = -1, - const wxString& caption = _("Convert ASCII to SHP"), - const wxPoint& pos = wxDefaultPosition, - const wxSize& size = wxDefaultSize, - long style = wxCAPTION|wxDEFAULT_DIALOG_STYLE ); - bool Create( wxWindow* parent, wxWindowID id = -1, - const wxString& caption = _("Convert ASCII to SHP"), - const wxPoint& pos = wxDefaultPosition, - const wxSize& size = wxDefaultSize, - long style = wxCAPTION|wxDEFAULT_DIALOG_STYLE ); - void CreateControls(); - - void OnOkAddClick( wxCommandEvent& event ); - void OnCOpenIascClick( wxCommandEvent& event ); - void OnCOpenOshpClick( wxCommandEvent& event ); - void OnCancelClick( wxCommandEvent& event ); - - wxTextCtrl* m_inputfile; - wxTextCtrl* m_outputfile; - wxChoice* m_X; - wxChoice* m_Y; - - wxString fn; -}; - -#endif - diff --git a/DialogTools/AbstractClusterDlg.cpp b/DialogTools/AbstractClusterDlg.cpp new file mode 100644 index 000000000..f958380f2 --- /dev/null +++ b/DialogTools/AbstractClusterDlg.cpp @@ -0,0 +1,936 @@ +/** + * GeoDa TM, Copyright (C) 2011-2015 by Luc Anselin - all rights reserved + * + * This file is part of GeoDa. + * + * GeoDa is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * GeoDa is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../ShapeOperations/PolysToContigWeights.h" +#include "../Algorithms/texttable.h" +#include "../Project.h" +#include "../GeneralWxUtils.h" +#include "../GenUtils.h" +#include "SaveToTableDlg.h" +#include "AbstractClusterDlg.h" + + +AbstractClusterDlg::AbstractClusterDlg(wxFrame* parent_s, Project* project_s, wxString title) +: frames_manager(project_s->GetFramesManager()), table_state(project_s->GetTableState()), +wxDialog(NULL, -1, title, wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE|wxRESIZE_BORDER), +validator(wxFILTER_INCLUDE_CHAR_LIST), input_data(NULL), mask(NULL), weight(NULL), m_use_centroids(NULL), m_weight_centroids(NULL), m_wc_txt(NULL), chk_floor(NULL), combo_floor(NULL), txt_floor(NULL), txt_floor_pct(NULL), slider_floor(NULL), combo_var(NULL), m_reportbox(NULL), gal(NULL) +{ + wxLogMessage("Open AbstractClusterDlg."); + + wxArrayString list; + wxString valid_chars(".0123456789"); + size_t len = valid_chars.Length(); + for (size_t i=0; iGetTableInt()->GetNumberCols() == 0) { + wxString err_msg = _("No numeric variables found in table."); + wxMessageDialog dlg(NULL, err_msg, _("Warning"), wxOK | wxICON_ERROR); + dlg.ShowModal(); + EndDialog(wxID_CANCEL); + } + bool init_success = Init(); + + if (init_success == false) { + EndDialog(wxID_CANCEL); + } + frames_manager->registerObserver(this); + table_state->registerObserver(this); +} + +AbstractClusterDlg::~AbstractClusterDlg() +{ + CleanData(); + frames_manager->removeObserver(this); + table_state->removeObserver(this); +} + +void AbstractClusterDlg::CleanData() +{ + if (input_data) { + for (int i=0; iGetTableInt(); + if (table_int == NULL) + return false; + + num_obs = project->GetNumRecords(); + table_int->GetTimeStrings(tm_strs); + + return true; +} + +void AbstractClusterDlg::update(FramesManager* o) +{ +} + +void AbstractClusterDlg::update(TableState* o) +{ + InitVariableCombobox(combo_var); +} + +bool AbstractClusterDlg::GetDefaultContiguity() +{ + if (gal== NULL) { + bool is_queen = true; + gal = PolysToContigWeights(project->main_data, is_queen); + } + return gal != NULL; +} + +bool AbstractClusterDlg::CheckConnectivity(GalWeight* gw) +{ + if (num_obs == 0 || gw == NULL) return false; + + GalElement* W = gw->gal; + if (W == NULL) return false; + + // start from first node in W + if (W[0].Size() == 0) return false; + + std::map access_dict; // prevent loop + access_dict[0] = true; + + std::list magzine; + for (int i=0; iAdd(st, 0, wxALIGN_CENTER | wxLEFT | wxRIGHT, 10); + hbox0->Add(combo_var, 1, wxEXPAND | wxLEFT | wxRIGHT | wxBOTTOM, 10); + + wxStaticText* note_st = new wxStaticText(panel, wxID_ANY, + _("(Please note: Only supported for smaller datasets.)"), + wxDefaultPosition, wxDefaultSize); + vbox->Add(note_st, 0, wxEXPAND | wxALL, 10); + vbox->Add(hbox0, 1, wxEXPAND | wxTOP | wxLEFT, 10); +} + +void AbstractClusterDlg::AddInputCtrls(wxPanel *panel, wxBoxSizer* vbox, bool show_auto_button) +{ + wxStaticText* st = new wxStaticText (panel, wxID_ANY, _("Select Variables"), + wxDefaultPosition, wxDefaultSize); + + combo_var = new wxListBox(panel, wxID_ANY, wxDefaultPosition, wxSize(250,250), 0, NULL, + wxLB_MULTIPLE | wxLB_HSCROLL| wxLB_NEEDED_SB); + InitVariableCombobox(combo_var); + + m_use_centroids = new wxCheckBox(panel, wxID_ANY, _("Use geometric centroids")); + auto_btn = new wxButton(panel, wxID_OK, _("Auto Weighting")); + auto_btn->Bind(wxEVT_BUTTON, &AbstractClusterDlg::OnAutoWeightCentroids, this); + if (!show_auto_button) auto_btn->Hide(); + wxBoxSizer *hbox_c = new wxBoxSizer(wxHORIZONTAL); + hbox_c->Add(m_use_centroids, 0); + hbox_c->Add(auto_btn, 0); + + wxStaticText* st_wc = new wxStaticText (panel, wxID_ANY, _("Weighting:"), wxDefaultPosition, wxDefaultSize); + wxStaticText* st_w0 = new wxStaticText (panel, wxID_ANY, "0"); + wxStaticText* st_w1 = new wxStaticText (panel, wxID_ANY, "1"); + m_weight_centroids = new wxSlider(panel, wxID_ANY, 100, 0, 100, wxDefaultPosition, wxSize(140, -1), wxSL_HORIZONTAL); + m_wc_txt = new wxTextCtrl(panel, wxID_ANY, "1", wxDefaultPosition, wxSize(40,-1), 0, validator); + wxBoxSizer *hbox_w = new wxBoxSizer(wxHORIZONTAL); + hbox_w->Add(st_wc, 0, wxLEFT, 20); + hbox_w->Add(st_w0, 0, wxALIGN_CENTER_VERTICAL|wxLEFT, 5); + hbox_w->Add(m_weight_centroids, 0, wxEXPAND); + hbox_w->Add(st_w1, 0, wxALIGN_CENTER_VERTICAL); + hbox_w->Add(m_wc_txt, 0, wxALIGN_TOP|wxLEFT, 5); + + + wxStaticBoxSizer *hbox0 = new wxStaticBoxSizer(wxVERTICAL, panel, _("Input:")); + hbox0->Add(st, 0, wxALIGN_CENTER | wxLEFT | wxRIGHT, 10); + hbox0->Add(combo_var, 1, wxEXPAND | wxLEFT | wxRIGHT | wxBOTTOM, 10); + hbox0->Add(hbox_c, 0, wxLEFT | wxRIGHT, 10); + hbox0->Add(hbox_w, 0, wxLEFT | wxRIGHT, 10); + + + wxStaticText* note_st = new wxStaticText (panel, wxID_ANY, + _("(Please note: Only supported for smaller datasets.)"), + wxDefaultPosition, wxDefaultSize); + vbox->Add(note_st, 0, wxEXPAND | wxALL, 10); + vbox->Add(hbox0, 1, wxEXPAND | wxALL, 10); + + if (project->IsTableOnlyProject()) { + m_use_centroids->Disable(); + } + m_weight_centroids->Disable(); + m_wc_txt->Disable(); + auto_btn->Disable(); + m_use_centroids->Bind(wxEVT_CHECKBOX, &AbstractClusterDlg::OnUseCentroids, this); + m_weight_centroids->Bind(wxEVT_SLIDER, &AbstractClusterDlg::OnSlideWeight, this); + m_wc_txt->Bind(wxEVT_TEXT, &AbstractClusterDlg::OnInputWeights, this); +} + +void AbstractClusterDlg::OnInputWeights(wxCommandEvent& ev) +{ + wxString val = m_wc_txt->GetValue(); + double w_val; + if (val.ToDouble(&w_val)) { + m_weight_centroids->SetValue(w_val * 100); + } +} + +void AbstractClusterDlg::OnSlideWeight(wxCommandEvent& ev) +{ + int val = m_weight_centroids->GetValue(); + wxString t_val = wxString::Format("%.2f", val/100.0); + m_wc_txt->SetValue(t_val); +} + +void AbstractClusterDlg::OnUseCentroids(wxCommandEvent& event) +{ + if (m_use_centroids->IsChecked()) { + m_weight_centroids->Enable(); + m_weight_centroids->SetValue(100); + m_wc_txt->SetValue("1.00"); + m_wc_txt->Enable(); + auto_btn->Enable(); + } else { + m_weight_centroids->SetValue(false); + m_weight_centroids->Disable(); + m_wc_txt->SetValue("0.00"); + m_wc_txt->Disable(); + auto_btn->Disable(); + } +} + +void AbstractClusterDlg::OnAutoWeightCentroids(wxCommandEvent& event) +{ +} + +void AbstractClusterDlg::AddTransformation(wxPanel *panel, wxFlexGridSizer* gbox) +{ + wxStaticText* st14 = new wxStaticText(panel, wxID_ANY, _("Transformation:"), wxDefaultPosition, wxSize(120,-1)); + const wxString _transform[4] = {"Raw", "Demean", "Standardize (Z)", "Standardize (MAD)"}; + combo_tranform = new wxChoice(panel, wxID_ANY, wxDefaultPosition, + wxSize(120,-1), 4, _transform); + combo_tranform->SetSelection(2); + gbox->Add(st14, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT | wxLEFT, 10); + gbox->Add(combo_tranform, 1, wxEXPAND); +} + +void AbstractClusterDlg::AddMinBound(wxPanel *panel, wxFlexGridSizer* gbox, bool show_checkbox) +{ + wxStaticText* st = new wxStaticText(panel, wxID_ANY, _("Minimum Bound:"), wxDefaultPosition, wxSize(128,-1)); + + wxBoxSizer *hbox0 = new wxBoxSizer(wxHORIZONTAL); + chk_floor = new wxCheckBox(panel, wxID_ANY, ""); + combo_floor = new wxChoice(panel, wxID_ANY, wxDefaultPosition, wxSize(128,-1), var_items); + txt_floor = new wxTextCtrl(panel, wxID_ANY, "1", wxDefaultPosition, wxSize(70,-1), 0, validator); + hbox0->Add(chk_floor); + hbox0->Add(combo_floor); + hbox0->Add(txt_floor); + + wxBoxSizer *hbox1 = new wxBoxSizer(wxHORIZONTAL); + slider_floor = new wxSlider(panel, wxID_ANY, 10, 0, 100, wxDefaultPosition, wxSize(150,-1), wxSL_HORIZONTAL); + txt_floor_pct = new wxTextCtrl(panel, wxID_ANY, "10%", wxDefaultPosition, wxSize(70,-1), 0, validator); + hbox1->Add(slider_floor); + hbox1->Add(txt_floor_pct); + + wxBoxSizer *hbox = new wxBoxSizer(wxVERTICAL); + hbox->Add(hbox0); + hbox->Add(hbox1); + + gbox->Add(st, 0, wxALIGN_TOP| wxRIGHT | wxLEFT, 10); + gbox->Add(hbox, 1, wxEXPAND); + + chk_floor->Bind(wxEVT_CHECKBOX, &AbstractClusterDlg::OnCheckMinBound, this); + combo_floor->Bind(wxEVT_CHOICE, &AbstractClusterDlg::OnSelMinBound, this); + txt_floor->Bind(wxEVT_TEXT, &AbstractClusterDlg::OnTypeMinBound, this); + slider_floor->Bind(wxEVT_SLIDER, &AbstractClusterDlg::OnSlideMinBound, this); + + if (!show_checkbox) { + chk_floor->SetValue(true); + chk_floor->Hide(); + combo_floor->SetSelection(-1); + } else { + combo_floor->Disable(); + txt_floor->Disable(); + } + slider_floor->Disable(); + txt_floor_pct->Disable(); + +} +void AbstractClusterDlg::OnSlideMinBound(wxCommandEvent& event) +{ + int idx = combo_floor->GetSelection(); + if (idx >= 0) { + int val = slider_floor->GetValue(); + wxString t_val = wxString::Format("%d%%", val); + txt_floor_pct->SetValue(t_val); + + if (idx_sum.find(idx) != idx_sum.end()) { + double slide_val = (val / 100.0) * idx_sum[idx]; + wxString str_val; + str_val << slide_val; + txt_floor->SetValue(str_val); + } + } +} +void AbstractClusterDlg::OnCheckMinBound(wxCommandEvent& event) +{ + if (chk_floor->IsChecked() ) { + combo_floor->Enable(); + txt_floor->Enable(); + combo_floor->SetSelection(-1); + txt_floor->SetValue(""); + } else { + combo_floor->Disable(); + txt_floor->Disable(); + slider_floor->Disable(); + txt_floor_pct->Disable(); + combo_floor->SetSelection(-1); + txt_floor->SetValue(""); + } +} +void AbstractClusterDlg::OnSelMinBound(wxCommandEvent& event) +{ + int rows = project->GetNumRecords(); + int idx = combo_floor->GetSelection(); + if (idx >= 0) { + slider_floor->Enable(); + txt_floor_pct->Enable(); + + vector floor_variable(rows, 1); + wxString nm = name_to_nm[combo_floor->GetString(idx)]; + int col = table_int->FindColId(nm); + if (col == wxNOT_FOUND) { + wxString err_msg = wxString::Format(_("Variable %s is no longer in the Table. Please close and reopen this dialog to synchronize with Table data."), nm); + wxMessageDialog dlg(NULL, err_msg, _("Error"), wxOK | wxICON_ERROR); + dlg.ShowModal(); + return; + } + int tm = name_to_tm_id[combo_floor->GetString(idx)]; + table_int->GetColData(col, tm, floor_variable); + // 10% as default to txt_floor + double sum = 0; + for (int i=0; iSetValue(str_suggest); + slider_floor->SetValue(10); + txt_floor_pct->SetValue("10%"); + } else { + slider_floor->Disable(); + txt_floor_pct->Disable(); + slider_floor->SetValue(10); + txt_floor_pct->SetValue("10%"); + } +} +void AbstractClusterDlg::OnTypeMinBound(wxCommandEvent& event) +{ + wxString tmp_val = txt_floor->GetValue(); + tmp_val.Trim(false); + tmp_val.Trim(true); + long input_min_k; + bool is_valid = tmp_val.ToLong(&input_min_k); + if (is_valid) { + } +} +bool AbstractClusterDlg::CheckMinBound() +{ + if (chk_floor->IsChecked()) { + if (combo_floor->GetSelection() < 0 || txt_floor->GetValue().Trim() == wxEmptyString) { + wxString err_msg = _("Please input minimum bound value."); + wxMessageDialog dlg(NULL, err_msg, _("Error"), wxOK | wxICON_ERROR); + dlg.ShowModal(); + return false; + } + } + return true; +} + +void AbstractClusterDlg::InitVariableCombobox(wxListBox* var_box, bool integer_only) +{ + combo_var->Clear(); + var_items.Clear(); + + std::vector col_id_map; + if (integer_only) table_int->FillIntegerColIdMap(col_id_map); + else table_int->FillNumericColIdMap(col_id_map); + for (int i=0, iend=col_id_map.size(); iGetColName(id); + if (table_int->IsColTimeVariant(id)) { + for (int t=0; tGetColTimeSteps(id); t++) { + wxString nm = name; + nm << " (" << table_int->GetTimeString(t) << ")"; + name_to_nm[nm] = name; + name_to_tm_id[nm] = t; + var_items.Add(nm); + } + } else { + name_to_nm[name] = name; + name_to_tm_id[name] = 0; + var_items.Add(name); + } + } + if (!var_items.IsEmpty()) + var_box->InsertItems(var_items,0); + + for (int i=0; iSetStringSelection(select_vars[i], true); + } +} + +bool AbstractClusterDlg::GetInputData(int transform, int min_num_var) +{ + CleanData(); + + bool use_centroids = false; + + if (m_use_centroids) use_centroids = m_use_centroids->GetValue(); + + if (use_centroids && m_weight_centroids) { + if (m_weight_centroids->GetValue() == 0) use_centroids = false; + } + + wxArrayInt selections; + combo_var->GetSelections(selections); + + int num_var = selections.size(); + if (num_var < min_num_var && !use_centroids) { + wxString err_msg = wxString::Format(_("Please select at least %d variables."), min_num_var); + wxMessageDialog dlg(NULL, err_msg, _("Info"), wxOK | wxICON_ERROR); + dlg.ShowModal(); + return false; + } + + col_names.clear(); + select_vars.clear(); + + if ((!use_centroids && num_var>0) || (use_centroids && m_weight_centroids && m_weight_centroids->GetValue() != 1)) + { + col_ids.resize(num_var); + var_info.resize(num_var); + + for (int i=0; iGetString(idx); + select_vars.push_back(sel_str); + + wxString nm = name_to_nm[sel_str]; + + int col = table_int->FindColId(nm); + if (col == wxNOT_FOUND) { + wxString err_msg = wxString::Format(_("Variable %s is no longer in the Table. Please close and reopen this dialog to synchronize with Table data."), nm); + wxMessageDialog dlg(NULL, err_msg, _("Error"), wxOK | wxICON_ERROR); + dlg.ShowModal(); + return false; + } + + int tm = name_to_tm_id[combo_var->GetString(idx)]; + col_names.push_back(nm); + + col_ids[i] = col; + var_info[i].time = tm; + + // Set Primary GdaVarTools::VarInfo attributes + var_info[i].name = nm; + var_info[i].is_time_variant = table_int->IsColTimeVariant(nm); + + // var_info[i].time already set above + table_int->GetMinMaxVals(col_ids[i], var_info[i].min, var_info[i].max); + var_info[i].sync_with_global_time = var_info[i].is_time_variant; + var_info[i].fixed_scale = true; + } + + // Call function to set all Secondary Attributes based on Primary Attributes + GdaVarTools::UpdateVarInfoSecondaryAttribs(var_info); + + rows = project->GetNumRecords(); + columns = 0; + + std::vector data; + data.resize(col_ids.size()); // data[variable][time][obs] + for (int i=0; iGetColData(col_ids[i], data[i]); + } + + // if use centroids + if (use_centroids) { + columns += 2; + col_names.insert(col_names.begin(), "CENTY"); + col_names.insert(col_names.begin(), "CENTX"); + } + + // get columns (time variables always show upgrouped) + columns += data.size(); + + if (m_weight_centroids && m_use_centroids) + weight = GetWeights(columns); + else { + weight = new double[columns]; + for (int j=0; j cents = project->GetCentroids(); + std::vector cent_xs; + std::vector cent_ys; + for (int i=0; i< rows; i++) { + cent_xs.push_back(cents[i]->GetX()); + cent_ys.push_back(cents[i]->GetY()); + } + if (transform == 3) { + GenUtils::MeanAbsoluteDeviation(cent_xs); + GenUtils::MeanAbsoluteDeviation(cent_ys); + } else if (transform == 2) { + GenUtils::StandardizeData(cent_xs ); + GenUtils::StandardizeData(cent_ys ); + } else if (transform == 1 ) { + GenUtils::DeviationFromMean(cent_xs ); + GenUtils::DeviationFromMean(cent_ys ); + } + for (int i=0; i< rows; i++) { + input_data[i][col_ii + 0] = cent_xs[i]; + input_data[i][col_ii + 1] = cent_ys[i]; + } + col_ii = 2; + } + for (int i=0; i vals; + int c_t = 0; + if (var_info[i].is_time_variant) { + c_t = var_info[i].time; + } + for (int k=0; k< rows;k++) { // row + vals.push_back(data[i][c_t][k]); + } + if (transform == 3) { + GenUtils::MeanAbsoluteDeviation(vals); + } else if (transform == 2) { + GenUtils::StandardizeData(vals); + } else if (transform == 1 ) { + GenUtils::DeviationFromMean(vals); + } + for (int k=0; k< rows;k++) { // row + input_data[k][col_ii] = vals[k]; + } + col_ii += 1; + } + return true; + } + return false; +} + +double* AbstractClusterDlg::GetWeights(int columns) +{ + double* weight = new double[columns]; + double wc = 1; + for (int j=0; jGetValue() > 0 && m_use_centroids->IsChecked() ) { + double sel_wc = m_weight_centroids->GetValue(); + wc = sel_wc / 100.0; + double n_var_cols = (double)(columns - 2); + for (int j=0; jIsChecked() && combo_floor->GetSelection()>-1) { + wxString tmp_val = txt_floor->GetValue(); + tmp_val.ToDouble(&bound); + } + return bound; +} + +double* AbstractClusterDlg::GetBoundVals() +{ + int rows = project->GetNumRecords(); + int idx = combo_floor->GetSelection(); + double* vals = NULL; + if (chk_floor->IsChecked() && idx >= 0) { + vals = new double[rows]; + wxString nm = name_to_nm[combo_floor->GetString(idx)]; + int col = table_int->FindColId(nm); + if (col != wxNOT_FOUND) { + vector floor_variable(rows, 1); + int tm = name_to_tm_id[combo_floor->GetString(idx)]; + table_int->GetColData(col, tm, floor_variable); + for (int i=0; iAddPage(m_reportbox, _("Summary")); + return notebook; +} + + +//////////////////////////////////////////////////////////////// +// +// Clustering Stats +// +//////////////////////////////////////////////////////////////// + +double AbstractClusterDlg::CreateSummary(const vector& clusters, bool show_print) +{ + vector > solution; + vector isolated; + for (int i=0; i solution.size()) solution.resize(c); + + if (c-1 >= 0) + solution[c-1].push_back(i); + else + isolated.push_back(i); + } + return CreateSummary(solution, isolated, show_print); +} + +double AbstractClusterDlg::CreateSummary(const vector >& solution, const vector& isolated, bool show_print) +{ + // mean centers + vector > mean_centers = _getMeanCenters(solution); + // totss + double totss = _getTotalSumOfSquares(); + // withinss + vector withinss = _getWithinSumOfSquares(solution); + // tot.withiness + double totwithiness = GenUtils::Sum(withinss); + // betweenss + double betweenss = totss - totwithiness; + // ratio + double ratio = betweenss / totss; + + wxString summary; + summary << "------\n"; + if (isolated.size()>0) + summary << _("Number of not clustered observations: ") << isolated.size() << "\n"; + summary << _printConfiguration(); + summary << _printMeanCenters(mean_centers); + summary << _("The total sum of squares:\t") << totss << "\n"; + summary << _printWithinSS(withinss); + summary << _("The total within-cluster sum of squares:\t") << totwithiness << "\n"; + summary << _("The between-cluster sum of squares:\t") << betweenss << "\n"; + summary << _("The ratio of between to total sum of squares:\t") << ratio << "\n\n"; + + if (m_reportbox && show_print) { + wxString report = m_reportbox->GetValue(); + report = summary + report; + m_reportbox->SetValue(report); + } + + return ratio; +} + +vector > AbstractClusterDlg::_getMeanCenters(const vector >& solutions) +{ + int n_clusters = solutions.size(); + vector > result(n_clusters); + + if (columns <= 0 || rows <= 0) return result; + + for (int i=0; i means; + for (int c=0; c 0 ? sum / n : 0; + //if (weight) mean = mean * weight[c]; + means.push_back(mean); + } + result[i] = means; + } + + return result; +} + +double AbstractClusterDlg::_getTotalSumOfSquares() +{ + if (columns <= 0 || rows <= 0) return 0; + + double ssq = 0.0; + for (int i=0; i vals; + for (int j=0; j AbstractClusterDlg::_getWithinSumOfSquares(const vector >& solution) +{ + // solution is a list of lists of region ids [[1,7,2],[0,4,3],...] such + // that the first solution has areas 1,7,2 the second solution 0,4,3 and so + // on. cluster_ids does not have to be exhaustive + vector wss; + for (int i=0; i& cluster_ids) +{ + if (cluster_ids.empty() || input_data==NULL || mask == NULL) + return 0; + + double ssq = 0; + + for (int i=0; i vals; + for (int j=0; j >& mean_centers) +{ + wxString txt; + txt << _("Cluster centers:\n"); + + stringstream ss; + TextTable t( TextTable::MD ); + + // v1 v2 v3 + // c1 1 2 3 + // c2 1 2 3 + + // first row + t.add(""); + for (int i=0; i& vals = mean_centers[i]; + for (int j=0; j& within_ss) +{ + wxString summary; + summary << _("Within-cluster sum of squares:\n"); + + // # obs Within cluster SS + // C1 12 62.1 + // C2 3 42.3 + // C3 + + wxString ss_str = _("Within cluster S.S."); + + stringstream ss; + TextTable t( TextTable::MD ); + + // first row + t.add(""); + //t.add("#obs"); + t.add(ss_str.ToStdString()); + t.endOfRow(); + + // second row + for (int i=0; i. + */ + +#ifndef __GEODA_CENTER_ABSTRACTCLUSTER_DLG_H___ +#define __GEODA_CENTER_ABSTRACTCLUSTER_DLG_H___ + +#include +#include +#include +#include +#include + +#include "../GeneralWxUtils.h" +#include "../FramesManager.h" +#include "../VarTools.h" +#include "../DataViewer/TableStateObserver.h" +#include "../ShapeOperations/GalWeight.h" + +using namespace std; + +class Project; +class TableInterface; + +class AbstractClusterDlg : public wxDialog, public FramesManagerObserver, public TableStateObserver +{ +public: + AbstractClusterDlg(wxFrame *parent, Project* project, wxString title); + virtual ~AbstractClusterDlg(); + + void CleanData(); + + /** Implementation of FramesManagerObserver interface */ + virtual void update(FramesManager* o); + + /** Implementation of TableStateObserver interface */ + virtual void update(TableState* o); + virtual bool AllowTimelineChanges() { return true; } + virtual bool AllowGroupModify(const wxString& grp_nm) { return true; } + virtual bool AllowObservationAddDelete() { return false; } + + +protected: + wxFrame *parent; + Project* project; + TableInterface* table_int; + FramesManager* frames_manager; + TableState* table_state; + GalElement* gal; + + vector > z; + vector undefs; + int num_vars; + + int rows; + int columns; + int num_obs; + + vector col_names; + std::vector tm_strs; + std::map name_to_nm; + std::map name_to_tm_id; + std::map idx_sum; + + wxTextValidator validator; + wxArrayString var_items; + + virtual bool GetDefaultContiguity(); + + virtual bool Init(); + + virtual double* GetWeights(int columns); + + virtual double GetMinBound(); + + virtual double* GetBoundVals(); + + // Utils + bool CheckConnectivity(GalWeight* gw); + + // Input related + std::vector var_info; + std::vector col_ids; + std::vector select_vars; + double* weight; + double** input_data; + int** mask; + // -- controls + wxListBox* combo_var; + wxCheckBox* m_use_centroids; + wxButton* auto_btn; + wxSlider* m_weight_centroids; + wxTextCtrl* m_wc_txt; + // -- functions + virtual void AddInputCtrls( + wxPanel *panel, + wxBoxSizer* vbox, + bool show_auto_button = false); + virtual void AddSimpleInputCtrls( + wxPanel *panel, + wxBoxSizer* vbox, + bool integer_only = false); + void OnUseCentroids(wxCommandEvent& event); + void OnSlideWeight(wxCommandEvent& event); + virtual void InitVariableCombobox(wxListBox* var_box, + bool integer_only=false); + bool GetInputData(int transform, int min_num_var=2); + void OnInputWeights(wxCommandEvent& event); + virtual void OnAutoWeightCentroids(wxCommandEvent& event); + + // Transformation control + // -- variables + wxChoice* combo_tranform; + // -- functions; + virtual void AddTransformation( + wxPanel* panel, + wxFlexGridSizer* gbox); + + + // Minimum Bound related + // -- variables + wxCheckBox* chk_floor; + wxChoice* combo_floor; + wxTextCtrl* txt_floor; + wxTextCtrl* txt_floor_pct; + wxSlider* slider_floor; + // -- functions + virtual void AddMinBound( + wxPanel *panel, + wxFlexGridSizer* gbox, + bool show_checkbox=true); + virtual void OnCheckMinBound(wxCommandEvent& event); + virtual void OnSelMinBound(wxCommandEvent& event); + virtual void OnTypeMinBound(wxCommandEvent& event); + virtual void OnSlideMinBound(wxCommandEvent& event); + virtual bool CheckMinBound(); + + // Summary related + // The main statistics should be: + // - mean centers or centroids of each cluster in terms of the variables involved + // - the total sum of squares + // - the within sum of squares + // - the between sum of squares + // - the ratio of between to total sum of squares + // -- variables + SimpleReportTextCtrl* m_reportbox; + wxNotebook* AddSimpleReportCtrls(wxPanel *panel); + // -- functions + double _getTotalSumOfSquares(); + double _calcSumOfSquares(const vector& cluster_ids); + vector > _getMeanCenters(const vector >& solution); + vector _getWithinSumOfSquares(const vector >& solution); + wxString _printMeanCenters(const vector >& mean_centers); + wxString _printWithinSS(const vector& within_ss); + virtual wxString _printConfiguration()=0; + double CreateSummary(const vector& clusters, bool show_print = true); + double CreateSummary(const vector >& solution, const vector& isolated = vector(), bool show_print = true); +}; + +#endif diff --git a/DialogTools/AddIdVariable.cpp b/DialogTools/AddIdVariable.cpp index 40180f015..65ad1132d 100644 --- a/DialogTools/AddIdVariable.cpp +++ b/DialogTools/AddIdVariable.cpp @@ -25,7 +25,6 @@ #include #include #include "../DataViewer/TableInterface.h" -#include "../DbfFile.h" #include "AddIdVariable.h" BEGIN_EVENT_TABLE( AddIdVariable, wxDialog ) @@ -77,7 +76,7 @@ void AddIdVariable::OnOkClick( wxCommandEvent& event ) msg << "variable name. The first character must be alphabetic,"; msg << " and the remaining characters can be either alphanumeric "; msg << "or underscores."; - wxMessageDialog dlg(this, msg, "Error", wxOK | wxICON_ERROR ); + wxMessageDialog dlg(this, msg, _("Error"), wxOK | wxICON_ERROR ); dlg.ShowModal(); return; } @@ -88,7 +87,7 @@ void AddIdVariable::OnOkClick( wxCommandEvent& event ) wxString msg; msg << "Variable name \"" + new_id_var_name; msg << "\" already exists. Please choose a different name."; - wxMessageDialog dlg(this, msg, "Error", wxOK | wxICON_ERROR ); + wxMessageDialog dlg(this, msg, _("Error"), wxOK | wxICON_ERROR ); dlg.ShowModal(); return; } @@ -105,7 +104,7 @@ void AddIdVariable::OnOkClick( wxCommandEvent& event ) } else { wxString msg("Could not create a new variable. " "Possibly a read-only data source."); - wxMessageDialog dlg(this, msg, "Error", wxOK | wxICON_ERROR ); + wxMessageDialog dlg(this, msg, _("Error"), wxOK | wxICON_ERROR ); dlg.ShowModal(); return; } diff --git a/DialogTools/AddIdVariable.h b/DialogTools/AddIdVariable.h index e8c4a63f1..69ba9bee8 100644 --- a/DialogTools/AddIdVariable.h +++ b/DialogTools/AddIdVariable.h @@ -24,7 +24,6 @@ #include #include #include -#include "../DbfFile.h" class TableInterface; @@ -46,7 +45,7 @@ class AddIdVariable: public wxDialog { wxString new_id_var_name; wxTextCtrl *new_id_var; wxListBox *existing_vars_list; - std::vector fields; + //std::vector fields; TableInterface* table_int; DECLARE_EVENT_TABLE(); diff --git a/DialogTools/AdjustYAxisDlg.cpp b/DialogTools/AdjustYAxisDlg.cpp index 376462fe4..9dba49d90 100644 --- a/DialogTools/AdjustYAxisDlg.cpp +++ b/DialogTools/AdjustYAxisDlg.cpp @@ -145,7 +145,7 @@ void AxisLabelPrecisionDlg::CreateControls() { wxXmlResource::Get()->LoadDialog(this, GetParent(), "ID_AXIS_LABEL_PRECISION_DLG"); m_precision_spin = wxDynamicCast(FindWindow(XRCID("ID_AXIS_LABEL_PRECISION_SPIN")), wxSpinCtrl); - m_precision_spin->SetRange(1, 6); + m_precision_spin->SetRange(0, 6); m_precision_spin->SetValue(precision); } diff --git a/DialogTools/AggregateDlg.cpp b/DialogTools/AggregateDlg.cpp new file mode 100644 index 000000000..3761e883c --- /dev/null +++ b/DialogTools/AggregateDlg.cpp @@ -0,0 +1,496 @@ +/** + * GeoDa TM, Copyright (C) 2011-2015 by Luc Anselin - all rights reserved + * + * This file is part of GeoDa. + * + * GeoDa is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * GeoDa is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "AggregateDlg.h" +#include "../DataViewer/DataSource.h" +#include "../DataViewer/OGRTable.h" +#include "../DataViewer/OGRColumn.h" +#include "../DataViewer/TableInterface.h" +#include "../FramesManagerObserver.h" +#include "../FramesManager.h" +#include "../DialogTools/ExportDataDlg.h" +#include "../logger.h" +#include "../GeneralWxUtils.h" +#include "../Project.h" + +BEGIN_EVENT_TABLE( AggregationDlg, wxDialog ) + + EVT_BUTTON( XRCID("ID_INC_ALL_BUTTON"), AggregationDlg::OnIncAllClick ) + EVT_BUTTON( XRCID("ID_INC_ONE_BUTTON"), AggregationDlg::OnIncOneClick ) + EVT_LISTBOX_DCLICK( XRCID("ID_INCLUDE_LIST"), AggregationDlg::OnIncListDClick ) + EVT_BUTTON( XRCID("ID_EXCL_ALL_BUTTON"), AggregationDlg::OnExclAllClick ) + EVT_BUTTON( XRCID("ID_EXCL_ONE_BUTTON"), AggregationDlg::OnExclOneClick ) + EVT_LISTBOX_DCLICK( XRCID("ID_EXCLUDE_LIST"), AggregationDlg::OnExclListDClick ) + EVT_CHOICE( XRCID("ID_CURRENT_KEY_CHOICE"), AggregationDlg::OnKeyChoice ) + EVT_CHOICE( XRCID("ID_IMPORT_KEY_CHOICE"), AggregationDlg::OnKeyChoice ) + EVT_BUTTON( XRCID("wxID_AGGREGATE"), AggregationDlg::OnOKClick ) + EVT_BUTTON( XRCID("wxID_CLOSE"), AggregationDlg::OnCloseClick ) + EVT_CLOSE( AggregationDlg::OnClose ) +END_EVENT_TABLE() + +using namespace std; + +AggregationDlg::AggregationDlg(wxWindow* parent, Project* _project_s, const wxPoint& pos) +: project_s(_project_s), export_dlg(NULL) +{ + wxLogMessage("Open AggregationDlg."); + SetParent(parent); + + //table_int->FillColIdMap(col_id_map); + table_int = project_s->GetTableInt(), + frames_manager = project_s->GetFramesManager(), + + CreateControls(); + Init(); + wxString nm; + SetTitle(_("Aggregate - ") + table_int->GetTableName()); + SetPosition(pos); + Centre(); + + frames_manager->registerObserver(this); +} + +AggregationDlg::~AggregationDlg() +{ + frames_manager->removeObserver(this); + if (export_dlg) { + export_dlg->Destroy(); + delete export_dlg; + export_dlg = NULL; + } +} + +void AggregationDlg::update(FramesManager* o) +{ +} + +void AggregationDlg::CreateControls() +{ + wxXmlResource::Get()->LoadDialog(this, GetParent(), "ID_AGGREGATE_DATA_DLG"); + //m_input_file_name = wxDynamicCast(FindWindow(XRCID("ID_INPUT_FILE_TEXT")), wxTextCtrl); + //m_key_val_rb = wxDynamicCast(FindWindow(XRCID("ID_KEY_VAL_RB")), wxRadioButton); + //m_rec_order_rb = wxDynamicCast(FindWindow(XRCID("ID_REC_ORDER_RB")), wxRadioButton); + m_current_key = wxDynamicCast(FindWindow(XRCID("ID_CURRENT_KEY_CHOICE")), wxChoice); + //m_import_key = wxDynamicCast(FindWindow(XRCID("ID_IMPORT_KEY_CHOICE")), wxChoice); + m_exclude_list = wxDynamicCast(FindWindow(XRCID("ID_EXCLUDE_LIST")), wxListBox); + m_include_list = wxDynamicCast(FindWindow(XRCID("ID_INCLUDE_LIST")), wxListBox); + m_count = wxDynamicCast(FindWindow(XRCID("ID_AGGREGATE_COUNT")), wxRadioButton); + m_sum = wxDynamicCast(FindWindow(XRCID("ID_AGGREGATE_SUM")), wxRadioButton); + m_avg = wxDynamicCast(FindWindow(XRCID("ID_AGGREGATE_AVG")), wxRadioButton); + m_min = wxDynamicCast(FindWindow(XRCID("ID_AGGREGATE_MIN")), wxRadioButton); + m_max = wxDynamicCast(FindWindow(XRCID("ID_AGGREGATE_MAX")), wxRadioButton); + //m_overwrite_field = wxDynamicCast(FindWindow(XRCID("ID_MERGE_OVERWRITE_SAME_FIELD")), wxCheckBox); + m_inc_all = wxDynamicCast(FindWindow(XRCID("ID_INC_ALL_BUTTON")), wxButton); + m_inc_one = wxDynamicCast(FindWindow( XRCID("ID_INC_ONE_BUTTON")), wxButton); + m_exc_all = wxDynamicCast(FindWindow( XRCID("ID_EXCL_ALL_BUTTON")), wxButton); + m_exc_one = wxDynamicCast(FindWindow( XRCID("ID_EXCL_ONE_BUTTON")), wxButton); + + wxScrolledWindow* win = wxDynamicCast(FindWindow( XRCID("ID_AGGREGATE_SCROLL_WIN")), wxScrolledWindow); + + win->SetAutoLayout(true); + win->FitInside(); + win->SetScrollRate(5, 5); + + FitInside(); + + + m_count->Bind(wxEVT_RADIOBUTTON, &AggregationDlg::OnMethodSelect, this); + m_sum->Bind(wxEVT_RADIOBUTTON, &AggregationDlg::OnMethodSelect, this); + m_avg->Bind(wxEVT_RADIOBUTTON, &AggregationDlg::OnMethodSelect, this); + m_min->Bind(wxEVT_RADIOBUTTON, &AggregationDlg::OnMethodSelect, this); + m_max->Bind(wxEVT_RADIOBUTTON, &AggregationDlg::OnMethodSelect, this); +} + +void AggregationDlg::Init() +{ + m_current_key->Clear(); + m_include_list->Clear(); + m_exclude_list->Clear(); + + vector col_names; + // get the field names from table interface + set key_name_set; + set field_name_set; + int time_steps = table_int->GetTimeSteps(); + int n_fields = table_int->GetNumberCols(); + for (int cid=0; cidGetColName(cid); + for (int i=0; iGetColType(cid,i); + wxString field_name = table_int->GetColName(cid, i); + // only String, Integer can be keys for merging + if (field_type == GdaConst::long64_type || + field_type == GdaConst::string_type ) + { + if ( key_name_set.count(field_name) == 0) { + m_current_key->Append(field_name); + key_name_set.insert(field_name); + } + } + if (field_type == GdaConst::long64_type || field_type == GdaConst::double_type ) { + if ( field_name_set.count(field_name) == 0) { + m_exclude_list->Append(field_name); + field_name_set.insert(field_name); + } + } + } + } + UpdateMergeButton(); +} + + +void AggregationDlg::OnMethodSelect( wxCommandEvent& ev) +{ + UpdateMergeButton(); +} + +void AggregationDlg::OnIncAllClick( wxCommandEvent& ev) +{ + wxLogMessage("Entering AggregationDlg::OnIncAllClick()"); + for (int i=0, iend=m_exclude_list->GetCount(); iAppend(m_exclude_list->GetString(i)); + } + m_exclude_list->Clear(); + UpdateMergeButton(); +} + +void AggregationDlg::OnIncOneClick( wxCommandEvent& ev) +{ + wxLogMessage("Entering AggregationDlg::OnIncOneClick()"); + if (m_exclude_list->GetSelection() >= 0) { + wxString k = m_exclude_list->GetString(m_exclude_list->GetSelection()); + m_include_list->Append(k); + m_exclude_list->Delete(m_exclude_list->GetSelection()); + } + UpdateMergeButton(); +} + +void AggregationDlg::OnIncListDClick( wxCommandEvent& ev) +{ + wxLogMessage("Entering AggregationDlg::OnIncListDClick()"); + OnExclOneClick(ev); +} + +void AggregationDlg::OnExclAllClick( wxCommandEvent& ev) +{ + wxLogMessage("Entering AggregationDlg::OnExclAllClick()"); + for (int i=0, iend=m_include_list->GetCount(); iAppend(m_include_list->GetString(i)); + } + m_include_list->Clear(); + UpdateMergeButton(); +} + +void AggregationDlg::OnExclOneClick( wxCommandEvent& ev) +{ + wxLogMessage("Entering AggregationDlg::OnExclOneClick()"); + if (m_include_list->GetSelection() >= 0) { + m_exclude_list-> + Append(m_include_list->GetString(m_include_list->GetSelection())); + m_include_list->Delete(m_include_list->GetSelection()); + } + UpdateMergeButton(); +} + +void AggregationDlg::OnExclListDClick( wxCommandEvent& ev) +{ + wxLogMessage("Entering AggregationDlg::OnExclListDClick()"); + OnIncOneClick(ev); +} + +bool AggregationDlg::CheckKeys(wxString key_name, vector& key_vec, map >& key_map) +{ + std::map > dup_dict; // value:[] + std::vector uniq_fnames; + + for (int i=0, iend=key_vec.size(); i aggregate_field_names; + for (int i=0, iend=m_include_list->GetCount(); iGetString(i); + aggregate_field_names.push_back(inc_n); + } + int n_rows = table_int->GetNumberRows(); + + vector key1_vec; + map > key1_map; + + // get and check keys from original table + int key1_id = m_current_key->GetSelection(); + wxString key1_name = m_current_key->GetString(key1_id); + int col1_id = table_int->FindColId(key1_name); + if (table_int->IsColTimeVariant(col1_id)) { + error_msg = wxString::Format(_("Chosen key field '%s' s a time variant. Please choose a non-time variant field as key."), key1_name); + throw GdaException(error_msg.mb_str()); + } + + vector key1_l_vec; + GdaConst::FieldType key_ftype = table_int->GetColType(col1_id, 0); + + if (key_ftype == GdaConst::string_type) { + table_int->GetColData(col1_id, 0, key1_vec); + }else if (key_ftype==GdaConst::long64_type){ + table_int->GetColData(col1_id, 0, key1_l_vec); + } + + if (key1_vec.empty()) { // convert everything (key) to wxString + for( int i=0; i< key1_l_vec.size(); i++){ + wxString tmp; + tmp << key1_l_vec[i]; + key1_vec.push_back(tmp); + } + } + if (CheckKeys(key1_name, key1_vec, key1_map) == false) + return; + + // Create in-memory geometries&table + int new_rows = key1_map.size(); + OGRTable* mem_table = new OGRTable(new_rows); + vector undefs(new_rows, true); + + int in_cols = aggregate_field_names.size(); + map new_fields_dict; + vector new_fields; + + // create key column + OGRColumn* key_col; + if (key_ftype == GdaConst::string_type) { + key_col = new OGRColumnString(key1_name, 50, 0, new_rows); + for(int i=0; iSetValueAt(i, key1_vec[key1_map[i][0]]); + }else if (key_ftype==GdaConst::long64_type){ + key_col = new OGRColumnInteger(key1_name, 18, 0, new_rows); + for(int i=0; iSetValueAt(i, key1_l_vec[key1_map[i][0]]); + } + new_fields_dict[key1_name] = key_col; + new_fields.push_back(key1_name); + + // create count column + OGRColumn* _col = new OGRColumnInteger("AGG_COUNT", 18, 0, new_rows); + for(int i=0; iSetValueAt(i, (wxInt64)(key1_map[i].size())); + new_fields_dict[_col->GetName()] = _col; + new_fields.push_back(_col->GetName()); + + // get columns from table + for ( int i=0; i < in_cols; i++ ) { + wxString fname = aggregate_field_names[i]; + OGRColumn* col = CreateNewOGRColumn(new_rows, table_int, key1_map, fname); + new_fields_dict[fname] = col; + new_fields.push_back(col->GetName()); + } + + for (int i=0; iAddOGRColumn(new_fields_dict[new_fields[i]]); + } + + if (export_dlg != NULL) { + export_dlg->Destroy(); + delete export_dlg; + } + export_dlg = new ExportDataDlg(this, mem_table); + if (export_dlg->ShowModal() == wxID_OK) { + wxMessageDialog dlg(this, _("Successful aggregation."), _("Success"), wxOK); + dlg.ShowModal(); + } + delete mem_table; + } catch (GdaException& ex) { + if (ex.type() == GdaException::NORMAL) + return; + wxMessageDialog dlg(this, ex.what(), _("Error"), wxOK | wxICON_ERROR); + dlg.ShowModal(); + return; + } + ev.Skip(); +} + +double AggregationDlg::ComputeAgg(vector& vals, vector& undefs, vector& ids) +{ + if (m_sum->GetValue()) { + double v_sum = 0; + for (int i=0; iGetValue()) { + double v_sum = 0; + int n = 0; + for (int i=0; iGetValue()) { + double v_max = DBL_MIN; + for (int i=0; i v_max) + v_max = vals[idx]; + } + } + return v_max; + } + + else if (m_min->GetValue()) { + double v_min = DBL_MAX; + for (int i=0; i >& key_map, wxString f_name) +{ + int idx = table_int->FindColId(f_name); + int t = 0; + int f_length = table_int->GetColLength(idx, 0); + int f_decimal = table_int->GetColDecimals(idx, 0); + GdaConst::FieldType f_type = table_int->GetColType(idx, 0); + + OGRColumn* _col; + if (f_type == GdaConst::long64_type) { + bool is_integer = false; + if (m_max->GetValue() || m_min->GetValue() || m_sum->GetValue()) { + _col = new OGRColumnInteger(f_name, f_length, f_decimal, new_rows); + is_integer = true; + } else + _col = new OGRColumnDouble(f_name, GdaConst::default_dbf_double_len, GdaConst::default_dbf_double_decimals, new_rows); + + vector vals; + vector undefs; + table_int->GetColData(idx, t, vals, undefs); + + for(int i=0; i& ids = key_map[i]; + double v = ComputeAgg(vals, undefs, ids); + if (is_integer) { + wxInt64 vv = v; + _col->SetValueAt(i, vv); + } else + _col->SetValueAt(i, v); + } + + } else if (f_type == GdaConst::double_type) { + _col = new OGRColumnDouble(f_name, f_length, f_decimal, new_rows); + vector vals; + vector undefs; + table_int->GetColData(idx, t, vals, undefs); + for(int i=0; i& ids = key_map[i]; + double v = ComputeAgg(vals, undefs, ids); + _col->SetValueAt(i, v); + } + + } + return _col; +} + +void AggregationDlg::OnCloseClick( wxCommandEvent& ev ) +{ + wxLogMessage("In AggregationDlg::OnCloseClick()"); + if (export_dlg) { + export_dlg->Destroy(); + delete export_dlg; + export_dlg = NULL; + } + EndDialog(wxID_CLOSE); +} + +void AggregationDlg::OnClose( wxCloseEvent& ev) +{ + wxLogMessage("In AggregationDlg::OnClose()"); + if (export_dlg) { + export_dlg->Destroy(); + delete export_dlg; + export_dlg = NULL; + } + Destroy(); +} + +void AggregationDlg::OnKeyChoice( wxCommandEvent& ev ) +{ + wxLogMessage("In AggregationDlg::OnKeyChoice()"); + UpdateMergeButton(); +} + +void AggregationDlg::UpdateMergeButton() +{ + bool enable = m_count->GetValue() || (!m_include_list->IsEmpty() && m_current_key->GetSelection() != wxNOT_FOUND); + FindWindow(XRCID("wxID_AGGREGATE"))->Enable(enable); + + m_inc_all->Enable(!m_count->GetValue()); + m_inc_one->Enable(!m_count->GetValue()); + m_exc_all->Enable(!m_count->GetValue()); + m_exc_one->Enable(!m_count->GetValue()); +} diff --git a/DialogTools/AggregateDlg.h b/DialogTools/AggregateDlg.h new file mode 100644 index 000000000..462c684a2 --- /dev/null +++ b/DialogTools/AggregateDlg.h @@ -0,0 +1,126 @@ +/** + * GeoDa TM, Copyright (C) 2011-2015 by Luc Anselin - all rights reserved + * + * This file is part of GeoDa. + * + * GeoDa is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * GeoDa is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#ifndef __GEODA_CENTER_AGGREGATION_DLG_H__ +#define __GEODA_CENTER_AGGREGATION_DLG_H__ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../DataViewer/DataSource.h" +#include "../FramesManagerObserver.h" +#include "../ShapeOperations/OGRLayerProxy.h" +#include "../ShapeOperations/OGRDatasourceProxy.h" +#include "../DataViewer/TableInterface.h" + +class FramesManager; +class Project; +class ExportDataDlg; +class OGRColumn; + +class AggregationDlg: public wxDialog, public FramesManagerObserver +{ +public: + AggregationDlg(wxWindow* parent, + Project* project_p, + const wxPoint& pos = wxDefaultPosition); + virtual ~AggregationDlg(); + + void CreateControls(); + void Init(); + + /** Implementation of FramesManagerObserver interface */ + virtual void update(FramesManager* o); + + void OnIncAllClick( wxCommandEvent& ev ); + void OnIncOneClick( wxCommandEvent& ev ); + void OnIncListDClick(wxCommandEvent& ev ); + void OnExclAllClick( wxCommandEvent& ev ); + void OnExclOneClick( wxCommandEvent& ev ); + void OnExclListDClick(wxCommandEvent& ev ); + + void OnOKClick( wxCommandEvent& ev ); + void OnKeyChoice( wxCommandEvent& ev ); + + void OnCloseClick( wxCommandEvent& ev ); + void OnClose( wxCloseEvent& ev); + void OnLeftJoinClick( wxCommandEvent& ev ); + void OnOuterJoinClick( wxCommandEvent& ev ); + void UpdateMergeButton(); + //void UpdateIncListItems(); + + void OnMethodSelect( wxCommandEvent& ev ); + + + //wxTextCtrl* m_input_file_name; + //wxRadioButton* m_key_val_rb; + //wxRadioButton* m_rec_order_rb; + wxChoice* m_current_key; + //wxChoice* m_import_key; + wxListBox* m_exclude_list; + wxListBox* m_include_list; + //wxRadioButton* m_left_join; + //wxRadioButton* m_outer_join; + //wxCheckBox* m_overwrite_field; + wxRadioButton* m_count; + wxRadioButton* m_sum; + wxRadioButton* m_avg; + wxRadioButton* m_max; + wxRadioButton* m_min; + wxButton* m_inc_all; + wxButton* m_inc_one; + wxButton* m_exc_all; + wxButton* m_exc_one; + + ExportDataDlg* export_dlg; + + Project* project_s; + TableInterface* table_int; + +private: + FramesManager* frames_manager; + + std::map dedup_to_id; + std::set dups; + // a mapping from displayed col order to actual col ids in table + // Eg, in underlying table, we might have A, B, C, D, E, F, + // but because of user wxGrid col reorder operaions might see these + // as C, B, A, F, D, E. In this case, the col_id_map would be + // 0->2, 1->1, 2->0, 3->5, 4->3, 5->4 + //std::vector col_id_map; + + bool CheckKeys(wxString key_name, std::vector& key_vec, + std::map >& key_map); + + OGRColumn* CreateNewOGRColumn(int new_rows, TableInterface* table_int, std::map >& key_map, wxString f_name); + + double ComputeAgg(vector& vals, vector& undefs, vector& ids); + + DECLARE_EVENT_TABLE() +}; + +#endif diff --git a/DialogTools/AutoCompTextCtrl.cpp b/DialogTools/AutoCompTextCtrl.cpp index 0c5e256e6..894b36f68 100644 --- a/DialogTools/AutoCompTextCtrl.cpp +++ b/DialogTools/AutoCompTextCtrl.cpp @@ -32,8 +32,8 @@ AutoTextCtrl::DoIdle( wxIdleEvent &event ) void AutoTextCtrl::TextEntered( wxCommandEvent &event ) { - std::string sVal; - std::string szListName; + wxString sVal; + wxString szListName; long iPoint; if(m_bIgnoreNextTextEdit) { @@ -66,7 +66,7 @@ AutoTextCtrl::TextEntered( wxCommandEvent &event ) // strlen(szVal) < strlen(szClassName)) { // Third, write the entire name of the first matching class // into the text string - SetValue(wxString(szListName)); + SetValue(szListName); // Fourth, select the text from the current cursor position to // the end of the text diff --git a/DialogTools/AutoCompTextCtrl.h b/DialogTools/AutoCompTextCtrl.h index bc973d081..ffc170941 100644 --- a/DialogTools/AutoCompTextCtrl.h +++ b/DialogTools/AutoCompTextCtrl.h @@ -25,7 +25,7 @@ class AutoTextCtrl: public wxTextCtrl { void TextEntered( wxCommandEvent &event ); void DoIdle( wxIdleEvent &event ); void DoKeyDown( wxKeyEvent &event ); - void SetAutoList(std::vector &autoList) { + void SetAutoList(std::vector &autoList) { if (autoList.size() == 0) return; m_pList = autoList; std::sort(m_pList.begin(), m_pList.end()); @@ -34,7 +34,7 @@ class AutoTextCtrl: public wxTextCtrl { private: bool m_bDoSelectAll; bool m_bIgnoreNextTextEdit; - std::vector m_pList; + std::vector m_pList; DECLARE_EVENT_TABLE() }; diff --git a/DialogTools/AutoUpdateDlg.cpp b/DialogTools/AutoUpdateDlg.cpp index 1579b46f2..274b10aa2 100644 --- a/DialogTools/AutoUpdateDlg.cpp +++ b/DialogTools/AutoUpdateDlg.cpp @@ -128,7 +128,7 @@ wxString AutoUpdate::CheckUpdate() { wxLogMessage("AutoUpdate::CheckUpdate()"); bool isTestMode = false; - std::vector test_mode = OGRDataAdapter::GetInstance().GetHistory("test_mode"); + std::vector test_mode = OGRDataAdapter::GetInstance().GetHistory("test_mode"); if (!test_mode.empty() && test_mode[0] == "yes") { isTestMode = true; } @@ -267,7 +267,7 @@ wxString AutoUpdate::GetCheckList() { wxLogMessage("AutoUpdate::GetCheckList()"); bool isTestMode = false; - std::vector test_mode = OGRDataAdapter::GetInstance().GetHistory("test_mode"); + std::vector test_mode = OGRDataAdapter::GetInstance().GetHistory("test_mode"); if (!test_mode.empty() && test_mode[0] == "yes") { isTestMode = true; } diff --git a/DialogTools/BasemapConfDlg.cpp b/DialogTools/BasemapConfDlg.cpp index b17d42911..d78ae078e 100644 --- a/DialogTools/BasemapConfDlg.cpp +++ b/DialogTools/BasemapConfDlg.cpp @@ -29,7 +29,7 @@ #include "../Project.h" #include "../ShapeOperations/OGRDataAdapter.h" - +#include "../GdaConst.h" #include "BasemapConfDlg.h" @@ -48,11 +48,23 @@ BasemapConfDlg::BasemapConfDlg(wxWindow* parent, Project* _p, wxLogMessage("Open BasemapConfDlg."); p = _p; + basemap_resources = wxString::FromUTF8(GdaConst::gda_basemap_sources.mb_str()); + std::vector items = OGRDataAdapter::GetInstance().GetHistory("gda_basemap_sources"); + if (items.size()>0) { + basemap_resources = items[0]; + } + + wxString encoded_str= wxString::FromUTF8((const char*)basemap_resources.mb_str()); + if (encoded_str.IsEmpty() == false) { + basemap_resources = encoded_str; + } + wxXmlResource::Get()->LoadDialog(this, GetParent(), "IDD_BASEMAP_CONF_DLG"); FindWindow(XRCID("wxID_OK"))->Enable(true); m_txt_nokia_uname = XRCCTRL(*this, "IDC_NOKIA_USERNAME",wxTextCtrl); m_txt_nokia_key = XRCCTRL(*this, "IDC_NOKIA_KEY",wxTextCtrl); - + m_txt_basemap = XRCCTRL(*this, "IDC_BASEMAP_SOURCE",wxTextCtrl); + m_txt_basemap->SetValue(basemap_resources); SetParent(parent); SetPosition(pos); @@ -64,14 +76,16 @@ void BasemapConfDlg::OnOkClick( wxCommandEvent& event ) { wxLogMessage("BasemapConfDlg: Click OK Button."); - std::string nokia_uname(m_txt_nokia_uname->GetValue().Trim().mb_str()); - std::string nokia_key(m_txt_nokia_key->GetValue().Trim().mb_str()); + wxString nokia_uname(m_txt_nokia_uname->GetValue().Trim()); + wxString nokia_key(m_txt_nokia_key->GetValue().Trim()); if (!nokia_uname.empty() && !nokia_key.empty()) { - OGRDataAdapter::GetInstance().AddEntry("nokia_user", nokia_uname.c_str()); - OGRDataAdapter::GetInstance().AddEntry("nokia_key", nokia_key.c_str()); + OGRDataAdapter::GetInstance().AddEntry("nokia_user", nokia_uname); + OGRDataAdapter::GetInstance().AddEntry("nokia_key", nokia_key); + } + if (m_txt_basemap->GetValue() != basemap_resources) { + OGRDataAdapter::GetInstance().AddEntry("gda_basemap_sources", m_txt_basemap->GetValue()); } - EndDialog(wxID_OK); } @@ -79,11 +93,12 @@ void BasemapConfDlg::OnResetClick( wxCommandEvent& event ) { wxLogMessage("BasemapConfDlg: Click Reset Button."); - std::string nokia_uname = "oRnRceLPyM8OFQQA5LYH"; - std::string nokia_key = "uEt3wtyghaTfPdDHdOsEGQ"; + wxString nokia_uname = "oRnRceLPyM8OFQQA5LYH"; + wxString nokia_key = "uEt3wtyghaTfPdDHdOsEGQ"; - OGRDataAdapter::GetInstance().AddEntry("nokia_user", nokia_uname.c_str()); - OGRDataAdapter::GetInstance().AddEntry("nokia_key", nokia_key.c_str()); + OGRDataAdapter::GetInstance().AddEntry("nokia_user", nokia_uname); + OGRDataAdapter::GetInstance().AddEntry("nokia_key", nokia_key); + OGRDataAdapter::GetInstance().AddEntry("gda_basemap_sources", basemap_resources); EndDialog(wxID_OK); } diff --git a/DialogTools/BasemapConfDlg.h b/DialogTools/BasemapConfDlg.h index acc3cfad5..65fbe94e8 100644 --- a/DialogTools/BasemapConfDlg.h +++ b/DialogTools/BasemapConfDlg.h @@ -37,15 +37,17 @@ class BasemapConfDlg: public wxDialog public: BasemapConfDlg(wxWindow* parent, Project* p, wxWindowID id = wxID_ANY, - const wxString& title = "Basemap Configuration Dialog", + const wxString& title = _("Basemap Configuration Dialog"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize ); private: Project* p; + wxString basemap_resources; + wxTextCtrl* m_txt_nokia_uname; wxTextCtrl* m_txt_nokia_key; - + wxTextCtrl* m_txt_basemap; void OnOkClick( wxCommandEvent& event ); void OnResetClick( wxCommandEvent& event ); diff --git a/DialogTools/Bnd2ShpDlg.cpp b/DialogTools/Bnd2ShpDlg.cpp index 4823e4fdc..2e6612e85 100644 --- a/DialogTools/Bnd2ShpDlg.cpp +++ b/DialogTools/Bnd2ShpDlg.cpp @@ -75,8 +75,13 @@ void Bnd2ShpDlg::OnCreateClick( wxCommandEvent& event ) wxString m_iASC = m_inputfile->GetValue(); - fstream ias; +#ifdef __WIN32__ + std:ifstream ias(m_iASC.wc_str()); +#else + std:ifstream ias; ias.open(GET_ENCODED_FILENAME(m_iASC)); +#endif + int nRows; char name[1000]; ias.getline(name,100); diff --git a/DialogTools/CalculatorDlg.cpp b/DialogTools/CalculatorDlg.cpp index 2018f68db..ee7eaa5b1 100644 --- a/DialogTools/CalculatorDlg.cpp +++ b/DialogTools/CalculatorDlg.cpp @@ -25,8 +25,8 @@ #include #include #include "../FramesManager.h" -#include "../DbfFile.h" -#include "../DataViewer/DbfTable.h" + + #include "../DataViewer/DataViewerAddColDlg.h" #include "../DataViewer/TableInterface.h" #include "../DataViewer/TableState.h" @@ -563,7 +563,7 @@ void CalculatorDlg::AssignOrSelect(bool assign) int num_obs_sel = 0; vector selected(obs); if (V_obs == 1) { - bool val = (bool) V[t]; + bool val = V[t]!=0 ? true : false; for (size_t i=0; iGetHighlightState(), pos, size, false, true), +project(project_s), num_obs(project_s->GetNumRecords()), y_axis(0), data(0), default_data(project_s->GetNumRecords()), breaks(0), default_breaks(default_intervals-1), @@ -283,9 +284,12 @@ wxString CatClassifHistCanvas::GetCanvasTitle() return s; } -void CatClassifHistCanvas::GetBarPositions(std::vector& x_center_pos, - std::vector& x_left_pos, - std::vector& x_right_pos) +wxString CatClassifHistCanvas::GetVariableNames() +{ + return wxEmptyString; +} + +void CatClassifHistCanvas::GetBarPositions(std::vector& x_center_pos, std::vector& x_left_pos, std::vector& x_right_pos) { int n = x_center_pos.size(); @@ -298,16 +302,31 @@ void CatClassifHistCanvas::GetBarPositions(std::vector& x_center_pos, std::vector ticks; ticks.push_back(val_min); - for(int i=0; isize();i++) + for(int i=0; isize();i++) { ticks.push_back((*breaks)[i]); + } ticks.push_back(val_max); int j=0; for (int i=0; i 0) { + x_right = x_max; + } else { + x_left = val_range==0 ? 0 : x_max * (ticks[i] - left) / val_range; + x_right = val_range==0 ? 0 : x_max * (ticks[i+1] - left) / val_range; + + if (x_left == x_right && ival_obs_cnt[i] > 0 && j>0) { + for (int k=j-1; k>=0; k--) + if (x_left_pos[k] != x_left) + x_left = x_left_pos[j]; + } + } + x_left_pos[j] = x_left; + x_right_pos[j] = x_right; + x_center_pos[j] = (x_left + x_right) / 2.0; j++; } } @@ -337,24 +356,29 @@ void CatClassifHistCanvas::PopulateCanvas() axis_scale_y = AxisScale(0, y_max, 5, axis_display_precision); y_max = axis_scale_y.scale_max; - y_axis = new GdaAxis("Frequency", axis_scale_y, + y_axis = new GdaAxis(_("Frequency"), axis_scale_y, wxRealPoint(0,0), wxRealPoint(0, y_max), -9, 0); foreground_shps.push_back(y_axis); - - last_scale_trans.SetMargin(45, 25+32, 25+35, 25); selectable_shps.resize(cur_intervals); + + wxClientDC dc(this); + + int max_label_height = 0; + for (int i=0; isetPen((*colors)[i]); selectable_shps[i]->setBrush((*colors)[i]); + int s_w =0; + int s_h = 0; + if (i==0) { GdaShapeText* brk = new GdaShapeText(GenUtils::DblToStr(min_val), @@ -362,6 +386,7 @@ void CatClassifHistCanvas::PopulateCanvas() wxRealPoint(x0, y0), 90, GdaShapeText::right, GdaShapeText::v_center, 0, 10); + brk->GetSize(dc, s_w, s_h); foreground_shps.push_back(brk); } if (iGetSize(dc, s_w, s_h); foreground_shps.push_back(brk); } if (i==cur_intervals-1) { @@ -380,9 +406,13 @@ void CatClassifHistCanvas::PopulateCanvas() wxRealPoint(x1, y0), 90, GdaShapeText::right, GdaShapeText::v_center, 0, 10); + brk->GetSize(dc, s_w, s_h); foreground_shps.push_back(brk); } + if (s_w > max_label_height) max_label_height = s_w; } + + last_scale_trans.SetMargin(45, 15+max_label_height, 25+35, 25); ResizeSelectableShps(); } @@ -419,7 +449,7 @@ void CatClassifHistCanvas::InitIntervals() int ind; max_val = (*data)[0].first; - min_val = (*data)[0].second; + min_val = (*data)[num_obs-1].first; for (int i=0; iSetSelection(0); save_categories_button = wxDynamicCast(FindWindow(XRCID("ID_CATEGORY_EDITOR_SAVE_CAT")), wxButton); change_title_button = @@ -734,11 +768,9 @@ useScientificNotation(_useScientificNotation) for (wxWindowList::iterator it = win_list.begin(); it != win_list.end(); it++) { if ((*it)->GetId() == XRCID("ID_CAT_BUT")) { - cat_color_button_srt_vec.push_back(make_pair((*it)->GetPosition().y, - (*it))); + cat_color_button_srt_vec.push_back(make_pair((*it)->GetPosition().y, (*it))); } else if ((*it)->GetId() == XRCID("ID_CAT_TXT")) { - cat_title_txt_srt_vec.push_back(make_pair((*it)->GetPosition().y, - (*it))); + cat_title_txt_srt_vec.push_back(make_pair((*it)->GetPosition().y, (*it))); } else if ((*it)->GetId() == XRCID("ID_BRK_RAD")) { brk_rad_srt_vec.push_back(make_pair((*it)->GetPosition().y, (*it))); } else if ((*it)->GetId() == XRCID("ID_BRK_LBL")) { @@ -754,8 +786,7 @@ useScientificNotation(_useScientificNotation) for (int i=0, iend=cat_color_button_srt_vec.size(); iBind(wxEVT_LEFT_UP, - &CatClassifPanel::OnCategoryColorButton, this); + cat_color_button[i]->Bind(wxEVT_LEFT_UP, &CatClassifPanel::OnCategoryColorButton, this); } std::sort(cat_title_txt_srt_vec.begin(), cat_title_txt_srt_vec.end(), int_win_pair_less); @@ -763,6 +794,7 @@ useScientificNotation(_useScientificNotation) for (int i=0, iend=cat_title_txt_srt_vec.size(); iSetEditable(!cc_data.automatic_labels); + //cat_title_txt[i]->Bind(wxEVT_TEXT_ENTER, &CatClassifPanel::OnUserInput, this); } for (int i=0; iGetValue(); @@ -809,6 +841,9 @@ useScientificNotation(_useScientificNotation) if (cc_state) { cc_data = cc_state->GetCatClassif(); SetSyncVars(true); + + CatClassification::CorrectCatClassifFromTable(cc_data, table_int,IsAutomaticLabels()); + InitFromCCData(); EnableControls(true); @@ -838,9 +873,7 @@ CatClassifState* CatClassifPanel::PromptNew(const CatClassifDef& ccd, if (!all_init) return 0; wxString msg = _("New Custom Categories Title:"); - wxString new_title = (suggested_title.IsEmpty() ? - GetDefaultTitle(field_name, field_tm) : - suggested_title); + wxString new_title = (suggested_title.IsEmpty() ? GetDefaultTitle(field_name) : suggested_title); bool retry = true; bool success = false; @@ -856,7 +889,7 @@ CatClassifState* CatClassifPanel::PromptNew(const CatClassifDef& ccd, retry = false; } else if (IsDuplicateTitle(new_title)) { wxString es = wxString::Format(_("Categories title \"%s\" already exists. Please choose a different title."), new_title); - wxMessageDialog ed(NULL, es, "Error", wxOK | wxICON_ERROR); + wxMessageDialog ed(NULL, es, _("Error"), wxOK | wxICON_ERROR); ed.ShowModal(); } else { success = true; @@ -867,7 +900,6 @@ CatClassifState* CatClassifPanel::PromptNew(const CatClassifDef& ccd, } } } - wxLogMessage("In CatClassifPanel::PromptNew"); wxLogMessage(_("suggested title:") + suggested_title); @@ -878,18 +910,25 @@ CatClassifState* CatClassifPanel::PromptNew(const CatClassifDef& ccd, cc_data.title = new_title; CatClassification::CatClassifTypeToBreakValsType(cc_data.cat_classif_type); cc_data.cat_classif_type = CatClassification::custom; + cc_data.break_vals_type = CatClassification::quantile_break_vals; + + CatClassification::CorrectCatClassifFromTable(cc_data, table_int, IsAutomaticLabels()); + int f_sel = assoc_var_choice->FindString(field_name); if (f_sel != wxNOT_FOUND) { assoc_var_choice->SetSelection(f_sel); if (table_int->IsColTimeVariant(field_name)) { assoc_var_tm_choice->SetSelection(field_tm); + assoc_var_tm_choice->Show(); } else { - assoc_var_tm_choice->Enable(false); + assoc_var_tm_choice->Hide(); } } cc_state = cat_classif_manager->CreateNewClassifState(cc_data); SetSyncVars(true); InitFromCCData(); + UpdateCCState(); + cc_state->SetCatClassif(cc_data); cur_cats_choice->Append(new_title); cur_cats_choice->SetSelection(cur_cats_choice->GetCount()-1); @@ -918,11 +957,12 @@ void CatClassifPanel::OnCurCatsChoice(wxCommandEvent& event) // Verify that cc data is self-consistent and correct if not. This // will result in all breaks, colors and names being initialized. - CatClassification::CorrectCatClassifFromTable(cc_data, table_int); + CatClassification::CorrectCatClassifFromTable(cc_data, table_int, IsAutomaticLabels()); InitFromCCData(); UpdateCCState(); EnableControls(true); + } void CatClassifPanel::OnBreaksChoice(wxCommandEvent& event) @@ -932,13 +972,18 @@ void CatClassifPanel::OnBreaksChoice(wxCommandEvent& event) if (!all_init) return; CatClassification::BreakValsType bv_type = GetBreakValsTypeChoice(); cc_data.break_vals_type = bv_type; + // Verify that cc data is self-consistent and correct if not. This // will result in all breaks, colors and names being initialized. - CatClassification::CorrectCatClassifFromTable(cc_data, table_int); + CatClassification::CorrectCatClassifFromTable(cc_data, table_int, IsAutomaticLabels()); InitFromCCData(); UpdateCCState(); + + if (bv_type != CatClassification::custom_break_vals) { + auto_labels_cb->SetValue(true); + } } void CatClassifPanel::OnColorSchemeChoice(wxCommandEvent& event) @@ -966,7 +1011,7 @@ void CatClassifPanel::OnColorSchemeChoice(wxCommandEvent& event) // Verify that cc data is self-consistent and correct if not. This // will result in all breaks, colors and names being initialized. - CatClassification::CorrectCatClassifFromTable(cc_data, table_int); + CatClassification::CorrectCatClassifFromTable(cc_data, table_int, IsAutomaticLabels()); InitFromCCData(); UpdateCCState(); @@ -1022,7 +1067,17 @@ void CatClassifPanel::OnNumCatsChoice(wxCommandEvent& event) // Verify that cc data is self-consistent and correct if not. This // will result in all breaks, colors and names being initialized. - CatClassification::CorrectCatClassifFromTable(cc_data, table_int); + CatClassification::CorrectCatClassifFromTable(cc_data, table_int, IsAutomaticLabels()); + + // check if breaks have same values + std::set brks; + for (int i=0; iIsColTimeVariant(cur_fc_str); - assoc_var_tm_choice->Enable(is_tm_var); + if (is_tm_var) + assoc_var_tm_choice->Show(); + else + assoc_var_tm_choice->Hide(); + if (is_tm_var && assoc_var_tm_choice->GetSelection() == wxNOT_FOUND) { assoc_var_tm_choice->SetSelection(0); } @@ -1050,7 +1109,7 @@ void CatClassifPanel::OnAssocVarChoice(wxCommandEvent& ev) // Verify that cc data is self-consistent and correct if not. This // will result in all breaks, colors and names being initialized. - CatClassification::CorrectCatClassifFromTable(cc_data, table_int); + CatClassification::CorrectCatClassifFromTable(cc_data, table_int, IsAutomaticLabels()); InitFromCCData(); UpdateCCState(); @@ -1066,7 +1125,7 @@ void CatClassifPanel::OnAssocVarTmChoice(wxCommandEvent& ev) // Verify that cc data is self-consistent and correct if not. This // will result in all breaks, colors and names being initialized. - CatClassification::CorrectCatClassifFromTable(cc_data, table_int); + CatClassification::CorrectCatClassifFromTable(cc_data, table_int, IsAutomaticLabels()); InitFromCCData(); UpdateCCState(); @@ -1188,7 +1247,7 @@ void CatClassifPanel::OnUnifDistMinEnter(wxCommandEvent& event) // Verify that cc data is self-consistent and correct if not. This // will result in all breaks, colors and names being initialized. - CatClassification::CorrectCatClassifFromTable(cc_data, table_int); + CatClassification::CorrectCatClassifFromTable(cc_data, table_int, IsAutomaticLabels()); InitFromCCData(); UpdateCCState(); @@ -1240,7 +1299,7 @@ void CatClassifPanel::OnUnifDistMaxEnter(wxCommandEvent& event) // Verify that cc data is self-consistent and correct if not. This // will result in all breaks, colors and names being initialized. - CatClassification::CorrectCatClassifFromTable(cc_data, table_int); + CatClassification::CorrectCatClassifFromTable(cc_data, table_int, IsAutomaticLabels()); InitFromCCData(); UpdateCCState(); @@ -1291,6 +1350,21 @@ void CatClassifPanel::OnBrkRad(wxCommandEvent& event) SetSliderFromBreak(obj_id); } +void CatClassifPanel::OnUserInput(wxCommandEvent& event) +{ + wxLogMessage("CatClassifPanel::OnUserInput"); + if (!all_init) return; + wxTextCtrl* obj = (wxTextCtrl*) event.GetEventObject(); + int obj_id = -1; + for (int i=0, iend=cat_title_txt.size(); iGetValue()); + + UpdateCCState(); +} + void CatClassifPanel::OnBrkTxtEnter(wxCommandEvent& event) { wxLogMessage("CatClassifPanel::OnBrkTxtEnter"); @@ -1430,7 +1504,7 @@ void CatClassifPanel::OnCategoryColorButton(wxMouseEvent& event) } wxColourDialog dialog(this, &clr_data); - dialog.SetTitle("Choose Cateogry Color"); + dialog.SetTitle(_("Choose Cateogry Color")); if (dialog.ShowModal() != wxID_OK) return; wxColourData retData = dialog.GetColourData(); if (cc_data.colors[obj_id] == retData.GetColour()) return; @@ -1461,13 +1535,12 @@ void CatClassifPanel::OnButtonChangeTitle(wxCommandEvent& event) { wxLogMessage("CatClassifPanel::OnButtonChangeTitle"); if (!all_init) return; - wxString msg; wxString cur_title = cur_cats_choice->GetStringSelection(); wxString new_title = cur_title; - msg << "Change title \"" << cur_title << "\" to"; + wxString msg = wxString::Format(_("Change title \"%s\" to"), cur_title); bool retry = true; while (retry) { - wxTextEntryDialog dlg(this, msg, "Change Categories Title"); + wxTextEntryDialog dlg(this, msg, _("Change Categories Title")); dlg.SetValue(new_title); if (dlg.ShowModal() == wxID_OK) { new_title = dlg.GetValue(); @@ -1476,10 +1549,9 @@ void CatClassifPanel::OnButtonChangeTitle(wxCommandEvent& event) if (new_title.IsEmpty() || new_title == cur_title) { retry = false; } else if (IsDuplicateTitle(new_title)) { - wxString es; - es << "Categories title \"" << new_title << "\" already "; - es << "exists. Please choose a different title."; - wxMessageDialog ed(NULL, es, "Error", wxOK | wxICON_ERROR); + wxString es = _("Categories title \"%s\" already exists. Please choose a different title."); + es = wxString::Format(es, new_title); + wxMessageDialog ed(NULL, es, _("Error"), wxOK | wxICON_ERROR); ed.ShowModal(); } else { int sel = cur_cats_choice->GetSelection(); @@ -1498,12 +1570,11 @@ void CatClassifPanel::OnButtonNew(wxCommandEvent& event) { wxLogMessage("CatClassifPanel::OnButtonNew"); if (!all_init) return; - wxString msg; - msg << "New Custom Categories Title:"; + wxString msg = _("New Custom Categories Title:"); wxString new_title = GetDefaultTitle(); bool retry = true; while (retry) { - wxTextEntryDialog dlg(this, msg, "New Categories Title"); + wxTextEntryDialog dlg(this, msg, _("New Categories Title")); dlg.SetValue(new_title); if (dlg.ShowModal() == wxID_OK) { new_title = dlg.GetValue(); @@ -1513,10 +1584,9 @@ void CatClassifPanel::OnButtonNew(wxCommandEvent& event) retry = false; } else if (IsDuplicateTitle(new_title)) { - wxString es; - es << "Categories title \"" << new_title << "\" already "; - es << "exists. Please choose a different title."; - wxMessageDialog ed(NULL, es, "Error", wxOK | wxICON_ERROR); + wxString es = _("Categories title \"%s\" already exists. Please choose a different title."); + es = wxString::Format(es, new_title); + wxMessageDialog ed(NULL, es, _("Error"), wxOK | wxICON_ERROR); ed.ShowModal(); } else { @@ -1529,7 +1599,7 @@ void CatClassifPanel::OnButtonNew(wxCommandEvent& event) // Verify that cc data is self-consistent and correct if not. This // will result in all breaks, colors and names being initialized. - CatClassification::CorrectCatClassifFromTable(cc_data, table_int); + CatClassification::CorrectCatClassifFromTable(cc_data, table_int, IsAutomaticLabels()); InitFromCCData(); EnableControls(true); @@ -1569,11 +1639,9 @@ void CatClassifPanel::OnButtonDelete(wxCommandEvent& event) EnableControls(false); } } else { - wxString es; - es << "Categories \"" << custom_cat_title << "\" is currently "; - es << "in use by another view. Please close or change all views "; - es << "using this custom categories before deleting."; - wxMessageDialog ed(NULL, es, "Error", wxOK | wxICON_ERROR); + wxString es = _("Categories \"%s\" is currently in use by another view. Please close or change all views using this custom categories before deleting."); + es = wxString::Format(es, custom_cat_title); + wxMessageDialog ed(NULL, es, _("Error"), wxOK | wxICON_ERROR); ed.ShowModal(); } } @@ -1671,7 +1739,7 @@ void CatClassifPanel::ResetValuesToDefault() unif_dist_mode = true; assoc_var_choice->SetSelection(0); assoc_var_tm_choice->SetSelection(0); - assoc_var_tm_choice->Enable(false); + assoc_var_tm_choice->Hide(); preview_var_choice->SetSelection(0); preview_var_tm_choice->SetSelection(0); @@ -1819,10 +1887,10 @@ void CatClassifPanel::InitFromCCData() int sel = assoc_var_choice->FindString(table_int->GetColName(col)); assoc_var_choice->SetSelection(sel); if (table_int->IsColTimeVariant(col)) { - assoc_var_tm_choice->Enable(true); + assoc_var_tm_choice->Show(); assoc_var_tm_choice->SetSelection(tm); } else { - assoc_var_tm_choice->Enable(false); + assoc_var_tm_choice->Hide(); } if (IsSyncVars()) { preview_var_choice->SetSelection(sel); @@ -1861,8 +1929,12 @@ void CatClassifPanel::InitFromCCData() SetSliderFromBreak(0); + if (GetBreakValsTypeChoice() != CatClassification::custom_break_vals) { + auto_labels_cb->SetValue(true); + } + hist_canvas->ChangeAll(&preview_data, &cc_data.breaks, &cc_data.colors); - Refresh(); + Refresh(); } /** @@ -1895,7 +1967,12 @@ void CatClassifPanel::InitAssocVarChoices() } assoc_var_choice->SetSelection(assoc_var_choice->FindString(cur_fc_str)); - assoc_var_tm_choice->Enable(table_int->IsColTimeVariant(cur_fc_str)); + + bool is_time_var = table_int->IsColTimeVariant(cur_fc_str); + if (is_time_var) + assoc_var_tm_choice->Show(); + else + assoc_var_tm_choice->Hide(); if (table_int->IsColTimeVariant(cur_fc_str) && assoc_var_tm_choice->GetSelection() == wxNOT_FOUND) { @@ -2072,8 +2149,7 @@ CatClassification::BreakValsType CatClassifPanel::GetBreakValsTypeChoice() } /** Set breaks_choice widget classification type */ -void CatClassifPanel::SetBreakValsTypeChoice( - CatClassification::BreakValsType ct) +void CatClassifPanel::SetBreakValsTypeChoice(CatClassification::BreakValsType ct) { int brs = 0; // quantile by default //if (ct == CatClassification::no_theme_break_vals) brs = 0; @@ -2315,7 +2391,7 @@ wxString CatClassifPanel::GetDefaultTitle(const wxString& field_name, { int max_tries = 500; int cur_try = 1; - wxString ret_title_base("Custom Breaks"); + wxString ret_title_base = _("Custom Breaks"); if (table_int->ColNameExists(field_name)) { ret_title_base << " (" << field_name; if (table_int->IsColTimeVariant(field_name)) { @@ -2345,6 +2421,36 @@ bool CatClassifPanel::IsOkToDelete(const wxString& custom_cat_title) notifyObservers. */ void CatClassifPanel::UpdateCCState() { + // try to add toolbar/menu items + wxMenuBar* mb = GdaFrame::GetGdaFrame()->GetMenuBar(); + int mPos = mb->FindMenu(_("Map")); + if (mPos > wxNOT_FOUND) { + wxMenu* menu = mb->GetMenu(mPos); + int m_id = menu->FindItem(_("Custom Breaks")); + wxMenuItem* mi = menu->FindItem(m_id); + if (mi) { + wxMenu* sm = mi->GetSubMenu(); + if (sm) { + // clean + wxMenuItemList items = sm->GetMenuItems(); + for (int i=0; iDelete(items[i]); + } + vector titles; + CatClassifManager* ccm = project->GetCatClassifManager(); + ccm->GetTitles(titles); + + sm->Append(XRCID("ID_NEW_CUSTOM_CAT_CLASSIF_A"), _("Create New Custom"), _("Create new custom categories classification.")); + sm->AppendSeparator(); + + for (size_t j=0; jAppend(GdaConst::ID_CUSTOM_CAT_CLASSIF_CHOICE_A0+j, titles[j]); + } + GdaFrame::GetGdaFrame()->Bind(wxEVT_COMMAND_MENU_SELECTED, &GdaFrame::OnCustomCategoryClick, GdaFrame::GetGdaFrame(), GdaConst::ID_CUSTOM_CAT_CLASSIF_CHOICE_A0, GdaConst::ID_CUSTOM_CAT_CLASSIF_CHOICE_A0 + titles.size()); + } + } + } + if (!cc_state) return; cc_state->SetCatClassif(cc_data); cc_state->notifyObservers(); @@ -2365,6 +2471,7 @@ END_EVENT_TABLE() CatClassifFrame::CatClassifFrame(wxFrame *parent, Project* project, bool useScientificNotation, + bool promptNew, const wxString& title, const wxPoint& pos, const wxSize& size, const long style) : TemplateFrame(parent, project, title, pos, size, style) @@ -2453,6 +2560,11 @@ CatClassifFrame::CatClassifFrame(wxFrame *parent, Project* project, DisplayStatusBar(true); SetTitle(template_canvas->GetCanvasTitle()); Show(true); + + if (promptNew) { + wxCommandEvent ev; + panel->OnButtonNew(ev); + } } ///MMM: Sort out in all Frames: what should be in the destructor? diff --git a/DialogTools/CatClassifDlg.h b/DialogTools/CatClassifDlg.h index 578f4c456..e686a913a 100644 --- a/DialogTools/CatClassifDlg.h +++ b/DialogTools/CatClassifDlg.h @@ -63,6 +63,7 @@ class CatClassifHistCanvas : public TemplateCanvas { virtual void DisplayRightClickMenu(const wxPoint& pos); virtual void update(HLStateInt* o); virtual wxString GetCanvasTitle(); + virtual wxString GetVariableNames(); virtual void SetCheckMarks(wxMenu* menu); virtual void DetermineMouseHoverObjects(wxPoint pt); virtual void UpdateSelection(bool shiftdown = false, @@ -70,13 +71,12 @@ class CatClassifHistCanvas : public TemplateCanvas { virtual void DrawSelectableShapes(wxMemoryDC &dc); virtual void DrawHighlightedShapes(wxMemoryDC &dc); -protected: virtual void PopulateCanvas(); + virtual void UpdateStatusBar(); void GetBarPositions(std::vector& x_center_pos, std::vector& x_left_pos, std::vector& x_right_pos); -public: void InitIntervals(); void UpdateIvalSelCnts(); static const int max_intervals; @@ -92,8 +92,9 @@ class CatClassifHistCanvas : public TemplateCanvas { double min, double max); protected: - virtual void UpdateStatusBar(); - + + Project* project; + int num_obs; Gda::dbl_int_pair_vec_type* data; Gda::dbl_int_pair_vec_type default_data; @@ -165,6 +166,8 @@ class CatClassifPanel: public wxPanel, public TableStateObserver void OnAutomaticLabelsCb(wxCommandEvent& event); void OnBrkRad(wxCommandEvent& event); void OnBrkTxtEnter(wxCommandEvent& event); + void OnUserInput(wxCommandEvent& event); + void OnBrkSlider(wxCommandEvent& event); void OnScrollThumbRelease(wxScrollEvent& event); void OnKillFocusEvent(wxFocusEvent& event); @@ -291,6 +294,7 @@ class CatClassifFrame : public TemplateFrame public: CatClassifFrame(wxFrame *parent, Project* project, bool useScientificNotation = false, + bool promptNew = false, const wxString& title = _("Category Editor"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = GdaConst::cat_classif_default_size, diff --git a/DialogTools/ConnectDatasourceDlg.cpp b/DialogTools/ConnectDatasourceDlg.cpp index 1da721789..62cef7ffb 100644 --- a/DialogTools/ConnectDatasourceDlg.cpp +++ b/DialogTools/ConnectDatasourceDlg.cpp @@ -30,11 +30,12 @@ #include #include #include -#include + #include #include #include #include +#include #include #include @@ -49,22 +50,21 @@ #include "../GeneralWxUtils.h" #include "../GdaCartoDB.h" #include "../GeoDa.h" -#include "ConnectDatasourceDlg.h" -#include "DatasourceDlg.h" +#include "../Project.h" #include "../rc/GeoDaIcon-16x16.xpm" +#include "ConnectDatasourceDlg.h" using namespace std; -class DnDFile : public wxFileDropTarget +DnDFile::DnDFile(ConnectDatasourceDlg *pOwner) +{ + m_pOwner = pOwner; +} + +DnDFile::~DnDFile() { -public: - DnDFile(ConnectDatasourceDlg *pOwner = NULL) { m_pOwner = pOwner; } - - virtual bool OnDropFiles(wxCoord x, wxCoord y, const wxArrayString& filenames); -private: - ConnectDatasourceDlg *m_pOwner; -}; +} bool DnDFile::OnDropFiles(wxCoord, wxCoord, const wxArrayString& filenames) { @@ -72,11 +72,11 @@ bool DnDFile::OnDropFiles(wxCoord, wxCoord, const wxArrayString& filenames) if (m_pOwner != NULL && nFiles > 0) { - wxFileName fn = wxFileName::FileName(filenames[0]); + wxString fpath = filenames[0]; + wxFileName fn = wxFileName::FileName(fpath); m_pOwner->ds_file_path = fn; - //wxCommandEvent ev; - //m_pOwner->OnOkClick(ev); - m_pOwner->TriggerOKClick(); + wxCommandEvent ev; + m_pOwner->OnOkClick(ev); } return true; @@ -94,7 +94,7 @@ RecentDatasource::RecentDatasource() { n_ds =0; // get a latest input DB information - std::vector ds_infos = OGRDataAdapter::GetInstance().GetHistory(KEY_NAME_IN_GDA_HISTORY); + std::vector ds_infos = OGRDataAdapter::GetInstance().GetHistory(KEY_NAME_IN_GDA_HISTORY); if (ds_infos.size() > 0) { ds_json_str = ds_infos[0]; @@ -370,15 +370,15 @@ wxString RecentDatasource::GetLayerName(wxString ds_name) // Class ConnectDatasourceDlg //////////////////////////////////////////////////////////////////////////////// -BEGIN_EVENT_TABLE( ConnectDatasourceDlg, wxFrame ) +BEGIN_EVENT_TABLE( ConnectDatasourceDlg, wxDialog ) EVT_BUTTON(XRCID("IDC_OPEN_IASC"), ConnectDatasourceDlg::OnBrowseDSfileBtn) EVT_BUTTON(XRCID("ID_BTN_LOOKUP_TABLE"), ConnectDatasourceDlg::OnLookupDSTableBtn) //EVT_BUTTON(XRCID("ID_CARTODB_LOOKUP_TABLE"), ConnectDatasourceDlg::OnLookupCartoDBTableBtn) //EVT_BUTTON(XRCID("ID_BTN_LOOKUP_WSLAYER"), ConnectDatasourceDlg::OnLookupWSLayerBtn) EVT_BUTTON(wxID_OK, ConnectDatasourceDlg::OnOkClick ) - EVT_BUTTON(wxID_CANCEL, ConnectDatasourceDlg::OnCancelClick ) - EVT_BUTTON(wxID_EXIT, ConnectDatasourceDlg::OnCancelClick ) - EVT_MENU(wxID_EXIT, ConnectDatasourceDlg::OnCancelClick ) + //EVT_BUTTON(wxID_CANCEL, ConnectDatasourceDlg::OnCancelClick ) + //EVT_BUTTON(wxID_EXIT, ConnectDatasourceDlg::OnCancelClick ) + //EVT_MENU(wxID_EXIT, ConnectDatasourceDlg::OnCancelClick ) END_EVENT_TABLE() @@ -386,7 +386,7 @@ ConnectDatasourceDlg::ConnectDatasourceDlg(wxWindow* parent, const wxPoint& pos, const wxSize& size, bool showCsvConfigure_, bool showRecentPanel_, - int dialogType) + int _dialogType) :DatasourceDlg(), datasource(0), scrl(0), recent_panel(0), showCsvConfigure(showCsvConfigure_), showRecentPanel(showRecentPanel_) { @@ -395,7 +395,8 @@ ConnectDatasourceDlg::ConnectDatasourceDlg(wxWindow* parent, const wxPoint& pos, // init controls defined in parent class DatasourceDlg::Init(); - type = dialogType; + //type = dialogType; + dialogType = _dialogType; ds_names.Add("GeoDa Project File (*.gda)|*.gda"); SetParent(parent); @@ -417,15 +418,15 @@ ConnectDatasourceDlg::ConnectDatasourceDlg(wxWindow* parent, const wxPoint& pos, } InitSamplePanel(); - } else { } - - m_drag_drop_box->SetDropTarget(new DnDFile(this)); + + m_dnd = new DnDFile(this); + m_drag_drop_box->SetDropTarget(m_dnd); SetIcon(wxIcon(GeoDaIcon_16x16_xpm)); Bind(wxEVT_COMMAND_MENU_SELECTED, &ConnectDatasourceDlg::BrowseDataSource, - this, DatasourceDlg::ID_DS_START, ID_DS_START + ds_names.Count()); + this, GdaConst::ID_CONNECT_POPUP_MENU, GdaConst::ID_CONNECT_POPUP_MENU + ds_names.Count()); Centre(); Move(pos); @@ -491,7 +492,7 @@ void ConnectDatasourceDlg::AddRecentItem(wxBoxSizer* sizer, wxScrolledWindow* sc #ifdef __WIN32__ int pad_remove_btn = 10; - wxButton *remove = new wxButton(scrl, id, wxT("Delete"), wxDefaultPosition, wxSize(36,18), wxBORDER_NONE|wxBU_EXACTFIT); + wxButton *remove = new wxButton(scrl, id, _("Delete"), wxDefaultPosition, wxSize(36,18), wxBORDER_NONE|wxBU_EXACTFIT); remove->SetFont(*GdaConst::extra_small_font); #else int pad_remove_btn = 0; @@ -542,9 +543,7 @@ void ConnectDatasourceDlg::OnRecent(wxCommandEvent& event) RecentDatasource recent_ds; wxString ds_name = recent_ds.GetDSName(recent_idx); // UTF-8 decoded - - wxLogMessage(ds_name); - + if (ds_name.EndsWith(".gda")) { GdaFrame* gda_frame = GdaFrame::GetGdaFrame(); gda_frame->OpenProject(ds_name); @@ -554,14 +553,14 @@ void ConnectDatasourceDlg::OnRecent(wxCommandEvent& event) layer_name = project->layername; } recent_ds.Add(ds_name, ds_name, layer_name); - EndDialog(); + EndDialog(wxID_CANCEL); } else { IDataSource* ds = recent_ds.GetDatasource(ds_name); if (ds == NULL) { // raise message dialog show can't connect to datasource wxString msg = _("Can't connect to datasource: ") + ds_name; - wxMessageDialog dlg (this, msg, "Error", wxOK | wxICON_ERROR); + wxMessageDialog dlg (this, msg, _("Error"), wxOK | wxICON_ERROR); dlg.ShowModal(); return; } else { @@ -569,8 +568,7 @@ void ConnectDatasourceDlg::OnRecent(wxCommandEvent& event) SaveRecentDataSource(ds, layername); layer_name = layername; datasource = ds; - is_ok_clicked = true; - EndDialog(); + EndDialog(wxID_OK); } } } @@ -611,13 +609,13 @@ void ConnectDatasourceDlg::InitRecentPanel() void ConnectDatasourceDlg::CreateControls() { if (showRecentPanel) { - wxXmlResource::Get()->LoadFrame(this, GetParent(),"IDD_CONNECT_DATASOURCE"); + wxXmlResource::Get()->LoadDialog(this, GetParent(),"IDD_CONNECT_DATASOURCE"); recent_nb = XRCCTRL(*this, "IDC_DS_LIST", wxNotebook); recent_nb->SetSelection(1); recent_panel = XRCCTRL(*this, "dsRecentListSizer", wxPanel); smaples_panel = XRCCTRL(*this, "dsSampleList", wxPanel); } else { - wxXmlResource::Get()->LoadFrame(this, GetParent(),"IDD_CONNECT_DATASOURCE_SIMPLE"); + wxXmlResource::Get()->LoadDialog(this, GetParent(),"IDD_CONNECT_DATASOURCE_SIMPLE"); } FindWindow(XRCID("wxID_OK"))->Enable(true); @@ -644,7 +642,7 @@ void ConnectDatasourceDlg::CreateControls() DatasourceDlg::CreateControls(); // setup WSF auto-completion - std::vector ws_url_cands = OGRDataAdapter::GetInstance().GetHistory("ws_url"); + std::vector ws_url_cands = OGRDataAdapter::GetInstance().GetHistory("ws_url"); m_webservice_url->SetAutoList(ws_url_cands); } @@ -685,7 +683,7 @@ void ConnectDatasourceDlg::OnLookupDSTableBtn( wxCommandEvent& event ) } catch (GdaException& e) { wxString msg; msg << e.what(); - wxMessageDialog dlg(this, msg , "Error", wxOK | wxICON_ERROR); + wxMessageDialog dlg(this, msg , _("Error"), wxOK | wxICON_ERROR); dlg.ShowModal(); if( datasource!= NULL && msg.StartsWith("Failed to open data source") ) { @@ -712,13 +710,6 @@ void ConnectDatasourceDlg::OnLookupCartoDBTableBtn( wxCommandEvent& event ) } } - -void ConnectDatasourceDlg::TriggerOKClick() -{ - wxCommandEvent evt = wxCommandEvent(wxEVT_COMMAND_BUTTON_CLICKED, wxID_OK ); - AddPendingEvent(evt); -} - /** * This function handles the event of user click OK button. * When user chooses a data source, validate it first, @@ -731,6 +722,13 @@ void ConnectDatasourceDlg::OnOkClick( wxCommandEvent& event ) try { // Open GeoDa project file direclty if (ds_file_path.GetExt().Lower() == "gda") { + if (dialogType == 1) { + // in Merge/Stack (when dialogType == 1), user can't open gda file + wxString msg = _("Please open a data file rather than a project file (*.gda)."); + wxMessageDialog dlg(this, msg, _("Info"), wxOK | wxICON_ERROR); + dlg.ShowModal(); + return; + } GdaFrame* gda_frame = GdaFrame::GetGdaFrame(); if (gda_frame) { gda_frame->OpenProject(ds_file_path.GetFullPath()); @@ -745,7 +743,7 @@ void ConnectDatasourceDlg::OnOkClick( wxCommandEvent& event ) } catch( GdaException ex) { wxLogMessage(ex.what()); } - EndDialog(); + EndDialog(wxID_CANCEL); } return; } @@ -764,13 +762,20 @@ void ConnectDatasourceDlg::OnOkClick( wxCommandEvent& event ) int datasource_type = m_ds_notebook->GetSelection(); if (datasource_type == 0) { // File table is selected - if (layer_name.IsEmpty()) { - layername = ds_file_path.GetName(); - } else { - // user may select a layer name from Popup dialog that displays - // all layer names, see PromptDSLayers() - layername = layer_name; - } + + if ( wxDirExists(ds_file_path.GetFullPath()) ) { + // dra-n-drop a directory + PromptDSLayers(datasource); + layername = layer_name; + } else { + if (layer_name.IsEmpty()) { + layername = ds_file_path.GetName(); + } else { + // user may select a layer name from Popup dialog that displays + // all layer names, see PromptDSLayers() + layername = layer_name; + } + } } else if (datasource_type == 1) { // Database tab is selected @@ -805,18 +810,17 @@ void ConnectDatasourceDlg::OnOkClick( wxCommandEvent& event ) SaveRecentDataSource(datasource, layer_name); - is_ok_clicked = true; - EndDialog(); + EndDialog(wxID_OK); } catch (GdaException& e) { wxString msg; msg << e.what(); - wxMessageDialog dlg(this, msg, "Error", wxOK | wxICON_ERROR); + wxMessageDialog dlg(this, msg, _("Error"), wxOK | wxICON_ERROR); dlg.ShowModal(); } catch (...) { - wxString msg = "Unknow exception. Please contact GeoDa support."; - wxMessageDialog dlg(this, msg , "Error", wxOK | wxICON_ERROR); + wxString msg = _("Unknow exception. Please contact GeoDa support."); + wxMessageDialog dlg(this, msg , _("Error"), wxOK | wxICON_ERROR); dlg.ShowModal(); } wxLogMessage("Exiting ConnectDatasourceDlg::OnOkClick"); @@ -883,7 +887,7 @@ IDataSource* ConnectDatasourceDlg::CreateDataSource() else if (cur_sel == DBTYPE_MYSQL) ds_type = GdaConst::ds_mysql; //else if (cur_sel == 4) ds_type = GdaConst::ds_ms_sql; else { - wxString msg = "The selected database driver is not supported on this platform. Please check GeoDa website for more information about database support and connection."; + wxString msg = _("The selected database driver is not supported on this platform. Please check GeoDa website for more information about database support and connection."); throw GdaException(msg.mb_str()); } @@ -905,14 +909,15 @@ IDataSource* ConnectDatasourceDlg::CreateDataSource() wxRegEx regex; regex.Compile("[0-9]+"); if (!regex.Matches( dbport )){ - throw GdaException(wxString("Database port is empty. Please input one.").mb_str()); + wxString msg = _("Database port is empty. Please input one."); + throw GdaException(msg.mb_str()); } wxString error_msg; - if (dbhost.IsEmpty()) error_msg = "Please input database host."; - else if (dbname.IsEmpty()) error_msg = "Please input database name."; - else if (dbport.IsEmpty()) error_msg = "Please input database port."; - else if (dbuser.IsEmpty()) error_msg = "Please input user name."; - else if (dbpwd.IsEmpty()) error_msg = "Please input password."; + if (dbhost.IsEmpty()) error_msg = _("Please input database host."); + else if (dbname.IsEmpty()) error_msg = _("Please input database name."); + else if (dbport.IsEmpty()) error_msg = _("Please input database port."); + else if (dbuser.IsEmpty()) error_msg = _("Please input user name."); + else if (dbpwd.IsEmpty()) error_msg = _("Please input password."); if (!error_msg.IsEmpty()) { throw GdaException(error_msg.mb_str() ); } @@ -938,10 +943,12 @@ IDataSource* ConnectDatasourceDlg::CreateDataSource() wxRegEx regex; regex.Compile("^(https|http)://"); if (!regex.Matches( ws_url )){ - throw GdaException(wxString("Please input a valid url address.").mb_str()); + wxString msg = _("Please input a valid url address."); + throw GdaException(msg.mb_str()); } if (ws_url.IsEmpty()) { - throw GdaException(wxString("Please input a valid url.").mb_str()); + wxString msg = _("Please input a valid url."); + throw GdaException(msg.mb_str()); } else { OGRDataAdapter::GetInstance().AddHistory("ws_url", ws_url.ToStdString()); } @@ -961,23 +968,25 @@ IDataSource* ConnectDatasourceDlg::CreateDataSource() } else if ( datasource_type == 3 ) { - std::string user(m_cartodb_uname->GetValue().Trim().mb_str()); - std::string key(m_cartodb_key->GetValue().Trim().mb_str()); + wxString user =m_cartodb_uname->GetValue().Trim(); + wxString key = m_cartodb_key->GetValue().Trim(); if (user.empty()) { - throw GdaException("Please input Carto User Name."); + wxString msg = _("Please input Carto User Name."); + throw GdaException(msg.mb_str()); } if (key.empty()) { - throw GdaException("Please input Carto App Key."); + wxString msg = _("Please input Carto App Key."); + throw GdaException(msg.mb_str()); } - CPLSetConfigOption("CARTODB_API_KEY", key.c_str()); - OGRDataAdapter::GetInstance().AddEntry("cartodb_key", key.c_str()); - OGRDataAdapter::GetInstance().AddEntry("cartodb_user", user.c_str()); + CPLSetConfigOption("CARTODB_API_KEY", (const char*)key.mb_str()); + OGRDataAdapter::GetInstance().AddEntry("cartodb_key", key); + OGRDataAdapter::GetInstance().AddEntry("cartodb_user", user); CartoDBProxy::GetInstance().SetKey(key); CartoDBProxy::GetInstance().SetUserName(user); - wxString url = "CartoDB:" + user; + wxString url = "Carto:" + user; datasource = new WebServiceDataSource(GdaConst::ds_cartodb, url); } @@ -1019,10 +1028,10 @@ void ConnectDatasourceDlg::InitSamplePanel() int n = 11; // number of sample dataset for (int i=0; iSetSizer( sizer ); @@ -1040,7 +1049,7 @@ void ConnectDatasourceDlg::InitSamplePanel() void ConnectDatasourceDlg::AddSampleItem(wxBoxSizer* sizer, wxScrolledWindow* scrl, wxString name, - wxString ds_name, + wxString ds_url, wxString ds_layername, wxString ds_thumb, int id) { @@ -1067,13 +1076,13 @@ void ConnectDatasourceDlg::AddSampleItem(wxBoxSizer* sizer, obs_txt->SetToolTip(name); text_sizer->Add(obs_txt, 0, wxALIGN_LEFT | wxALL, 5); - wxString lbl_ds_name = ds_name; + wxString lbl_ds_name = ds_url; lbl_ds_name = GenUtils::PadTrim(lbl_ds_name, 50, false); - wxStaticText* filepath; - filepath = new wxStaticText(scrl, wxID_ANY, lbl_ds_name); + wxHyperlinkCtrl* filepath; + filepath = new wxHyperlinkCtrl(scrl, wxID_ANY, ds_url, ds_url); filepath->SetFont(*GdaConst::extra_small_font); filepath->SetForegroundColour(wxColour(70,70,70)); - filepath->SetToolTip(ds_name); + filepath->SetToolTip(ds_url); text_sizer->Add(filepath, 1, wxALIGN_LEFT | wxALL, 5); wxString file_path_str; @@ -1126,14 +1135,13 @@ void ConnectDatasourceDlg::OnSample(wxCommandEvent& event) if (ds == NULL) { // raise message dialog show can't connect to datasource wxString msg = _("Can't connect to datasource: ") + ds_name; - wxMessageDialog dlg (this, msg, "Error", wxOK | wxICON_ERROR); + wxMessageDialog dlg (this, msg, _("Error"), wxOK | wxICON_ERROR); dlg.ShowModal(); return; } else { datasource = ds; layer_name = layername; - is_ok_clicked = true; - EndDialog(); + EndDialog(wxID_OK); } } diff --git a/DialogTools/ConnectDatasourceDlg.h b/DialogTools/ConnectDatasourceDlg.h index 864c18f00..ee30f7d39 100644 --- a/DialogTools/ConnectDatasourceDlg.h +++ b/DialogTools/ConnectDatasourceDlg.h @@ -26,11 +26,13 @@ #include #include #include - +#include #include + #include "../DataViewer/DataSource.h" #include "AutoCompTextCtrl.h" #include "DatasourceDlg.h" +#include "DatasourceDlg.h" using namespace std; @@ -87,6 +89,7 @@ class RecentDatasource // Class ConnectDatasourceDlg // //////////////////////////////////////////////////////////////////////////////// +class DnDFile; class ConnectDatasourceDlg: public DatasourceDlg { public: @@ -97,9 +100,8 @@ class ConnectDatasourceDlg: public DatasourceDlg bool showRecentPanel=GdaConst::show_recent_sample_connect_ds_dialog, int dialogType = 0); virtual ~ConnectDatasourceDlg(); - - void TriggerOKClick(); virtual void OnOkClick( wxCommandEvent& event ); + void CreateControls(); void OnLookupWSLayerBtn( wxCommandEvent& event ); void OnLookupDSTableBtn( wxCommandEvent& event ); @@ -108,6 +110,7 @@ class ConnectDatasourceDlg: public DatasourceDlg protected: + int dialogType; bool showCsvConfigure; bool showRecentPanel; @@ -123,6 +126,7 @@ class ConnectDatasourceDlg: public DatasourceDlg wxNotebook* recent_nb; wxCheckBox* noshow_recent; wxChoice* m_web_choice; + DnDFile* m_dnd; int base_xrcid_recent_thumb; int base_xrcid_sample_thumb; @@ -148,4 +152,17 @@ class ConnectDatasourceDlg: public DatasourceDlg DECLARE_EVENT_TABLE() }; +// Drag and Drop Area +class DnDFile : public wxFileDropTarget +{ +public: + DnDFile(ConnectDatasourceDlg *pOwner = NULL); + ~DnDFile(); + + virtual bool OnDropFiles(wxCoord x, wxCoord y, const wxArrayString& filenames); + +private: + ConnectDatasourceDlg *m_pOwner; +}; + #endif diff --git a/DialogTools/CreateGridDlg.cpp b/DialogTools/CreateGridDlg.cpp index 42c99bdb4..22cae41ca 100644 --- a/DialogTools/CreateGridDlg.cpp +++ b/DialogTools/CreateGridDlg.cpp @@ -38,6 +38,7 @@ IMPLEMENT_CLASS( CreateGridDlg, wxDialog ) BEGIN_EVENT_TABLE( CreateGridDlg, wxDialog ) + EVT_CLOSE(CreateGridDlg::OnClose ) EVT_BUTTON( XRCID("IDCANCEL"), CreateGridDlg::OnCancelClick ) EVT_BUTTON( XRCID("IDC_REFERENCEFILE"), CreateGridDlg::OnCReferencefileClick ) @@ -54,10 +55,17 @@ BEGIN_EVENT_TABLE( CreateGridDlg, wxDialog ) EVT_RADIOBUTTON( XRCID("IDC_RADIO3"), CreateGridDlg::OnCRadio3Selected ) END_EVENT_TABLE() -CreateGridDlg::CreateGridDlg( ) +CreateGridDlg::~CreateGridDlg( ) { } +void CreateGridDlg::OnClose(wxCloseEvent& event) +{ + // Note: it seems that if we don't explictly capture the close event + // and call Destory, then the destructor is not called. + Destroy(); +} + CreateGridDlg::CreateGridDlg( wxWindow* parent, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style ) @@ -238,32 +246,23 @@ void CreateGridDlg::OnCReferencefile2Click( wxCommandEvent& event ) wxLogMessage("In CreateGridDlg::OnCReferencefile2Click()"); try{ - wxWindowList::compatibility_iterator node = wxTopLevelWindows.GetFirst(); - while (node) { - wxWindow* win = node->GetData(); - if (ConnectDatasourceDlg* w = dynamic_cast(win)) { - if (w->GetType() == 0) { - w->Show(true); - w->Maximize(false); - w->Raise(); - return; - } - } - node = node->GetNext(); - } - - ConnectDatasourceDlg dlg(this); - if (dlg.ShowModal() != wxID_OK) + wxPoint pos = GetPosition(); + int dialog_type = 1; // no gda is allowed + bool showCsvConfigure = false; + bool showRecentPanel = false; + ConnectDatasourceDlg connect_dlg(this, pos, wxDefaultSize, showCsvConfigure, showRecentPanel, dialog_type); + if (connect_dlg.ShowModal() != wxID_OK) { return; + } - wxString proj_title = dlg.GetProjectTitle(); - wxString layer_name = dlg.GetLayerName(); - IDataSource* datasource = dlg.GetDataSource(); + wxString proj_title = connect_dlg.GetProjectTitle(); + wxString layer_name = connect_dlg.GetLayerName(); + IDataSource* datasource = connect_dlg.GetDataSource(); wxString ds_name = datasource->GetOGRConnectStr(); GdaConst::DataSourceType ds_type = datasource->GetType(); OGRDatasourceProxy* ogr_ds = new OGRDatasourceProxy(ds_name, ds_type, false); - OGRLayerProxy* ogr_layer = ogr_ds->GetLayerProxy(layer_name.ToStdString()); + OGRLayerProxy* ogr_layer = ogr_ds->GetLayerProxy(layer_name); bool validExt = ogr_layer->GetExtent(m_xBot, m_yBot, m_xTop, m_yTop); delete ogr_ds; ogr_ds = NULL; @@ -285,14 +284,15 @@ void CreateGridDlg::OnCreateClick( wxCommandEvent& event ) { wxLogMessage("In CreateGridDlg::OnCreateClick()"); if (CheckBBox()) { - CreateGrid(); + if (CreateGrid() == false) + return; hasCreated = true; } else { - wxMessageBox(_("Please fix the grid bounding box!")); + wxMessageBox(_("Please fix the grid bounding box.")); return; } + wxMessageBox(_("Grid file was successfully created.")); event.Skip(); - EndDialog(wxID_OK); } void CreateGridDlg::OnCRadio1Selected( wxCommandEvent& event ) @@ -348,7 +348,7 @@ bool CreateGridDlg::CheckBBox() return true; } -void CreateGridDlg::CreateGrid() +bool CreateGridDlg::CreateGrid() { FindWindow(XRCID("ID_CREATE"))->Enable(false); FindWindow(XRCID("IDCANCEL"))->Enable(false); @@ -391,10 +391,11 @@ void CreateGridDlg::CreateGrid() delete[] pts; } } - - ExportDataDlg dlg(NULL, grids, Shapefile::POLYGON); - dlg.Raise(); - dlg.ShowModal(); + + + ExportDataDlg export_dlg(this, grids, Shapefile::POLYGON); + + bool result = export_dlg.ShowModal() == wxID_OK; m_nCount = nMaxCount; @@ -408,13 +409,17 @@ void CreateGridDlg::CreateGrid() x = NULL; delete [] y; y = NULL; + + return result; } void CreateGridDlg::OnCEdit1Updated( wxCommandEvent& event ) { wxLogMessage("In CreateGridDlg::OnCEdit1Updated()"); if (!isCreated) return; - m_lower_x->GetValue().ToDouble(&m_xBot); + wxString input = m_lower_x->GetValue(); + wxLogMessage(input); + input.ToDouble(&m_xBot); EnableItems(); } @@ -423,7 +428,9 @@ void CreateGridDlg::OnCEdit2Updated( wxCommandEvent& event ) { wxLogMessage("In CreateGridDlg::OnCEdit2Updated()"); if (!isCreated) return; - m_lower_y->GetValue().ToDouble(&m_yBot); + wxString input = m_lower_y->GetValue(); + wxLogMessage(input); + input.ToDouble(&m_yBot); EnableItems(); } @@ -431,7 +438,9 @@ void CreateGridDlg::OnCEdit3Updated( wxCommandEvent& event ) { wxLogMessage("In CreateGridDlg::OnCEdit3Updated()"); if (!isCreated) return; - m_upper_x->GetValue().ToDouble(&m_xTop); + wxString input = m_upper_x->GetValue(); + wxLogMessage(input); + input.ToDouble(&m_xTop); EnableItems(); } @@ -439,6 +448,8 @@ void CreateGridDlg::OnCEdit4Updated( wxCommandEvent& event ) { wxLogMessage("In CreateGridDlg::OnCEdit4Updated()"); if (!isCreated) return; - m_upper_y->GetValue().ToDouble(&m_yTop); + wxString input = m_upper_y->GetValue(); + wxLogMessage(input); + input.ToDouble(&m_yTop); EnableItems(); } diff --git a/DialogTools/CreateGridDlg.h b/DialogTools/CreateGridDlg.h index ddb13c696..cf21166e7 100644 --- a/DialogTools/CreateGridDlg.h +++ b/DialogTools/CreateGridDlg.h @@ -20,7 +20,8 @@ #ifndef __GEODA_CENTER_CREATE_GRID_DLG_H__ #define __GEODA_CENTER_CREATE_GRID_DLG_H__ -#include "../ShapeOperations/Box.h" +class ExportDataDlg; +class ConnectDatasourceDlg; class CreateGridDlg: public wxDialog { @@ -28,7 +29,7 @@ class CreateGridDlg: public wxDialog DECLARE_EVENT_TABLE() public: - CreateGridDlg( ); + ~CreateGridDlg( ); CreateGridDlg( wxWindow* parent, wxWindowID id = -1, const wxString& caption = _("Creating Grid"), const wxPoint& pos = wxDefaultPosition, @@ -43,6 +44,7 @@ class CreateGridDlg: public wxDialog void CreateControls(); + void OnClose(wxCloseEvent& event); void OnCancelClick( wxCommandEvent& event ); void OnCReferencefileClick( wxCommandEvent& event ); void OnCBrowseOfileClick( wxCommandEvent& event ); @@ -65,17 +67,16 @@ class CreateGridDlg: public wxDialog wxTextCtrl* m_inputfileshp; wxTextCtrl* m_rows; wxTextCtrl* m_cols; - + void EnableItems(); bool CheckBBox(); - void CreateGrid(); + bool CreateGrid(); int m_check; int m_nCount; int m_nTimer; enum { nMaxCount = 10000 }; - Box m_BigBox; double m_xBot,m_yBot,m_xTop,m_yTop; bool hasCreated; diff --git a/DialogTools/CreatingWeightDlg.cpp b/DialogTools/CreatingWeightDlg.cpp index 4ece6814d..4cd79e56a 100644 --- a/DialogTools/CreatingWeightDlg.cpp +++ b/DialogTools/CreatingWeightDlg.cpp @@ -50,36 +50,38 @@ #include "CreatingWeightDlg.h" BEGIN_EVENT_TABLE( CreatingWeightDlg, wxDialog ) -EVT_CLOSE( CreatingWeightDlg::OnClose ) +EVT_CHOICE(XRCID("IDC_DISTANCE_METRIC"), CreatingWeightDlg::OnDistanceChoiceSelected ) EVT_BUTTON( XRCID("ID_CREATE_ID"), CreatingWeightDlg::OnCreateNewIdClick ) EVT_CHOICE(XRCID("IDC_IDVARIABLE"), CreatingWeightDlg::OnIdVariableSelected ) -EVT_CHOICE(XRCID("IDC_DISTANCE_METRIC"), CreatingWeightDlg::OnDistanceChoiceSelected ) EVT_CHOICE(XRCID("IDC_XCOORDINATES"), CreatingWeightDlg::OnXSelected ) EVT_CHOICE(XRCID("IDC_YCOORDINATES"), CreatingWeightDlg::OnYSelected ) EVT_CHOICE(XRCID("IDC_XCOORD_TIME"), CreatingWeightDlg::OnXTmSelected ) EVT_CHOICE(XRCID("IDC_YCOORD_TIME"), CreatingWeightDlg::OnYTmSelected ) -EVT_RADIOBUTTON( XRCID("IDC_RADIO_QUEEN"), CreatingWeightDlg::OnCRadioQueenSelected ) EVT_SPIN( XRCID("IDC_SPIN_ORDEROFCONTIGUITY"), CreatingWeightDlg::OnCSpinOrderofcontiguityUpdated ) -EVT_RADIOBUTTON( XRCID("IDC_RADIO_ROOK"), CreatingWeightDlg::OnCRadioRookSelected ) -EVT_RADIOBUTTON( XRCID("IDC_RADIO_DISTANCE"), CreatingWeightDlg::OnCRadioDistanceSelected ) EVT_TEXT( XRCID("IDC_THRESHOLD_EDIT"), CreatingWeightDlg::OnCThresholdTextEdit ) +EVT_TEXT( XRCID("IDC_BANDWIDTH_EDIT"), CreatingWeightDlg::OnCBandwidthThresholdTextEdit ) EVT_SLIDER( XRCID("IDC_THRESHOLD_SLIDER"), CreatingWeightDlg::OnCThresholdSliderUpdated ) - -EVT_RADIOBUTTON( XRCID("IDC_RADIO_KNN"), CreatingWeightDlg::OnCRadioKnnSelected ) +EVT_SLIDER( XRCID("IDC_BANDWIDTH_SLIDER"), CreatingWeightDlg::OnCBandwidthThresholdSliderUpdated ) EVT_SPIN( XRCID("IDC_SPIN_KNN"), CreatingWeightDlg::OnCSpinKnnUpdated ) +EVT_SPIN( XRCID("IDC_SPIN_KERNEL_KNN"), CreatingWeightDlg::OnCSpinKernelKnnUpdated ) EVT_BUTTON( XRCID("wxID_OK"), CreatingWeightDlg::OnCreateClick ) EVT_CHECKBOX( XRCID("IDC_PRECISION_CBX"), CreatingWeightDlg::OnPrecisionThresholdCheck) +EVT_CHECKBOX( XRCID("IDC_CHK_INVERSE_DISTANCE"), CreatingWeightDlg::OnInverseDistCheck) +EVT_CHECKBOX( XRCID("IDC_CHK_INVERSE_DISTANCE_KNN"), CreatingWeightDlg::OnInverseKNNCheck) +EVT_SPIN( XRCID("IDC_SPIN_POWER"), CreatingWeightDlg::OnCSpinPowerInverseDistUpdated ) +EVT_SPIN( XRCID("IDC_SPIN_POWER_KNN"), CreatingWeightDlg::OnCSpinPowerInverseKNNUpdated ) END_EVENT_TABLE() CreatingWeightDlg::CreatingWeightDlg(wxWindow* parent, Project* project_s, + bool user_xy_s, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style ) -: all_init(false), +: all_init(false), user_xy(user_xy_s), m_thres_delta_factor(1.00001), m_is_arc(false), m_arc_in_km(false), @@ -101,6 +103,9 @@ suspend_table_state_updates(false) frames_manager->registerObserver(this); table_state->registerObserver(this); w_man_state->registerObserver(this); + // use_xy is for MDS creating weights only + if (!user_xy) + Connect( wxEVT_CLOSE_WINDOW, wxCloseEventHandler(CreatingWeightDlg::OnClose) ); } CreatingWeightDlg::~CreatingWeightDlg() @@ -115,12 +120,11 @@ void CreatingWeightDlg::OnClose(wxCloseEvent& ev) wxLogMessage("Close CreatingWeightDlg"); // Note: it seems that if we don't explictly capture the close event // and call Destory, then the destructor is not called. - Destroy(); + if (!user_xy) + Destroy(); } -bool CreatingWeightDlg::Create( wxWindow* parent, wxWindowID id, - const wxString& caption, const wxPoint& pos, - const wxSize& size, long style ) +bool CreatingWeightDlg::Create(wxWindow* parent, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style) { m_id_field = 0; m_radio_queen = 0; @@ -135,12 +139,16 @@ bool CreatingWeightDlg::Create( wxWindow* parent, wxWindowID id, m_Y = 0; m_X_time = 0; m_Y_time = 0; - m_radio_thresh = 0; m_threshold = 0; m_sliderdistance = 0; - m_radio_knn = 0; m_neighbors = 0; m_spinneigh = 0; + m_spinn_inverse = 0; + m_kernel_neighbors = 0; + m_spinn_kernel = 0; + m_kernel_methods = 0; + m_kernel_diagnals = 0; + m_const_diagnals = 0; SetParent(parent); CreateControls(); @@ -153,31 +161,54 @@ bool CreatingWeightDlg::Create( wxWindow* parent, wxWindowID id, void CreatingWeightDlg::CreateControls() { - wxXmlResource::Get()->LoadDialog(this, GetParent(), - "IDD_WEIGHTS_FILE_CREATION"); + wxXmlResource::Get()->LoadDialog(this, GetParent(), "IDD_WEIGHTS_FILE_CREATION"); m_id_field = XRCCTRL(*this, "IDC_IDVARIABLE", wxChoice); - m_contiguity = XRCCTRL(*this, "IDC_EDIT_ORDEROFCONTIGUITY", wxTextCtrl); - m_spincont = XRCCTRL(*this, "IDC_SPIN_ORDEROFCONTIGUITY", wxSpinButton); + // contiguity weight + m_nb_weights_type = XRCCTRL(*this, "IDC_NB_WEIGHTS_CREATION", wxNotebook); + m_radio_queen = XRCCTRL(*this, "IDC_RADIO_QUEEN", wxRadioButton); + m_contiguity = XRCCTRL(*this, "IDC_EDIT_ORDEROFCONTIGUITY", wxTextCtrl); + m_spincont = XRCCTRL(*this, "IDC_SPIN_ORDEROFCONTIGUITY", wxSpinButton); + m_radio_rook = XRCCTRL(*this, "IDC_RADIO_ROOK", wxRadioButton); m_include_lower = XRCCTRL(*this, "IDC_CHECK1", wxCheckBox); m_cbx_precision_threshold= XRCCTRL(*this, "IDC_PRECISION_CBX", wxCheckBox); + m_txt_precision_threshold = XRCCTRL(*this, "IDC_PRECISION_THRESHOLD_EDIT", wxTextCtrl); + // distance weight m_dist_choice = XRCCTRL(*this, "IDC_DISTANCE_METRIC", wxChoice); m_X = XRCCTRL(*this, "IDC_XCOORDINATES", wxChoice); + m_X_time = XRCCTRL(*this, "IDC_XCOORD_TIME", wxChoice); m_Y = XRCCTRL(*this, "IDC_YCOORDINATES", wxChoice); - m_X_time = XRCCTRL(*this, "IDC_XCOORD_TIME", wxChoice); m_Y_time = XRCCTRL(*this, "IDC_YCOORD_TIME", wxChoice); - m_X_time->Show(false); - m_Y_time->Show(false); + m_nb_distance_methods = XRCCTRL(*this, "IDC_NB_DISTANCE_WEIGHTS", wxNotebook); m_threshold = XRCCTRL(*this, "IDC_THRESHOLD_EDIT", wxTextCtrl); - m_txt_precision_threshold = XRCCTRL(*this, "IDC_PRECISION_THRESHOLD_EDIT", - wxTextCtrl); m_sliderdistance = XRCCTRL(*this, "IDC_THRESHOLD_SLIDER", wxSlider); - m_radio_queen = XRCCTRL(*this, "IDC_RADIO_QUEEN", wxRadioButton); - m_radio_rook = XRCCTRL(*this, "IDC_RADIO_ROOK", wxRadioButton); - m_radio_thresh = XRCCTRL(*this, "IDC_RADIO_DISTANCE", wxRadioButton); - m_radio_knn = XRCCTRL(*this, "IDC_RADIO_KNN", wxRadioButton); - m_neighbors = XRCCTRL(*this, "IDC_EDIT_KNN", wxTextCtrl); + m_neighbors = XRCCTRL(*this, "IDC_EDIT_KNN", wxTextCtrl); m_spinneigh = XRCCTRL(*this, "IDC_SPIN_KNN", wxSpinButton); - + m_kernel_methods = XRCCTRL(*this, "IDC_KERNEL_METHODS", wxChoice); + m_kernel_neighbors = XRCCTRL(*this, "IDC_EDIT_KERNEL_KNN", wxTextCtrl); + m_spinn_kernel = XRCCTRL(*this, "IDC_SPIN_KERNEL_KNN", wxSpinButton); + m_radio_adaptive_bandwidth = XRCCTRL(*this, "IDC_RADIO_ADAPTIVE_BANDWIDTH", wxRadioButton); + m_radio_auto_bandwidth = XRCCTRL(*this, "IDC_RADIO_AUTO_BANDWIDTH", wxRadioButton); + m_radio_manu_bandwdith = XRCCTRL(*this, "IDC_RADIO_MANU_BANDWIDTH", wxRadioButton); + m_manu_bandwidth = XRCCTRL(*this, "IDC_BANDWIDTH_EDIT", wxTextCtrl); + m_bandwidth_slider = XRCCTRL(*this, "IDC_BANDWIDTH_SLIDER", wxSlider); + m_kernel_diagnals = XRCCTRL(*this, "IDC_KERNEL_DIAGNAL_CHECK", wxRadioButton); + m_const_diagnals = XRCCTRL(*this, "IDC_CONST_DIAGNAL_CHECK", wxRadioButton); + m_use_inverse = XRCCTRL(*this, "IDC_CHK_INVERSE_DISTANCE", wxCheckBox); + m_power = XRCCTRL(*this, "IDC_EDIT_POWER", wxTextCtrl); + m_spinn_inverse = XRCCTRL(*this, "IDC_SPIN_POWER", wxSpinButton); + m_use_inverse_knn = XRCCTRL(*this, "IDC_CHK_INVERSE_DISTANCE_KNN", wxCheckBox); + m_power_knn = XRCCTRL(*this, "IDC_EDIT_POWER_KNN", wxTextCtrl); + m_spinn_inverse_knn = XRCCTRL(*this, "IDC_SPIN_POWER_KNN", wxSpinButton); + + m_btn_ok = XRCCTRL(*this, "wxID_OK", wxButton); + + m_X_time->Show(false); + m_Y_time->Show(false); + + m_txt_precision_threshold->Enable(false); + m_power->Enable(false); + m_power_knn->Enable(false); + InitDlg(); } @@ -191,12 +222,9 @@ void CreatingWeightDlg::OnCreateNewIdClick( wxCommandEvent& event ) // We know that the new id has been added to the the table in memory col_id_map.clear(); table_int->FillColIdMap(col_id_map); - InitFields(); m_id_field->SetSelection(0); - - EnableDistanceRadioButtons(m_id_field->GetSelection() != wxNOT_FOUND); - EnableContiguityRadioButtons((m_id_field->GetSelection() != wxNOT_FOUND) && !project->IsTableOnlyProject()); + bool valid = m_id_field->GetSelection() != wxNOT_FOUND; UpdateCreateButtonState(); } else { // A new id was not added to the dbf file, so do nothing. @@ -205,256 +233,16 @@ void CreatingWeightDlg::OnCreateNewIdClick( wxCommandEvent& event ) event.Skip(); } -void CreatingWeightDlg::OnCreateClick( wxCommandEvent& event ) +void CreatingWeightDlg::OnInverseDistCheck( wxCommandEvent& event ) { - wxLogMessage("Click CreatingWeightDlg::OnCreateClick"); - try { - CreateWeights(); - } catch(GdaException e) { - wxString msg; - msg << e.what(); - wxMessageDialog dlg(this, msg , _("Error"), wxOK | wxICON_ERROR); - dlg.ShowModal(); - } + wxLogMessage("Click CreatingWeightDlg::OnInverseDistCheck"); + m_power->Enable( m_use_inverse->IsChecked() ); } -void CreatingWeightDlg::CreateWeights() +void CreatingWeightDlg::OnInverseKNNCheck( wxCommandEvent& event ) { - WeightsMetaInfo wmi; - - if (m_radio == NO_RADIO) { - wxString msg = _("Please select a weights type."); - wxMessageDialog dlg(this, msg, _("Error"), wxOK | wxICON_ERROR); - dlg.ShowModal(); - return; - } - - if (m_radio == THRESH) { - if (!m_thres_val_valid) { - wxString msg = _("The currently entered threshold value is not a valid number. Please move the slider, or enter a valid number."); - wxMessageDialog dlg(this, msg, _("Error"), wxOK | wxICON_ERROR); - dlg.ShowModal(); - return; - } - if (m_threshold_val*m_thres_delta_factor < m_thres_min) { - wxString msg = wxString::Format(_("The currently entered threshold value of %f is less than %f which is the minimum value for which there will be no neighborless observations (isolates). \n\nPress Yes to proceed anyhow, press No to abort."), m_threshold_val, m_thres_min); - wxMessageDialog dlg(this, msg, _("Warning"), - wxYES_NO | wxNO_DEFAULT | wxICON_QUESTION ); - if (dlg.ShowModal() != wxID_YES) - return; - } - } - - wxString wildcard; - wxString defaultFile(project->GetProjectTitle()); - if (IsSaveAsGwt()) { - defaultFile += ".gwt"; - wildcard = "GWT files (*.gwt)|*.gwt"; - } else { - defaultFile += ".gal"; - wildcard = "GAL files (*.gal)|*.gal"; - } - - wxFileDialog dlg(this, - _("Choose an output weights file name."), - project->GetWorkingDir().GetPath(), - defaultFile, - wildcard, - wxFD_SAVE | wxFD_OVERWRITE_PROMPT); - - wxString outputfile; - if (dlg.ShowModal() != wxID_OK) - return; - outputfile = dlg.GetPath(); - - wxLogMessage(_("CreateWeights()") + outputfile); - - wxString id = wxEmptyString; - if ( m_id_field->GetSelection() != wxNOT_FOUND ) { - id = m_id_field->GetString(m_id_field->GetSelection()); - } else { - return; // we must have key id variable - } - - if ((m_id_field->GetSelection() != wxNOT_FOUND) && !CheckID(id)) - return; - - int m_ooC = m_spincont->GetValue(); - int m_kNN = m_spinneigh->GetValue(); - int m_alpha = 1; - - bool done = false; - - wxString str_X = m_X->GetString(m_X->GetSelection()); - wxString str_Y = m_Y->GetString(m_Y->GetSelection()); - if (m_X->GetSelection() < 0) { - dist_values = WeightsMetaInfo::DV_unspecified; - } else if (m_X->GetSelection() == 0) { - dist_values = WeightsMetaInfo::DV_centroids; - } else if (m_X->GetSelection() == 1) { - dist_values = WeightsMetaInfo::DV_mean_centers; - } else { - dist_values = WeightsMetaInfo::DV_vars; - } - - bool m_check1 = m_include_lower->GetValue(); - - switch (m_radio) { - case THRESH: - { - GwtWeight* Wp = 0; - double t_val = m_threshold_val; - if (t_val <= 0) { - t_val = std::numeric_limits::min(); - } - wmi.SetToThres(id, dist_metric, dist_units, dist_units_str,dist_values, t_val, dist_var_1, dist_tm_1, dist_var_2, dist_tm_2); - - if (m_is_arc && m_arc_in_km) { - //t_val /= GenGeomAlgs::one_mi_in_km; // convert km to mi - } - - if (t_val > 0) { - using namespace SpatialIndAlgs; - Wp = thresh_build(m_XCOO, m_YCOO, t_val * m_thres_delta_factor, m_is_arc, !m_arc_in_km); - if (!Wp || !Wp->gwt) { - wxString m = _("No weights file was created due to all observations being isolates for the specified threshold value. Increase the threshold to create a non-empty weights file."); - wxMessageDialog dlg(this, m, _("Error"), wxOK | wxICON_ERROR); - dlg.ShowModal(); - return; - } - - WriteWeightFile(0, Wp->gwt, project->GetProjectTitle(), outputfile, id, wmi); - if (Wp) delete Wp; - done = true; - } - } - break; - - case KNN: // k nn - { - wmi.SetToKnn(id, dist_metric, dist_units, dist_units_str, dist_values, m_kNN, dist_var_1, dist_tm_1, dist_var_2, dist_tm_2); - - if (m_kNN > 0 && m_kNN < m_num_obs) { - GwtWeight* Wp = 0; - Wp = SpatialIndAlgs::knn_build(m_XCOO, m_YCOO, m_kNN, dist_metric == WeightsMetaInfo::DM_arc, dist_units == WeightsMetaInfo::DU_mile); - - if (!Wp->gwt) - return; - Wp->id_field = id; - - WriteWeightFile(0, Wp->gwt, project->GetProjectTitle(), outputfile, id, wmi); - if (Wp) delete Wp; - done = true; - - } else { - wxString s = wxString::Format(_("Error: Maximum number of neighbors %d exceeded."), m_num_obs-1); - wxMessageBox(s); - } - } - break; - - case ROOK: - case QUEEN: - { - GalElement *gal = 0; - bool is_rook = (m_radio == ROOK); - if (is_rook) { - wmi.SetToRook(id, m_ooC, m_check1); - } else { - wmi.SetToQueen(id, m_ooC, m_check1); - } - if (project->main_data.header.shape_type == Shapefile::POINT_TYP) { - if (project->IsPointDuplicates()) { - project->DisplayPointDupsWarning(); - } - - std::vector > nbr_map; - if (is_rook) { - project->GetVoronoiRookNeighborMap(nbr_map); - } else { - project->GetVoronoiQueenNeighborMap(nbr_map); - } - gal = Gda::VoronoiUtils::NeighborMapToGal(nbr_map); - if (!gal) { - wxString msg = _("There was a problem generating voronoi contiguity neighbors. Please report this."); - wxMessageDialog dlg(NULL, msg, _("Voronoi Contiguity Error"), wxOK | wxICON_ERROR); - dlg.ShowModal(); - break; - } - } else { - double precision_threshold = 0.0; - if ( m_cbx_precision_threshold->IsChecked()) { - if (!m_txt_precision_threshold->IsEmpty()) { - wxString prec_thres = - m_txt_precision_threshold->GetValue(); - double value; - if ( prec_thres.ToDouble(&value) ) { - precision_threshold = value; - } - } else { - precision_threshold = 0.0; - } - } - gal = PolysToContigWeights(project->main_data, !is_rook, precision_threshold); - } - - bool empty_w = true; - bool has_island = false; - - for (size_t i=0; i0) { - empty_w = false; - } else { - has_island = true; - } - } - - if (empty_w) { - // could be an empty weights file, and should prompt user - // to setup Precision Threshold - wxString msg = _("None of your observations have neighbors. This could be related to digitizing problems, which can be fixed by adjusting the precision threshold."); - wxMessageDialog dlg(NULL, msg, "Empty Contiguity Weights", wxOK | wxICON_WARNING); - dlg.ShowModal(); - - m_cbx_precision_threshold->SetValue(true); - m_txt_precision_threshold->Enable(true); - // give a suggested value - double shp_min_x = (double)project->main_data.header.bbox_x_min; - double shp_max_x = (double)project->main_data.header.bbox_x_max; - double shp_min_y = (double)project->main_data.header.bbox_y_min; - double shp_max_y = (double)project->main_data.header.bbox_y_max; - double shp_x_len = shp_max_x - shp_min_x; - double shp_y_len = shp_max_y - shp_min_y; - double pixel_len = MIN(shp_x_len, shp_y_len) / 4096.0; // 4K LCD - double suggest_precision = pixel_len * 10E-7; - // round it to power of 10 - suggest_precision = log10(suggest_precision); - suggest_precision = ceil(suggest_precision); - suggest_precision = pow(10, suggest_precision); - wxString tmpTxt; - tmpTxt << suggest_precision; - m_txt_precision_threshold->SetValue(tmpTxt); - break; - } - if (has_island) { - wxString msg = _("There is at least one neighborless observation. Check the weights histogram and linked map to see if the islands are real or not. If not, adjust the distance threshold (points) or the precision threshold (polygons)."); - wxMessageDialog dlg(NULL, msg, "Neighborless Observation", wxOK | wxICON_WARNING); - dlg.ShowModal(); - } - if (m_ooC > 1) { - Gda::MakeHigherOrdContiguity(m_ooC, m_num_obs, gal, m_check1); - WriteWeightFile(gal, 0, project->GetProjectTitle(), outputfile, id, wmi); - } else { - WriteWeightFile(gal, 0, project->GetProjectTitle(), outputfile, id, wmi); - } - if (gal) delete [] gal; gal = 0; - done = true; - } - break; - - default: - break; - }; + wxLogMessage("Click CreatingWeightDlg::OnInverseKNNCheck"); + m_power_knn->Enable( m_use_inverse_knn->IsChecked() ); } void CreatingWeightDlg::OnPrecisionThresholdCheck( wxCommandEvent& event ) @@ -469,27 +257,7 @@ void CreatingWeightDlg::OnPrecisionThresholdCheck( wxCommandEvent& event ) dlg.ShowModal(); m_cbx_precision_threshold_first_click = false; } - if ( m_cbx_precision_threshold->IsChecked() ) { - m_txt_precision_threshold->Enable(true); - m_cbx_precision_threshold->SetValue(true); - } else { - m_txt_precision_threshold->Enable(false); - m_cbx_precision_threshold->SetValue(false); - } -} - -void CreatingWeightDlg::OnCRadioRookSelected( wxCommandEvent& event ) -{ - wxLogMessage("Click CreatingWeightDlg::OnCRadioRookSelected"); - SetRadioBtnAndAssocWidgets(ROOK); - SetRadioButtons(ROOK); -} - -void CreatingWeightDlg::OnCRadioQueenSelected( wxCommandEvent& event ) -{ - wxLogMessage("Click CreatingWeightDlg::OnCRadioQueenSelected"); - SetRadioBtnAndAssocWidgets(QUEEN); - SetRadioButtons(QUEEN); + m_txt_precision_threshold->Enable(m_cbx_precision_threshold->IsChecked()); } void CreatingWeightDlg::update(FramesManager* o) @@ -498,14 +266,15 @@ void CreatingWeightDlg::update(FramesManager* o) void CreatingWeightDlg::update(TableState* o) { - if (suspend_table_state_updates) return; + if (suspend_table_state_updates) + return; if (o->GetEventType() == TableState::cols_delta || - o->GetEventType() == TableState::col_rename || - o->GetEventType() == TableState::col_data_change || - o->GetEventType() == TableState::col_order_change || - o->GetEventType() == TableState::time_ids_add_remove || - o->GetEventType() == TableState::time_ids_rename || - o->GetEventType() == TableState::time_ids_swap) + o->GetEventType() == TableState::col_rename || + o->GetEventType() == TableState::col_data_change || + o->GetEventType() == TableState::col_order_change || + o->GetEventType() == TableState::time_ids_add_remove || + o->GetEventType() == TableState::time_ids_rename || + o->GetEventType() == TableState::time_ids_swap) { InitDlg(); } @@ -517,25 +286,6 @@ void CreatingWeightDlg::update(WeightsManState* o) Refresh(); } -void CreatingWeightDlg::EnableThresholdControls( bool b ) -{ - // This either enable the Threshold distance controls. This does not - // affect the state of the Theshold button itself. - FindWindow(XRCID("IDC_STATIC1"))->Enable(b); - FindWindow(XRCID("IDC_STATIC2"))->Enable(b); - FindWindow(XRCID("IDC_STATIC3"))->Enable(b); - m_X->Enable(b); - m_Y->Enable(b); - m_dist_choice->Enable(b); - m_sliderdistance->Enable(b); - m_threshold->Enable(b); - UpdateTmSelEnableState(); - if (!b) { - m_X_time->Disable(); - m_Y_time->Disable(); - } -} - void CreatingWeightDlg::UpdateTmSelEnableState() { int m_x_sel = m_X->GetSelection(); @@ -556,75 +306,14 @@ void CreatingWeightDlg::UpdateTmSelEnableState() } } -void CreatingWeightDlg::SetRadioBtnAndAssocWidgets(RadioBtnId radio) -{ - // Updates the value of m_radio and disables - // wigets associated with deslectd radio buttons. - - // Disable everything to begin. - FindWindow(XRCID("IDC_STATIC_OOC1"))->Enable(false); - m_contiguity->Enable(false); - m_spincont->Enable(false); - m_cbx_precision_threshold->Enable(false); - m_include_lower->Enable(false); - EnableThresholdControls(false); - FindWindow(XRCID("IDC_STATIC_KNN"))->Enable(false); - m_neighbors->Enable(false); - m_spinneigh->Enable(false); - - if ((radio == QUEEN) || (radio == ROOK) || - (radio == THRESH) || (radio == KNN)) { - m_radio = radio; - } else { - m_radio = NO_RADIO; - } - UpdateCreateButtonState(); - - switch (m_radio) { - case QUEEN: - case ROOK: { - FindWindow(XRCID("IDC_STATIC_OOC1"))->Enable(true); - m_contiguity->Enable(true); - m_spincont->Enable(true); - m_cbx_precision_threshold->Enable(true); - m_include_lower->Enable(true); - } - break; - case THRESH: { - EnableThresholdControls(true); - } - break; - case KNN: { - FindWindow(XRCID("IDC_STATIC1"))->Enable(true); - FindWindow(XRCID("IDC_STATIC2"))->Enable(true); - FindWindow(XRCID("IDC_STATIC3"))->Enable(true); - m_X->Enable(true); - m_Y->Enable(true); - //SetDistChoiceEuclid(true); - m_dist_choice->Enable(true); - m_sliderdistance->Enable(false); - FindWindow(XRCID("IDC_STATIC_KNN"))->Enable(true); - m_neighbors->Enable(true); - m_spinneigh->Enable(true); - UpdateTmSelEnableState(); - } - break; - default: - break; - } -} - // This function is only called when one of the choices that affects // the entire threshold scale is changed. This function will use // the current position of the slider void CreatingWeightDlg::UpdateThresholdValues() { - if (!all_init) return; - int sl_x, sl_y; - m_sliderdistance->GetPosition(&sl_x, &sl_y); - wxSize sl_size = m_sliderdistance->GetSize(); - m_sliderdistance->SetSize(sl_x, sl_y, 500, sl_size.GetHeight()); - + if (!all_init) + return; + if (m_X->GetSelection() == wxNOT_FOUND || m_Y->GetSelection() == wxNOT_FOUND) { return; @@ -652,7 +341,8 @@ void CreatingWeightDlg::UpdateThresholdValues() } dist_var_1 = v1; dist_var_2 = v2; - + + if (!user_xy) { if (v1 == wxEmptyString || v2 == wxEmptyString) { if (mean_center) { project->GetMeanCenters(m_XCOO, m_YCOO); @@ -687,6 +377,7 @@ void CreatingWeightDlg::UpdateThresholdValues() table_int->GetColData(col_id, tm, m_YCOO); } } + } m_thres_min = SpatialIndAlgs::find_max_1nn_dist(m_XCOO, m_YCOO, m_is_arc, @@ -704,10 +395,13 @@ void CreatingWeightDlg::UpdateThresholdValues() } } - m_threshold_val = (m_sliderdistance->GetValue() * - (m_thres_max-m_thres_min)/100.0) + m_thres_min; + m_threshold_val = (m_sliderdistance->GetValue() * (m_thres_max-m_thres_min)/100.0) + m_thres_min; m_thres_val_valid = true; - m_threshold->ChangeValue( wxString::Format("%f", m_threshold_val)); + m_threshold->ChangeValue( wxString::Format("%f", m_threshold_val)); + + m_bandwidth_thres_val = (m_bandwidth_slider->GetValue() * (m_thres_max-m_thres_min)/100.0) + m_thres_min; + m_bandwidth_thres_val_valid = true; + m_manu_bandwidth->ChangeValue( wxString::Format("%f", m_bandwidth_thres_val) ); } void CreatingWeightDlg::OnCThresholdTextEdit( wxCommandEvent& event ) @@ -736,6 +430,32 @@ void CreatingWeightDlg::OnCThresholdTextEdit( wxCommandEvent& event ) } } +void CreatingWeightDlg::OnCBandwidthThresholdTextEdit( wxCommandEvent& event ) +{ + wxLogMessage("Click CreatingWeightDlg::OnCBandwidthThresholdTextEdit:"); + + if (!all_init) return; + wxString val = m_manu_bandwidth->GetValue(); + val.Trim(false); + val.Trim(true); + + wxLogMessage(val); + + double t = m_bandwidth_thres_val; + m_bandwidth_thres_val_valid = val.ToDouble(&t); + if (m_bandwidth_thres_val_valid) { + m_bandwidth_thres_val = t; + if (t <= m_thres_min) { + m_bandwidth_slider->SetValue(0); + } else if (t >= m_thres_max) { + m_bandwidth_slider->SetValue(100); + } else { + double s = (t-m_thres_min)/(m_thres_max-m_thres_min) * 100; + m_bandwidth_slider->SetValue((int) s); + } + } +} + void CreatingWeightDlg::OnCThresholdSliderUpdated( wxCommandEvent& event ) { wxLogMessage("Click CreatingWeightDlg::OnCThresholdSliderUpdated:"); @@ -754,23 +474,39 @@ void CreatingWeightDlg::OnCThresholdSliderUpdated( wxCommandEvent& event ) wxLogMessage(str_val); } -void CreatingWeightDlg::OnCRadioDistanceSelected( wxCommandEvent& event ) +void CreatingWeightDlg::OnCBandwidthThresholdSliderUpdated( wxCommandEvent& event ) { - wxLogMessage("Click CreatingWeightDlg::OnCRadioDistanceSelected"); + wxLogMessage("Click CreatingWeightDlg::OnCBandwidthThresholdSliderUpdated:"); - // Threshold Distance radio button selected - SetRadioBtnAndAssocWidgets(THRESH); - SetRadioButtons(THRESH); - UpdateThresholdValues(); + if (!all_init) return; + + m_bandwidth_thres_val = (m_bandwidth_slider->GetValue() * (m_thres_max-m_thres_min)/100.0) + m_thres_min; + m_manu_bandwidth->ChangeValue( wxString::Format("%f", (double) m_bandwidth_thres_val)); + if (m_bandwidth_thres_val > 0) { + m_btn_ok->Enable(true); + } + + wxString str_val; + str_val << m_bandwidth_thres_val; + wxLogMessage(str_val); } -void CreatingWeightDlg::OnCRadioKnnSelected( wxCommandEvent& event ) +void CreatingWeightDlg::OnCSpinPowerInverseDistUpdated( wxSpinEvent& event ) { - wxLogMessage("Click CreatingWeightDlg::OnCRadioKnnSelected"); + wxLogMessage("Click CreatingWeightDlg::OnCSpinPowerInverseDistUpdated"); - SetRadioBtnAndAssocWidgets(KNN); - SetRadioButtons(KNN); - UpdateThresholdValues(); + wxString val; + val << m_spinn_inverse->GetValue(); + m_power->SetValue(val); +} + +void CreatingWeightDlg::OnCSpinPowerInverseKNNUpdated( wxSpinEvent& event ) +{ + wxLogMessage("Click CreatingWeightDlg::OnCSpinPowerInverseKNNUpdated"); + + wxString val; + val << m_spinn_inverse_knn->GetValue(); + m_power_knn->SetValue(val); } void CreatingWeightDlg::OnCSpinOrderofcontiguityUpdated( wxSpinEvent& event ) @@ -791,6 +527,15 @@ void CreatingWeightDlg::OnCSpinKnnUpdated( wxSpinEvent& event ) m_neighbors->SetValue(val); } +void CreatingWeightDlg::OnCSpinKernelKnnUpdated( wxSpinEvent& event ) +{ + wxLogMessage("Click CreatingWeightDlg::OnCSpinKernelKnnUpdated"); + + wxString val; + val << m_spinn_kernel->GetValue(); + m_kernel_neighbors->SetValue(val); +} + // updates the enable/disable state of the Create button based // on the values of various other controls. void CreatingWeightDlg::UpdateCreateButtonState() @@ -800,36 +545,11 @@ void CreatingWeightDlg::UpdateCreateButtonState() // Check that a Weights File ID variable is selected. if (m_id_field->GetSelection() == wxNOT_FOUND) enable = false; // Check that a weight type radio button choice is selected. - if (m_radio == NO_RADIO) enable = false; if (m_X->GetSelection() == wxNOT_FOUND || - m_Y->GetSelection() == wxNOT_FOUND) enable = false; + m_Y->GetSelection() == wxNOT_FOUND) enable = false; - FindWindow(XRCID("wxID_OK"))->Enable(enable); -} - -void CreatingWeightDlg::EnableContiguityRadioButtons(bool b) -{ - FindWindow(XRCID("IDC_RADIO_ROOK"))->Enable(b); - FindWindow(XRCID("IDC_RADIO_QUEEN"))->Enable(b); -} - -void CreatingWeightDlg::EnableDistanceRadioButtons(bool b) -{ - FindWindow(XRCID("IDC_RADIO_DISTANCE"))->Enable(b); - FindWindow(XRCID("IDC_RADIO_KNN"))->Enable(b); -} - -void CreatingWeightDlg::SetRadioButtons(CreatingWeightDlg::RadioBtnId id) -{ - m_radio_queen->SetValue(id == CreatingWeightDlg::QUEEN); - m_radio_rook->SetValue(id == CreatingWeightDlg::ROOK); - m_radio_thresh->SetValue(id == CreatingWeightDlg::THRESH); - m_radio_knn->SetValue(id == CreatingWeightDlg::KNN); - if (id != QUEEN && id != ROOK && id != THRESH && id != KNN) { - m_radio = NO_RADIO; - } else { - m_radio = id; - } + m_btn_ok->Enable(enable); + m_nb_weights_type->Enable(enable); } void CreatingWeightDlg::ResetThresXandYCombo() @@ -917,13 +637,37 @@ bool CreatingWeightDlg::CheckID(const wxString& id) } } + std::set dup_ids; std::set id_set; + std::map > dup_dict; // value:[] + for (int i=0, iend=str_id_vec.size(); i ids; + dup_dict[str_id] = ids; + } + dup_dict[str_id].push_back(i); } - if (str_id_vec.size() != id_set.size()) { - wxString msg = id + _(" has duplicate values. Please choose a different ID Variable."); - wxMessageBox(msg); + if (id_set.size() != m_num_obs) { + wxString msg = id + _(" has duplicate values. Please choose a different ID Variable.\n\nDetails:"); + wxString details = "value, row\n"; + + std::map >::iterator it; + for (it=dup_dict.begin(); it!=dup_dict.end(); it++) { + wxString val = it->first; + std::vector& ids = it->second; + if (ids.size() > 1) { + for (int i=0; iShow(true); + return false; } return true; @@ -955,37 +699,43 @@ void CreatingWeightDlg::InitDlg() m_spinneigh->SetRange(1,10); m_spinneigh->SetValue(4); m_neighbors->SetValue( "4"); - FindWindow(XRCID("wxID_OK"))->Enable(false); - FindWindow(XRCID("ID_ID_VAR_STAT_TXT"))->Enable(false); - m_id_field->Enable(false); - FindWindow(XRCID("ID_CREATE_ID"))->Enable(false); + + m_power->SetValue("1"); + m_spinn_inverse->SetValue(1); + m_power_knn->SetValue("1"); + m_spinn_inverse_knn->SetValue(1); + + m_spinn_kernel->SetRange(1,20); + int n_kernel_nbrs = ceil(pow(project->GetNumRecords(), 1.0/3.0)); + m_spinn_kernel->SetValue(n_kernel_nbrs); + m_kernel_neighbors->SetValue(wxString::Format("%d", n_kernel_nbrs)); + m_kernel_methods->Clear(); + m_kernel_methods->Append("Uniform"); + m_kernel_methods->Append("Triangular"); + m_kernel_methods->Append("Epanechnikov"); + m_kernel_methods->Append("Quartic"); + m_kernel_methods->Append("Gaussian"); + m_kernel_methods->SetSelection(0); + m_dist_choice->Clear(); m_dist_choice->Append("Euclidean Distance"); m_dist_choice->Append("Arc Distance (mi)"); m_dist_choice->Append("Arc Distance (km)"); m_dist_choice->SetSelection(0); - SetRadioButtons(NO_RADIO); - SetRadioBtnAndAssocWidgets(NO_RADIO); - EnableContiguityRadioButtons(false); - EnableDistanceRadioButtons(false); - + + m_radio_queen->SetValue(true); + // Previously from OpenShapefile: FindWindow(XRCID("ID_ID_VAR_STAT_TXT"))->Enable(true); m_id_field->Enable(true); FindWindow(XRCID("ID_CREATE_ID"))->Enable(true); - FindWindow(XRCID("wxID_OK"))->Enable(false); - m_cbx_precision_threshold->Enable(false); - m_txt_precision_threshold->Enable(false); - + m_btn_ok->Enable(false); + col_id_map.clear(); table_int->FillColIdMap(col_id_map); InitFields(); - int sl_x, sl_y; - m_sliderdistance->GetPosition(&sl_x, &sl_y); - wxSize sl_size = m_sliderdistance->GetSize(); - m_sliderdistance->SetSize(sl_x, sl_y, 500, sl_size.GetHeight()); - + m_X_time->Show(table_int->IsTimeVariant()); m_Y_time->Show(table_int->IsTimeVariant()); m_spincont->SetRange(1, (int) m_num_obs / 2); @@ -993,18 +743,27 @@ void CreatingWeightDlg::InitDlg() m_XCOO.resize(m_num_obs); m_YCOO.resize(m_num_obs); + + m_nb_weights_type->Enable(false); + + if (user_xy) { + m_X_time->Hide(); + m_Y_time->Hide(); + m_dist_choice->Hide(); + m_X->Hide(); + m_Y->Hide(); + FindWindow(XRCID("IDC_STATIC_DIST_METRIC"))->Hide(); + FindWindow(XRCID("IDC_STATIC_XCOORD_VAR"))->Hide(); + FindWindow(XRCID("IDC_STATIC_YCOORD_VAR"))->Hide(); + } + Refresh(); } bool CreatingWeightDlg::IsSaveAsGwt() { // determine if save type will be GWT or GAL. - // m_radio values: - // THRESH - GWT - // KNN - GWT - // ROOK - GAL - // QUEEN - GAL - return !(m_radio == ROOK || m_radio == QUEEN); + return m_nb_weights_type->GetSelection() == 1; } void CreatingWeightDlg::OnXSelected(wxCommandEvent& event ) @@ -1071,17 +830,17 @@ void CreatingWeightDlg::OnDistanceChoiceSelected(wxCommandEvent& event ) { wxLogMessage("Click CreatingWeightDlg::OnDistanceChoiceSelected"); - wxString s = m_dist_choice->GetStringSelection(); - if (s == "Euclidean Distance") { - SetDistChoiceEuclid(false); - UpdateThresholdValues(); - } else if (s == "Arc Distance (mi)") { - SetDistChoiceArcMiles(false); - UpdateThresholdValues(); - } else if (s == "Arc Distance (km)") { - SetDistChoiceArcKms(false); - UpdateThresholdValues(); - } + wxString s = m_dist_choice->GetStringSelection(); + if (s == "Euclidean Distance") { + SetDistChoiceEuclid(false); + UpdateThresholdValues(); + } else if (s == "Arc Distance (mi)") { + SetDistChoiceArcMiles(false); + UpdateThresholdValues(); + } else if (s == "Arc Distance (km)") { + SetDistChoiceArcKms(false); + UpdateThresholdValues(); + } } void CreatingWeightDlg::SetDistChoiceEuclid(bool update_sel) @@ -1119,25 +878,22 @@ void CreatingWeightDlg::SetDistChoiceArcKms(bool update_sel) dist_units = WeightsMetaInfo::DU_km; } - void CreatingWeightDlg::OnIdVariableSelected( wxCommandEvent& event ) { wxLogMessage("Click CreatingWeightDlg::OnIdVariableSelected"); + // we must have key id variable + bool isValid = m_id_field->GetSelection() != wxNOT_FOUND; + if (!isValid) + return; - wxString id = wxEmptyString; - if ( m_id_field->GetSelection() != wxNOT_FOUND ) { - id = m_id_field->GetString(m_id_field->GetSelection()); - } else { - return; // we must have key id variable - } - - if ((m_id_field->GetSelection() != wxNOT_FOUND) && !CheckID(id)) { + wxString id = m_id_field->GetString(m_id_field->GetSelection()); + if (!CheckID(id)) { m_id_field->SetSelection(-1); return; } - - EnableDistanceRadioButtons(m_id_field->GetSelection() != wxNOT_FOUND); - EnableContiguityRadioButtons((m_id_field->GetSelection() != wxNOT_FOUND) && !project->IsTableOnlyProject()); + + UpdateTmSelEnableState(); + UpdateThresholdValues(); UpdateCreateButtonState(); wxString msg; @@ -1145,29 +901,393 @@ void CreatingWeightDlg::OnIdVariableSelected( wxCommandEvent& event ) wxLogMessage(msg); } +double CreatingWeightDlg::GetBandwidth() +{ + double bandwidth = 0.0; + if (m_radio_manu_bandwdith->GetValue()==true) { + wxString val = m_manu_bandwidth->GetValue(); + val.ToDouble(&bandwidth); + } + return bandwidth; +} + +bool CreatingWeightDlg::CheckThresholdInput() +{ + if (m_nb_weights_type->GetSelection() == 0) { + // no need to check + return true; + } + + if (m_nb_distance_methods->GetSelection() == 1) { + // case of KNN no need to check + return true; + } + + wxString not_valid_msg = _("The currently entered threshold value is not a valid number. Please move the slider, or enter a valid number."); + + wxString nbrless_msg = _("The currently entered threshold value of %f is less than %f which is the minimum value for which there will be no neighborless observations (isolates). \n\nPress Yes to proceed anyhow, press No to abort."); + + bool is_dist_band = m_nb_distance_methods->GetSelection() == 0 ? true : false; + + if ((is_dist_band && !m_thres_val_valid) || + (!is_dist_band && !m_bandwidth_thres_val_valid)) + { + wxMessageDialog dlg(this, not_valid_msg, _("Error"), wxOK | wxICON_ERROR); + dlg.ShowModal(); + return false; + } + + if (( is_dist_band && m_threshold_val*m_thres_delta_factor < m_thres_min) || + ( !is_dist_band && m_bandwidth_thres_val*m_thres_delta_factor < m_thres_min) ) + { + wxString msg; + if (is_dist_band) + msg = wxString::Format(nbrless_msg, m_threshold_val, m_thres_min); + else + msg = wxString::Format(nbrless_msg, m_bandwidth_thres_val, m_thres_min); + + wxMessageDialog dlg(this, msg, _("Warning"), wxYES_NO | wxNO_DEFAULT | wxICON_QUESTION ); + if (dlg.ShowModal() != wxID_YES) + return false; + } + return true; +} + +void CreatingWeightDlg::SetXCOO(const std::vector& xx) +{ + m_XCOO = xx; +} + +void CreatingWeightDlg::SetYCOO(const std::vector& yy) +{ + m_YCOO = yy; +} + +void CreatingWeightDlg::OnCreateClick( wxCommandEvent& event ) +{ + wxLogMessage("Click CreatingWeightDlg::OnCreateClick"); + try { + CreateWeights(); + } catch(GdaException e) { + wxString msg; + msg << e.what(); + wxMessageDialog dlg(this, msg , _("Error"), wxOK | wxICON_ERROR); + dlg.ShowModal(); + } +} +void CreatingWeightDlg::CreateWeights() +{ + WeightsMetaInfo wmi; + + if ( m_id_field->GetSelection() == wxNOT_FOUND ) { + return; // we must have key id variable + } + + if (!m_nb_weights_type->IsEnabled()) { + wxString msg = _("Please select a weights type."); + wxMessageDialog dlg(this, msg, _("Error"), wxOK | wxICON_ERROR); + dlg.ShowModal(); + return; + } + + if (!CheckThresholdInput()) + return; + + wxString id = m_id_field->GetString(m_id_field->GetSelection()); + if (!CheckID(id)) + return; + + wxString wildcard; + wxString defaultFile(project->GetProjectTitle()); + + if (m_nb_weights_type->GetSelection()== 0) { + defaultFile += ".gal"; + wildcard = _("GAL files (*.gal)|*.gal"); + } else { + if (m_nb_distance_methods->GetSelection() == 2) { + defaultFile += ".kwt"; + wildcard = _("KWT files (*.kwt)|*.kwt"); + } else { + defaultFile += ".gwt"; + wildcard = _("GWT files (*.gwt)|*.gwt"); + } + } + + wxFileDialog dlg(this, + _("Choose an output weights file name."), + project->GetWorkingDir().GetPath(), + defaultFile, + wildcard, + wxFD_SAVE | wxFD_OVERWRITE_PROMPT); + + wxString outputfile; + if (dlg.ShowModal() != wxID_OK) + return; + outputfile = dlg.GetPath(); + + wxLogMessage("CreateWeights()"); + wxLogMessage(outputfile); + + int m_ooC = m_spincont->GetValue(); + int m_kNN = m_spinneigh->GetValue(); + int m_kernel_kNN = m_spinn_kernel->GetValue(); + int m_alpha = 1; + + bool done = false; + + wxString str_X = m_X->GetString(m_X->GetSelection()); + wxString str_Y = m_Y->GetString(m_Y->GetSelection()); + if (m_X->GetSelection() < 0) { + dist_values = WeightsMetaInfo::DV_unspecified; + } else if (m_X->GetSelection() == 0) { + dist_values = WeightsMetaInfo::DV_centroids; + if (project->IsPointTypeData()) + dist_values = WeightsMetaInfo::DV_coordinates; + } else if (m_X->GetSelection() == 1) { + dist_values = WeightsMetaInfo::DV_mean_centers; + if (project->IsPointTypeData()) + dist_values = WeightsMetaInfo::DV_coordinates; + } else { + dist_values = WeightsMetaInfo::DV_vars; + } + + bool m_check1 = m_include_lower->GetValue(); + + if (m_nb_weights_type->GetSelection()== 0) { + // queen/rook + GalWeight* Wp = new GalWeight; + Wp->num_obs = project->GetNumRecords(); + Wp->is_symmetric = true; + Wp->symmetry_checked = true; + + bool is_rook = m_radio_queen->GetValue() ? false : true; + if (is_rook) { + wmi.SetToRook(id, m_ooC, m_check1); + } else { + wmi.SetToQueen(id, m_ooC, m_check1); + } + if (user_xy) { + std::vector > nbr_map; + Gda::VoronoiUtils::PointsToContiguity(m_XCOO, m_YCOO, false, nbr_map); + Wp->gal = Gda::VoronoiUtils::NeighborMapToGal(nbr_map); + if (!Wp->gal) { + wxString msg = _("There was a problem generating voronoi contiguity neighbors. Please report this."); + wxMessageDialog dlg(NULL, msg, _("Voronoi Contiguity Error"), wxOK | wxICON_ERROR); + dlg.ShowModal(); + } + + } else if (project->main_data.header.shape_type == Shapefile::POINT_TYP) { + if (project->IsPointDuplicates()) { + project->DisplayPointDupsWarning(); + } + + std::vector > nbr_map; + if (is_rook) { + project->GetVoronoiRookNeighborMap(nbr_map); + } else { + project->GetVoronoiQueenNeighborMap(nbr_map); + } + Wp->gal = Gda::VoronoiUtils::NeighborMapToGal(nbr_map); + if (!Wp->gal) { + wxString msg = _("There was a problem generating voronoi contiguity neighbors. Please report this."); + wxMessageDialog dlg(NULL, msg, _("Voronoi Contiguity Error"), wxOK | wxICON_ERROR); + dlg.ShowModal(); + } + } else { + double precision_threshold = 0.0; + if ( m_cbx_precision_threshold->IsChecked()) { + if (!m_txt_precision_threshold->IsEmpty()) { + wxString prec_thres = m_txt_precision_threshold->GetValue(); + double value; + if ( prec_thres.ToDouble(&value) ) { + precision_threshold = value; + } + } else { + precision_threshold = 0.0; + } + } + Wp->gal = PolysToContigWeights(project->main_data, !is_rook, + precision_threshold); + } + + bool empty_w = true; + bool has_island = false; + + for (size_t i=0; igal[i].Size() >0) { + empty_w = false; + } else { + has_island = true; + } + } + + if (empty_w && !user_xy) { + // could be an empty weights file, and should prompt user + // to setup Precision Threshold + wxString msg = _("None of your observations have neighbors. This could be related to digitizing problems, which can be fixed by adjusting the precision threshold."); + wxMessageDialog dlg(NULL, msg, "Empty Contiguity Weights", wxOK | wxICON_WARNING); + dlg.ShowModal(); + + m_cbx_precision_threshold->SetValue(true); + m_txt_precision_threshold->Enable(true); + // give a suggested value + double shp_min_x = (double)project->main_data.header.bbox_x_min; + double shp_max_x = (double)project->main_data.header.bbox_x_max; + double shp_min_y = (double)project->main_data.header.bbox_y_min; + double shp_max_y = (double)project->main_data.header.bbox_y_max; + double shp_x_len = shp_max_x - shp_min_x; + double shp_y_len = shp_max_y - shp_min_y; + double pixel_len = MIN(shp_x_len, shp_y_len) / 4096.0; // 4K LCD + double suggest_precision = pixel_len * 10E-7; + // round it to power of 10 + suggest_precision = log10(suggest_precision); + suggest_precision = ceil(suggest_precision); + suggest_precision = pow(10, suggest_precision); + wxString tmpTxt; + tmpTxt << suggest_precision; + m_txt_precision_threshold->SetValue(tmpTxt); + return; + } + if (has_island) { + wxString msg = _("There is at least one neighborless observation. Check the weights histogram and linked map to see if the islands are real or not. If not, adjust the distance threshold (points) or the precision threshold (polygons)."); + wxMessageDialog dlg(NULL, msg, "Neighborless Observation", wxOK | wxICON_WARNING); + dlg.ShowModal(); + } + + if (m_ooC > 1) { + Gda::MakeHigherOrdContiguity(m_ooC, m_num_obs, Wp->gal, m_check1); + WriteWeightFile(Wp, 0, project->GetProjectTitle(), outputfile, id, wmi); + } else { + WriteWeightFile(Wp, 0, project->GetProjectTitle(), outputfile, id, wmi); + } + if (Wp) delete Wp; + done = true; + + } else if (m_nb_distance_methods->GetSelection() == 0) { + // distance band + GwtWeight* Wp = 0; + double t_val = m_threshold_val; + double power = 1.0; + if (m_use_inverse->IsChecked()) { + // if use inverse distance + wxString inverse_val = m_power->GetValue(); + if (inverse_val.ToDouble(&power)) { + power = -power; + } + } + if (t_val <= 0) { + t_val = std::numeric_limits::min(); + } + if (user_xy) dist_units_str = wxEmptyString; + wmi.SetToThres(id, dist_metric, dist_units, dist_units_str,dist_values, t_val, power, dist_var_1, dist_tm_1, dist_var_2, dist_tm_2); + + if (m_is_arc && m_arc_in_km) { + //t_val /= GenGeomAlgs::one_mi_in_km; // convert km to mi + } + + if (t_val > 0) { + using namespace SpatialIndAlgs; + Wp = thresh_build(m_XCOO, m_YCOO, t_val * m_thres_delta_factor, power, m_is_arc, !m_arc_in_km); + if (!Wp || !Wp->gwt) { + wxString m = _("No weights file was created due to all observations being isolates for the specified threshold value. Increase the threshold to create a non-empty weights file."); + wxMessageDialog dlg(this, m, _("Error"), wxOK | wxICON_ERROR); + dlg.ShowModal(); + return; + } + WriteWeightFile(0, Wp, project->GetProjectTitle(), outputfile, id, wmi); + if (Wp) delete Wp; + done = true; + } + + } else if (m_nb_distance_methods->GetSelection() == 1) { + // knn + double power = 1.0; + bool is_inverse = m_use_inverse_knn->IsChecked(); + if ( is_inverse) { + // if use inverse distance + wxString inverse_val = m_power_knn->GetValue(); + if (inverse_val.ToDouble(&power)) { + power = -power; + } + } + + wmi.SetToKnn(id, dist_metric, dist_units, dist_units_str, dist_values, m_kNN, power, dist_var_1, dist_tm_1, dist_var_2, dist_tm_2); + + if (m_kNN > 0 && m_kNN < m_num_obs) { + GwtWeight* Wp = 0; + bool is_arc = dist_metric == WeightsMetaInfo::DM_arc; + bool is_mile = dist_units == WeightsMetaInfo::DU_mile; + // knn + Wp = SpatialIndAlgs::knn_build(m_XCOO, m_YCOO, m_kNN, is_arc, is_mile, is_inverse, power); + + if (!Wp->gwt) return; + Wp->id_field = id; + WriteWeightFile(0, Wp, project->GetProjectTitle(), outputfile, id, wmi); + if (Wp) delete Wp; + done = true; + } else { + wxString s = wxString::Format(_("Error: Maximum number of neighbors %d exceeded."), m_num_obs-1); + wxMessageBox(s); + } + + } else { + // kernel + bool is_arc = dist_metric == WeightsMetaInfo::DM_arc; + bool is_mile = dist_units == WeightsMetaInfo::DU_mile; + // kernel + wxString kernel = m_kernel_methods->GetString(m_kernel_methods->GetSelection()); + double bandwidth = GetBandwidth(); + bool is_adaptive_kernel = m_radio_adaptive_bandwidth->GetValue(); + bool use_kernel_diagnals = m_kernel_diagnals->GetValue(); + + wmi.SetToKernel(id, dist_metric, dist_units, dist_units_str, dist_values, kernel, m_kernel_kNN, bandwidth, is_adaptive_kernel, use_kernel_diagnals, dist_var_1, dist_tm_1, dist_var_2, dist_tm_2); + + if (m_kernel_kNN > 0 && m_kernel_kNN < m_num_obs) { + GwtWeight* Wp = 0; + if (m_radio_manu_bandwdith->GetValue()==true) { + Wp = SpatialIndAlgs::thresh_build(m_XCOO, m_YCOO, bandwidth, 1.0, m_is_arc, !m_arc_in_km, kernel, use_kernel_diagnals); + } else { + Wp = SpatialIndAlgs::knn_build(m_XCOO, m_YCOO, m_kernel_kNN, is_arc, is_mile, false, 1.0, kernel, bandwidth, is_adaptive_kernel, use_kernel_diagnals); + } + if (!Wp->gwt) return; + Wp->id_field = id; + WriteWeightFile(0, Wp, project->GetProjectTitle(), outputfile, id, wmi); + if (Wp) delete Wp; + done = true; + } else { + wxString s = wxString::Format(_("Error: Maximum number of neighbors %d exceeded."), m_num_obs-1); + wxMessageBox(s); + } + } +} + + /** layer_name: layer name * ofn: output file name * idd: id column name * id: id column vector * WeightsMetaInfo contains all meta info. */ -bool CreatingWeightDlg::WriteWeightFile(GalElement *gal, GwtElement *gwt, +bool CreatingWeightDlg::WriteWeightFile(GalWeight* Wp_gal, GwtWeight* Wp_gwt, const wxString& layer_name, const wxString& ofn, const wxString& idd, - const WeightsMetaInfo& wmi) + WeightsMetaInfo& wmi) { - FindWindow(XRCID("wxID_OK"))->Enable(false); - - bool success = false; - bool flag = false; - //bool geodaL=true; // always save as "Legacy" format. + FindWindow(XRCID("wxID_OK"))->Enable(false); + bool success = false; + bool flag = false; + //bool geodaL=true; // always save as "Legacy" format. + GalElement *gal = NULL; + GwtElement *gwt = NULL; + GeoDaWeight *Wp = NULL; int col = table_int->FindColId(idd); - - if (gal) { // gal - + + if (Wp_gal) { // gal + gal = Wp_gal->gal; + Wp = (GeoDaWeight*)Wp_gal; if (table_int->GetColType(col) == GdaConst::long64_type){ std::vector id_vec(m_num_obs); table_int->GetColData(col, 0, id_vec); @@ -1179,82 +1299,89 @@ bool CreatingWeightDlg::WriteWeightFile(GalElement *gal, GwtElement *gwt, flag = Gda::SaveGal(gal, layer_name, ofn, idd, id_vec); } - } else if (m_radio == THRESH || m_radio == KNN) { // binary distance + } else { + gwt = Wp_gwt->gwt; + Wp = (GeoDaWeight*)Wp_gwt; if (table_int->GetColType(col) == GdaConst::long64_type){ std::vector id_vec(m_num_obs); table_int->GetColData(col, 0, id_vec); - flag = Gda::SaveGwt(gwt, layer_name, ofn, idd, id_vec); + flag = Gda::SaveGwt(gwt, layer_name, ofn, idd, id_vec); } else if (table_int->GetColType(col) == GdaConst::string_type) { std::vector id_vec(m_num_obs); table_int->GetColData(col, 0, id_vec); - flag = Gda::SaveGwt(gwt, layer_name, ofn, idd, id_vec); + flag = Gda::SaveGwt(gwt, layer_name, ofn, idd, id_vec); } - } else { - flag = false; - } + } - if (!flag) { - wxString msg = _("Failed to create the weights file."); - wxMessageDialog dlg(NULL, msg, _("Error"), wxOK | wxICON_ERROR); - dlg.ShowModal(); - } else { - wxFileName t_ofn(ofn); - wxString file_name(t_ofn.GetFullName()); - wxString msg = wxString::Format(_("Weights file \"%s\" created successfully."), file_name); - wxMessageDialog dlg(NULL, msg, _("Success"), wxOK | wxICON_INFORMATION); - dlg.ShowModal(); - success = true; - } - - if (success) { - wxFileName t_ofn(ofn); - wxString ext = t_ofn.GetExt().Lower(); - GalWeight* w = 0; - if (ext != "gal" && ext != "gwt") { - //LOG_MSG("File extention not gal or gwt"); - } else { - GalElement* tempGal = 0; - if (ext == "gal") { - tempGal=WeightUtils::ReadGal(ofn, table_int); - } else { // ext == "gwt" - tempGal=WeightUtils::ReadGwtAsGal(ofn, table_int); - } - if (tempGal != 0) { - w = new GalWeight(); - w->num_obs = table_int->GetNumberRows(); - w->wflnm = ofn; - w->gal = tempGal; + if (!flag) { + wxString msg = _("Failed to create the weights file."); + wxMessageDialog dlg(NULL, msg, _("Error"), wxOK | wxICON_ERROR); + dlg.ShowModal(); + } else { + wxFileName t_ofn(ofn); + wxString file_name(t_ofn.GetFullName()); + wxString msg = wxString::Format(_("Weights file \"%s\" created successfully."), file_name); + wxMessageDialog dlg(NULL, msg, _("Success"), wxOK | wxICON_INFORMATION); + dlg.ShowModal(); + success = true; + } + + Wp->GetNbrStats(); + wmi.num_obs = Wp->GetNumObs(); + wmi.SetMinNumNbrs(Wp->GetMinNumNbrs()); + wmi.SetMaxNumNbrs(Wp->GetMaxNumNbrs()); + wmi.SetMeanNumNbrs(Wp->GetMeanNumNbrs()); + wmi.SetMedianNumNbrs(Wp->GetMedianNumNbrs()); + wmi.SetSparsity(Wp->GetSparsity()); + wmi.SetDensity(Wp->GetDensity()); + + if (success) { + wxFileName t_ofn(ofn); + wxString ext = t_ofn.GetExt().Lower(); + GalWeight* w = 0; + if (ext != "gal" && ext != "gwt" && ext != "kwt") { + //LOG_MSG("File extention not gal or gwt"); + } else { + GalElement* tempGal = 0; + if (ext == "gal") { + tempGal=WeightUtils::ReadGal(ofn, table_int); + } else { // ext == "gwt" + tempGal=WeightUtils::ReadGwtAsGal(ofn, table_int); + } + if (tempGal != 0) { + w = new GalWeight(); + w->num_obs = table_int->GetNumberRows(); + w->wflnm = ofn; + w->gal = tempGal; w->id_field = idd; - - WeightsMetaInfo e(wmi); - e.filename = ofn; - boost::uuids::uuid uid = w_man_int->RequestWeights(e); - if (uid.is_nil()) + + WeightsMetaInfo e(wmi); + e.filename = ofn; + boost::uuids::uuid uid = w_man_int->RequestWeights(e); + if (uid.is_nil()) success = false; - if (success) { - // deep copy of w - GalWeight* dcw = new GalWeight(*w); - success = ((WeightsNewManager*) w_man_int)->AssociateGal(uid, dcw); + if (success) { + // deep copy of w + GalWeight* dcw = new GalWeight(*w); + success = ((WeightsNewManager*) w_man_int)->AssociateGal(uid, dcw); - if (success) { - w_man_int->MakeDefault(uid); - //wxCommandEvent event; - //GdaFrame::GetGdaFrame()->OnToolsWeightsManager(event); - } else { - delete dcw; - } - //GdaFrame::GetGdaFrame()->ShowConnectivityMapView(uid); - } + if (success) { + w_man_int->MakeDefault(uid); + //wxCommandEvent event; + //GdaFrame::GetGdaFrame()->OnToolsWeightsManager(event); + } else { + delete dcw; + } + //GdaFrame::GetGdaFrame()->ShowConnectivityMapView(uid); + } delete w; - } else { - success = false; - } - } - } - - FindWindow(XRCID("wxID_OK"))->Enable(true); - return success; + } else { + success = false; + } + } + } + + FindWindow(XRCID("wxID_OK"))->Enable(true); + return success; } - - diff --git a/DialogTools/CreatingWeightDlg.h b/DialogTools/CreatingWeightDlg.h index ae9e438a7..96b5cf4a2 100644 --- a/DialogTools/CreatingWeightDlg.h +++ b/DialogTools/CreatingWeightDlg.h @@ -23,6 +23,7 @@ #include #include #include +#include #include #include #include @@ -36,8 +37,8 @@ class wxSpinButton; class FramesManager; -class GalElement; -class GwtElement; +class GalWeight; +class GwtWeight; class Project; class TableInterface; class TableState; @@ -48,24 +49,25 @@ class CreatingWeightDlg: public wxDialog, public FramesManagerObserver, public TableStateObserver, public WeightsManStateObserver { public: - CreatingWeightDlg(wxWindow* parent, - Project* project, - wxWindowID id = -1, - const wxString& caption = _("Weights File Creation"), - const wxPoint& pos = wxDefaultPosition, - const wxSize& size = wxDefaultSize, - long style = wxCAPTION|wxDEFAULT_DIALOG_STYLE ); + CreatingWeightDlg(wxWindow* parent, + Project* project, + bool user_xy = false, + wxWindowID id = -1, + const wxString& caption = _("Weights File Creation"), + const wxPoint& pos = wxDefaultPosition, + const wxSize& size = wxDefaultSize, + long style = wxCAPTION|wxDEFAULT_DIALOG_STYLE ); virtual ~CreatingWeightDlg(); void OnClose(wxCloseEvent& ev); - bool Create( wxWindow* parent, wxWindowID id = -1, - const wxString& caption = _("Weights File Creation"), - const wxPoint& pos = wxDefaultPosition, - const wxSize& size = wxDefaultSize, - long style = wxCAPTION|wxDEFAULT_DIALOG_STYLE ); + bool Create(wxWindow* parent, wxWindowID id = -1, + const wxString& caption = _("Weights File Creation"), + const wxPoint& pos = wxDefaultPosition, + const wxSize& size = wxDefaultSize, + long style = wxCAPTION|wxDEFAULT_DIALOG_STYLE ); + void CreateControls(); void OnCreateNewIdClick( wxCommandEvent& event ); - - void OnDistanceChoiceSelected(wxCommandEvent& event ); + void OnDistanceChoiceSelected(wxCommandEvent& event ); void SetDistChoiceEuclid(bool update_sel); void SetDistChoiceArcMiles(bool update_sel); void SetDistChoiceArcKms(bool update_sel); @@ -76,14 +78,18 @@ public TableStateObserver, public WeightsManStateObserver void OnYTmSelected(wxCommandEvent& event ); void OnCRadioQueenSelected( wxCommandEvent& event ); void OnCSpinOrderofcontiguityUpdated( wxSpinEvent& event ); - void OnCRadioRookSelected( wxCommandEvent& event ); - void OnCRadioDistanceSelected( wxCommandEvent& event ); void OnCThresholdTextEdit( wxCommandEvent& event ); - void OnCThresholdSliderUpdated( wxCommandEvent& event ); - void OnCRadioKnnSelected( wxCommandEvent& event ); + void OnCBandwidthThresholdTextEdit( wxCommandEvent& event ); + void OnCBandwidthThresholdSliderUpdated( wxCommandEvent& event ); void OnCSpinKnnUpdated( wxSpinEvent& event ); + void OnCSpinKernelKnnUpdated( wxSpinEvent& event ); void OnCreateClick( wxCommandEvent& event ); void OnPrecisionThresholdCheck( wxCommandEvent& event ); + void OnInverseDistCheck( wxCommandEvent& event ); + void OnInverseKNNCheck( wxCommandEvent& event ); + void OnCThresholdSliderUpdated( wxCommandEvent& event ); + void OnCSpinPowerInverseDistUpdated( wxSpinEvent& event ); + void OnCSpinPowerInverseKNNUpdated( wxSpinEvent& event ); /** Implementation of FramesManagerObserver interface */ virtual void update(FramesManager* o); @@ -96,56 +102,79 @@ public TableStateObserver, public WeightsManStateObserver /** Implementation of WeightsManStateObserver interface */ virtual void update(WeightsManState* o); - virtual int numMustCloseToRemove(boost::uuids::uuid id) const { - return 0; } + virtual int numMustCloseToRemove(boost::uuids::uuid id) const { return 0;} virtual void closeObserver(boost::uuids::uuid id) {}; + + void SetXCOO(const std::vector& xx); + void SetYCOO(const std::vector& yy); private: - enum RadioBtnId { NO_RADIO, QUEEN, ROOK, THRESH, KNN }; - + bool all_init; + + // controls wxChoice* m_id_field; + // contiguity weight + wxNotebook* m_nb_weights_type; wxRadioButton* m_radio_queen; // IDC_RADIO_QUEEN wxTextCtrl* m_contiguity; wxSpinButton* m_spincont; wxRadioButton* m_radio_rook; // IDC_RADIO_ROOK wxCheckBox* m_include_lower; + wxCheckBox* m_cbx_precision_threshold; + wxTextCtrl* m_txt_precision_threshold; + // distance weight wxChoice* m_dist_choice; wxChoice* m_X; wxChoice* m_X_time; wxChoice* m_Y; wxChoice* m_Y_time; - wxRadioButton* m_radio_thresh; // IDC_RADIO_DISTANCE + wxNotebook* m_nb_distance_methods; wxTextCtrl* m_threshold; - wxCheckBox* m_cbx_precision_threshold; - wxTextCtrl* m_txt_precision_threshold; wxSlider* m_sliderdistance; - wxRadioButton* m_radio_knn; // IDC_RADIO_KNN + wxCheckBox* m_use_inverse; + wxTextCtrl* m_power; + wxSpinButton* m_spinn_inverse; wxTextCtrl* m_neighbors; wxSpinButton* m_spinneigh; - + wxCheckBox* m_use_inverse_knn; + wxTextCtrl* m_power_knn; + wxSpinButton* m_spinn_inverse_knn; + wxChoice* m_kernel_methods; + wxTextCtrl* m_kernel_neighbors; + wxSpinButton* m_spinn_kernel; + wxRadioButton* m_radio_adaptive_bandwidth; + wxRadioButton* m_radio_auto_bandwidth; + wxRadioButton* m_radio_manu_bandwdith; + wxTextCtrl* m_manu_bandwidth; + wxSlider* m_bandwidth_slider; + wxRadioButton* m_kernel_diagnals; + wxRadioButton* m_const_diagnals; + wxButton* m_btn_ok; + FramesManager* frames_manager; Project* project; TableInterface* table_int; TableState* table_state; WeightsManState* w_man_state; WeightsManInterface* w_man_int; - + + bool user_xy; // col_id_map[i] is a map from the i'th numeric item in the // fields drop-down to the actual col_id_map. Items // in the fields dropdown are in the order displayed // in wxGrid std::vector col_id_map; - RadioBtnId m_radio; int m_num_obs; double m_thres_min; // minimum to avoid isolates double m_thres_max; // maxiumum to include everything double m_threshold_val; - double m_thres_val_valid; + bool m_thres_val_valid; + double m_bandwidth_thres_val; + bool m_bandwidth_thres_val_valid; const double m_thres_delta_factor; bool m_cbx_precision_threshold_first_click; - bool m_is_arc; // true = Arc Dist, false = Euclidean Dist bool m_arc_in_km; // true if Arc Dist in km, else miles std::vector m_XCOO; @@ -158,29 +187,26 @@ public TableStateObserver, public WeightsManStateObserver wxString dist_units_str; wxString dist_var_1; - long dist_tm_1; + long dist_tm_1; wxString dist_var_2; - long dist_tm_2; + long dist_tm_2; // updates the enable/disable state of the Create button based // on the values of various other controls. void UpdateCreateButtonState(); void UpdateTmSelEnableState(); - void SetRadioBtnAndAssocWidgets(RadioBtnId radio); void UpdateThresholdValues(); void ResetThresXandYCombo(); - void EnableThresholdControls(bool b); - void EnableContiguityRadioButtons(bool b); - void EnableDistanceRadioButtons(bool b); - void SetRadioButtons(RadioBtnId id); void InitFields(); void InitDlg(); bool CheckID(const wxString& id); + bool CheckThresholdInput(); + double GetBandwidth(); bool IsSaveAsGwt(); // determine if save type will be GWT or GAL. - bool WriteWeightFile(GalElement *gal, GwtElement *gwt, + bool WriteWeightFile(GalWeight* Wp_gal, GwtWeight* Wp_gwt, const wxString& ifn, const wxString& ofn, const wxString& idd, - const WeightsMetaInfo& wmi); + WeightsMetaInfo& wmi); void CreateWeights(); wxString s_int; diff --git a/DialogTools/CsvFieldConfDlg.cpp b/DialogTools/CsvFieldConfDlg.cpp index 532c465c3..160efd06a 100644 --- a/DialogTools/CsvFieldConfDlg.cpp +++ b/DialogTools/CsvFieldConfDlg.cpp @@ -68,6 +68,7 @@ CsvFieldConfDlg::CsvFieldConfDlg(wxWindow* parent, wxLogMessage("Open CsvFieldConfDlg."); + lat_box = NULL; n_max_rows = 10; filepath = _filepath; @@ -97,7 +98,7 @@ CsvFieldConfDlg::CsvFieldConfDlg(wxWindow* parent, wxStaticText* prev_lbl = new wxStaticText(panel, wxID_ANY, _("Data Preview - number of preview records:")); prev_spin = new wxSpinCtrl(panel, wxID_ANY, ""); n_max_rows = 10; - prev_spin->SetRange(0, 1000); + prev_spin->SetRange(0, 100); prev_spin->SetValue(n_max_rows); prev_spin->Connect(wxEVT_SPINCTRL, wxCommandEventHandler(CsvFieldConfDlg::OnSampleSpinClick), @@ -121,9 +122,9 @@ CsvFieldConfDlg::CsvFieldConfDlg(wxWindow* parent, // lat/lon wxStaticText* lat_lbl = new wxStaticText(panel, wxID_ANY, _("(Optional) Longitude/X:")); wxStaticText* lng_lbl = new wxStaticText(panel, wxID_ANY, _("Latitude/Y:")); - lat_box = new wxComboBox(panel, wxID_ANY, _(""), wxDefaultPosition, + lat_box = new wxComboBox(panel, wxID_ANY, "", wxDefaultPosition, wxSize(80,-1), 0, NULL, wxCB_READONLY); - lng_box = new wxComboBox(panel, wxID_ANY, _(""), wxDefaultPosition, + lng_box = new wxComboBox(panel, wxID_ANY, "", wxDefaultPosition, wxSize(80,-1), 0, NULL, wxCB_READONLY); wxBoxSizer* latlng_box = new wxBoxSizer(wxHORIZONTAL); latlng_box->Add(lat_lbl, 0, wxALIGN_CENTER_VERTICAL); @@ -136,13 +137,13 @@ CsvFieldConfDlg::CsvFieldConfDlg(wxWindow* parent, // first row wxStaticText* header_lbl = new wxStaticText(panel, wxID_ANY, _("(Optional) First record has field names? ")); - wxComboBox* header_cmb = new wxComboBox(panel, wxID_ANY, _(""), + wxComboBox* header_cmb = new wxComboBox(panel, wxID_ANY, "", wxDefaultPosition, wxDefaultSize, 0, NULL, wxCB_READONLY); header_cmb->Append("NO"); header_cmb->Append("YES"); header_cmb->Append("AUTO DETECT"); - header_cmb->SetSelection(2); + header_cmb->SetSelection(1); header_cmb->Connect(wxEVT_COMMAND_COMBOBOX_SELECTED, wxCommandEventHandler(CsvFieldConfDlg::OnHeaderCmbClick), NULL, @@ -273,6 +274,12 @@ void CsvFieldConfDlg::PrereadCSV(int HEADERS) types.push_back("Integer64"); } else if( poFieldDefn->GetType() == OFTReal ) { types.push_back("Real"); + } else if( poFieldDefn->GetType() == OFTDate) { + types.push_back("Date"); + } else if( poFieldDefn->GetType() == OFTTime) { + types.push_back("Time"); + } else if( poFieldDefn->GetType() == OFTDateTime ) { + types.push_back("DateTime"); } else { types.push_back("String"); } @@ -286,25 +293,50 @@ void CsvFieldConfDlg::PrereadCSV(int HEADERS) } prev_data.clear(); + int year = 0; + int month = 0; + int day = 0; + int hour = 0; + int minute = 0; + int second = 0; + int tzflag = 0; + int msg_shown = false; OGRFeature *poFeature; poLayer->ResetReading(); while( (poFeature = poLayer->GetNextFeature()) != NULL ) { - if (cnt > n_max_rows) + if (cnt >= n_max_rows) break; - + + if (cnt == 0) for(int iField = 0; iField < nFields; iField++) { OGRFieldDefn *poFieldDefn = poFDefn->GetFieldDefn( iField ); - - if( poFieldDefn->GetType() == OFTInteger ) { + OGRFieldType poFieldType = poFieldDefn->GetType(); + if( poFieldType == OFTInteger ) { poFeature->GetFieldAsInteger64( iField ); - } else if( poFieldDefn->GetType() == OFTInteger64 ) { + } else if( poFieldType == OFTInteger64 ) { poFeature->GetFieldAsInteger64( iField ); - } else if( poFieldDefn->GetType() == OFTReal ) { + } else if( poFieldType == OFTReal ) { poFeature->GetFieldAsDouble(iField); - } else if( poFieldDefn->GetType() == OFTString ) { + } else if( poFieldType == OFTDate || + poFieldType == OFTTime || + poFieldType == OFTDateTime) + { + int rtn = poFeature->GetFieldAsDateTime(iField, &year, &month, &day, &hour, &minute, &second, &tzflag); + if (rtn == 0) { + if (!msg_shown) { + wxString msg = _("Limited date/time type recognition can be done for Date (YYYY-MM-DD), Time (HH:MM:SS+nn) and DateTime (YYYY-MM-DD HH:MM:SS+nn) in configuration.\n\nPlease try to load customized date/time type as string and covert it using Table->Edit Variable Property"); + wxMessageDialog dlg(NULL, msg, _("CSV Configuration Warning"), wxOK | wxICON_ERROR); + dlg.ShowModal(); + msg_shown = true; + } + types[iField] = "String"; + poFeature->GetFieldAsString(iField); + fieldGrid->SetCellValue(iField, 1, "String"); + } + } else if( poFieldType == OFTString ) { poFeature->GetFieldAsString(iField); } else { poFeature->GetFieldAsString(iField); @@ -313,10 +345,44 @@ void CsvFieldConfDlg::PrereadCSV(int HEADERS) prev_data.push_back(poFeature); cnt += 1; } + GDALClose(poDS); n_prev_rows = cnt; - - GDALClose(poDS); + + if (msg_shown && lat_box) { + wxString lat_col_name = lat_box->GetValue(); + wxString lng_col_name = lng_box->GetValue(); + + wxString csvt; + + int n_rows = col_names.size(); + for (int r=0; r < n_rows; r++ ) { + wxString col_name = fieldGrid->GetCellValue(r, 0); + if (col_name == lat_col_name) { + csvt << "CoordX"; + } else if (col_name == lng_col_name ) { + csvt << "CoordY"; + } else { + wxString type = types[r]; + csvt << type; + } + if (r < n_rows-1) + csvt << ","; + } + + // write back to a CSVT file + wxString csvt_path = filepath + "t"; + wxTextFile file(csvt_path); + file.Open(); + file.Clear(); + + file.AddLine( csvt ); + + file.Write(); + file.Close(); + + PrereadCSV(HEADERS); + } } @@ -357,9 +423,9 @@ void CsvFieldConfDlg::UpdateFieldGrid( ) wxString col_name = col_names[i]; fieldGrid->SetCellValue(i, 0, col_name); - wxString strChoices[5] = {"Real", "Integer", "Integer64","String"}; + wxString strChoices[7] = {"Real", "Integer", "Integer64","String", "Date", "Time", "DateTime"}; int COL_T = 1; - wxGridCellChoiceEditor* m_editor = new wxGridCellChoiceEditor(5, strChoices, false); + wxGridCellChoiceEditor* m_editor = new wxGridCellChoiceEditor(7, strChoices, false); fieldGrid->SetCellEditor(i, COL_T, m_editor); if (types.size() == 0 || i >= types.size() ) { @@ -381,8 +447,11 @@ void CsvFieldConfDlg::UpdateXYcombox( ) lng_box->Clear(); bool first_item = true; + int coord_x_idx = -1; + int coord_y_idx = -1; + int cnt = 1; for (int i=0; iAppend(""); lng_box->Append(""); @@ -390,37 +459,13 @@ void CsvFieldConfDlg::UpdateXYcombox( ) } lat_box->Append(col_names[i]); lng_box->Append(col_names[i]); + if (types[i] == "CoordX") coord_x_idx = cnt; + else if (types[i] == "CoordY") coord_y_idx = cnt; + cnt ++; } } - - wxString csvt_path = filepath + "t"; - - if (wxFileExists(csvt_path)) { - // load data type from csvt file - wxTextFile csvt_file; - csvt_file.Open(csvt_path); - - // read the first line - wxString str = csvt_file.GetFirstLine(); - wxStringTokenizer tokenizer(str, ","); - - int idx = 0; - while ( tokenizer.HasMoreTokens() ) - { - wxString token = tokenizer.GetNextToken().Upper(); - if (token.Contains("COORDX")) { - wxString col_name = col_names[idx]; - int pos = lng_box->FindString(col_name); - lat_box->SetSelection(pos); - } else if (token.Contains("COORDY")) { - wxString col_name = col_names[idx]; - int pos = lng_box->FindString(col_name); - lng_box->SetSelection(pos); - } - idx += 1; - } - } - + lat_box->SetSelection(coord_x_idx); + lng_box->SetSelection(coord_y_idx); } void CsvFieldConfDlg::UpdatePreviewGrid( ) @@ -433,8 +478,10 @@ void CsvFieldConfDlg::UpdatePreviewGrid( ) int n_new_row = n_prev_rows; - if (n_max_rows < n_new_row) n_new_row = n_max_rows; - + if (n_max_rows > n_new_row) n_new_row = n_max_rows; + + if (n_new_row > prev_data.size()) n_new_row = prev_data.size(); + if (n_grid_row < n_new_row) { previewGrid->InsertRows(0, n_new_row - n_grid_row); } @@ -457,7 +504,7 @@ void CsvFieldConfDlg::UpdatePreviewGrid( ) if (types[j] == "Integer" || types[j] == "Integer64") { wxInt64 val = poFeature->GetFieldAsInteger64(j); - wxString str = wxString::Format(wxT("%") wxT(wxLongLongFmtSpec) wxT("d"), val); + wxString str = wxString::Format("%" wxLongLongFmtSpec "d", val); previewGrid->SetCellValue(i, j, str); } else if (types[j] == "Real") { @@ -465,6 +512,10 @@ void CsvFieldConfDlg::UpdatePreviewGrid( ) wxString str = wxString::Format("%f", val); previewGrid->SetCellValue(i, j, str); + } else if (types[j] == "Date" || types[j] == "Time" || types[j] == "DateTime") { + wxString str = poFeature->GetFieldAsString(j); + //wxString str = wxString::Format("%f", val); + previewGrid->SetCellValue(i, j, str); } else { wxString str = poFeature->GetFieldAsString(j); previewGrid->SetCellValue(i, j, str); @@ -500,6 +551,16 @@ void CsvFieldConfDlg::ReadCSVT() types[idx] = "Integer"; } else if (token.Contains("REAL")) { types[idx] = "Real"; + } else if (token.Contains("COORDX")) { + types[idx] = "CoordX"; + } else if (token.Contains("COORDY")) { + types[idx] = "CoordY"; + } else if (token.Contains("DATETIME")) { + types[idx] = "DateTime"; + } else if (token.Contains("TIME")) { + types[idx] = "Time"; + } else if (token.Contains("DATE")) { + types[idx] = "Date"; } else { types[idx] = "String"; } @@ -548,7 +609,6 @@ void CsvFieldConfDlg::OnOkClick( wxCommandEvent& event ) wxLogMessage("CsvFieldConfDlg::OnOkClick()"); WriteCSVT(); - GdaConst::gda_ogr_csv_header = HEADERS; EndDialog(wxID_OK); } @@ -579,12 +639,14 @@ void CsvFieldConfDlg::OnHeaderCmbClick( wxCommandEvent& event ) UpdateFieldGrid(); UpdatePreviewGrid(); UpdateXYcombox(); - + + GdaConst::gda_ogr_csv_header = HEADERS; } void CsvFieldConfDlg::OnSampleSpinClick( wxCommandEvent& event ) { wxLogMessage("CsvFieldConfDlg::OnSampleSpinClick()"); n_max_rows = prev_spin->GetValue(); + PrereadCSV(HEADERS); UpdatePreviewGrid(); } diff --git a/DialogTools/DatasourceDlg.cpp b/DialogTools/DatasourceDlg.cpp index c3313fdc0..8fca74723 100644 --- a/DialogTools/DatasourceDlg.cpp +++ b/DialogTools/DatasourceDlg.cpp @@ -37,7 +37,6 @@ #include "../Project.h" #include "../DataViewer/DataSource.h" -#include "../DataViewer/DbfTable.h" #include "../DataViewer/TableInterface.h" #include "../GenUtils.h" #include "../logger.h" @@ -50,59 +49,6 @@ using namespace std; -DatasourceDlg::DatasourceDlg() -: is_ok_clicked(false), eventLoop(NULL) -{ - Connect( wxEVT_CLOSE_WINDOW, wxCloseEventHandler(DatasourceDlg::OnExit) ); -} - -DatasourceDlg::~DatasourceDlg() -{ - if (eventLoop) { - delete eventLoop; - eventLoop = NULL; - } -} - -int DatasourceDlg::GetType() -{ - return type; -} - -int DatasourceDlg::ShowModal() -{ - Show(true); - - // mow to stop execution start a event loop - eventLoop = new wxEventLoop; - if (eventLoop == NULL) - return wxID_CANCEL; - - eventLoop->Run(); - - if (is_ok_clicked) - return wxID_OK; - else - return wxID_CANCEL; -} - -void DatasourceDlg::EndDialog() -{ - eventLoop->Exit(); - Show(false); - //Destroy(); -} - -void DatasourceDlg::OnCancelClick( wxCommandEvent& event ) -{ - EndDialog(); -} - -void DatasourceDlg::OnExit(wxCloseEvent& e) -{ - EndDialog(); -} - void DatasourceDlg::Init() { m_ds_menu = NULL; @@ -177,13 +123,13 @@ void DatasourceDlg::CreateControls() m_database_type->SetSelection(0); // for autocompletion of input boxes in Database Tab - vector host_cands = + vector host_cands = OGRDataAdapter::GetInstance().GetHistory("db_host"); - vector port_cands = + vector port_cands = OGRDataAdapter::GetInstance().GetHistory("db_port"); - vector uname_cands = + vector uname_cands = OGRDataAdapter::GetInstance().GetHistory("db_user"); - vector name_cands = + vector name_cands = OGRDataAdapter::GetInstance().GetHistory("db_name"); m_database_host->SetAutoList(host_cands); @@ -192,13 +138,13 @@ void DatasourceDlg::CreateControls() m_database_name->SetAutoList(name_cands); // get a latest input DB information - vector db_infos = OGRDataAdapter::GetInstance().GetHistory("db_info"); + vector db_infos = OGRDataAdapter::GetInstance().GetHistory("db_info"); if (db_infos.size() > 0) { - string db_info = db_infos[0]; + wxString db_info = db_infos[0]; json_spirit::Value v; // try to parse as JSON try { - if (!json_spirit::read( db_info, v)) { + if (!json_spirit::read(db_info.ToStdString(), v)) { throw runtime_error("Could not parse title as JSON"); } json_spirit::Value json_db_type; @@ -243,17 +189,17 @@ void DatasourceDlg::CreateControls() } // get a latest CartoDB account - vector cartodb_user = OGRDataAdapter::GetInstance().GetHistory("cartodb_user"); + vector cartodb_user = OGRDataAdapter::GetInstance().GetHistory("cartodb_user"); if (!cartodb_user.empty()) { - string user = cartodb_user[0]; + wxString user = cartodb_user[0]; CartoDBProxy::GetInstance().SetUserName(user); // control m_cartodb_uname->SetValue(user); } - vector cartodb_key = OGRDataAdapter::GetInstance().GetHistory("cartodb_key"); + vector cartodb_key = OGRDataAdapter::GetInstance().GetHistory("cartodb_key"); if (!cartodb_key.empty()) { - string key = cartodb_key[0]; + wxString key = cartodb_key[0]; CartoDBProxy::GetInstance().SetKey(key); // control m_cartodb_key->SetValue(key); @@ -296,7 +242,10 @@ void DatasourceDlg::PromptDSLayers(IDataSource* datasource) throw GdaException(msg.mb_str()); } - vector table_names = OGRDataAdapter::GetInstance().GetLayerNames(ds_name, ds_type); + vector table_names; + ds_type = OGRDataAdapter::GetInstance().GetLayerNames(ds_name, ds_type, table_names); + + datasource->UpdateDataSource(ds_type); int n_tables = table_names.size(); @@ -337,15 +286,12 @@ void DatasourceDlg::OnBrowseDSfileBtn ( wxCommandEvent& event ) if (ds_names[i].IsEmpty()) { m_ds_menu->AppendSeparator(); } else { - m_ds_menu->Append( ID_DS_START + i, ds_names[i].BeforeFirst('|')); + m_ds_menu->Append( GdaConst::ID_CONNECT_POPUP_MENU + i, ds_names[i].BeforeFirst('|')); } } } - - wxActivateEvent ae(wxEVT_NULL, true, 0, wxActivateEvent::Reason_Mouse); - OnActivate(ae); - PopupMenu(m_ds_menu); + PopupMenu(m_ds_menu); event.Skip(); } @@ -360,7 +306,7 @@ void DatasourceDlg::OnBrowseDSfileBtn ( wxCommandEvent& event ) void DatasourceDlg::BrowseDataSource( wxCommandEvent& event) { - int index = event.GetId() - ID_DS_START; + int index = event.GetId() - GdaConst::ID_CONNECT_POPUP_MENU; wxString name = ds_names[index]; if (name.Contains("gdb")) { diff --git a/DialogTools/DatasourceDlg.h b/DialogTools/DatasourceDlg.h index bcc1c3904..e5fe48740 100644 --- a/DialogTools/DatasourceDlg.h +++ b/DialogTools/DatasourceDlg.h @@ -31,36 +31,20 @@ #include #include #include -#include -#include #include "../DataViewer/DataSource.h" #include "AutoCompTextCtrl.h" - -class DatasourceDlg : public wxFrame +class DatasourceDlg : public wxDialog { -protected: - enum DS_IDS - { - ID_DS_START=8001 - }; - public: - DatasourceDlg(); - virtual ~DatasourceDlg(); + DatasourceDlg(){} + virtual ~DatasourceDlg(){} virtual void OnOkClick( wxCommandEvent& event ) = 0; - - void OnExit(wxCloseEvent& e); - int GetType(); - - wxFileName ds_file_path; + wxFileName ds_file_path; + protected: - wxEventLoop* eventLoop; - bool is_ok_clicked; - int type; /*0 connect 1 export 2 Merge*/ - wxTextCtrl* m_ds_filepath_txt; wxBitmapButton* m_ds_browse_file_btn; //wxBitmapButton* m_database_lookup_table; @@ -84,10 +68,6 @@ class DatasourceDlg : public wxFrame wxArrayString ds_names; public: - void EndDialog(); - int ShowModal(); - void OnCancelClick( wxCommandEvent& event ); - void Init(); void CreateControls(); void PromptDSLayers(IDataSource* datasource); diff --git a/DialogTools/ExportCsvDlg.cpp b/DialogTools/ExportCsvDlg.cpp index c6f70c24d..5db3ef80f 100644 --- a/DialogTools/ExportCsvDlg.cpp +++ b/DialogTools/ExportCsvDlg.cpp @@ -97,21 +97,25 @@ void ExportCsvDlg::OnOkClick( wxCommandEvent& event ) if (!wxRemoveFile(new_csv)) { wxString msg("Unable to overwrite "); msg << new_main_name + ".csv"; - wxMessageDialog dlg (this, msg, "Error", wxOK | wxICON_ERROR); + wxMessageDialog dlg (this, msg, _("Error"), wxOK | wxICON_ERROR); dlg.ShowModal(); return; } } wxLogMessage(_("csv file:") + new_csv); +#ifdef __WIN32__ + std::ofstream out_file(new_csv.wc_str(),std::ios::out | std::ios::binary); +#else std::ofstream out_file; - out_file.open(GET_ENCODED_FILENAME(new_csv), - std::ios::out | std::ios::binary); + out_file.open(GET_ENCODED_FILENAME(new_csv),std::ios::out | std::ios::binary); +#endif + if (!(out_file.is_open() && out_file.good())) { wxString msg; msg << "Unable to create CSV file."; - wxMessageDialog dlg(this, msg, "Error", wxOK | wxICON_ERROR); + wxMessageDialog dlg(this, msg, _("Error"), wxOK | wxICON_ERROR); dlg.ShowModal(); return; } diff --git a/DialogTools/ExportCsvDlg.h b/DialogTools/ExportCsvDlg.h index df8913fb3..1f8a1d2b1 100644 --- a/DialogTools/ExportCsvDlg.h +++ b/DialogTools/ExportCsvDlg.h @@ -23,7 +23,6 @@ #include #include #include -#include "../DbfFile.h" class Project; class TableInterface; diff --git a/DialogTools/ExportDataDlg.cpp b/DialogTools/ExportDataDlg.cpp index a9a60148b..e660534a6 100644 --- a/DialogTools/ExportDataDlg.cpp +++ b/DialogTools/ExportDataDlg.cpp @@ -39,7 +39,6 @@ #include "../Project.h" #include "../DataViewer/TableInterface.h" -#include "../DataViewer/DbfTable.h" #include "../DataViewer/DataSource.h" #include "../GenUtils.h" #include "../logger.h" @@ -52,10 +51,10 @@ using namespace std; -BEGIN_EVENT_TABLE( ExportDataDlg, wxFrame ) +BEGIN_EVENT_TABLE( ExportDataDlg, wxDialog ) EVT_BUTTON( XRCID("IDC_OPEN_IASC"), ExportDataDlg::OnBrowseDSfileBtn ) EVT_BUTTON( wxID_OK, ExportDataDlg::OnOkClick ) - EVT_BUTTON( wxID_CANCEL, ExportDataDlg::OnCancelClick ) + //EVT_BUTTON( wxID_CANCEL, ExportDataDlg::OnCancelClick ) END_EVENT_TABLE() ExportDataDlg::ExportDataDlg(wxWindow* parent, @@ -70,7 +69,8 @@ project_file_name(projectFileName), is_saveas_op(true), is_geometry_only(false), is_table_only(false), -is_save_centroids(false) +is_save_centroids(false), +spatial_ref(NULL) { if( project_p ) { @@ -78,7 +78,6 @@ is_save_centroids(false) table_p = project_p->GetTableInt(); } Init(parent, pos); - type = 2; } ExportDataDlg::ExportDataDlg(wxWindow* parent, @@ -88,14 +87,19 @@ ExportDataDlg::ExportDataDlg(wxWindow* parent, bool isSelectedOnly, const wxPoint& pos, const wxSize& size) -: is_selected_only(isSelectedOnly), project_p(_project), geometries(_geometries), shape_type(_shape_type), is_saveas_op(false), is_geometry_only(true), table_p(NULL), is_table_only(false), is_save_centroids(false) +: is_selected_only(isSelectedOnly), project_p(_project), geometries(_geometries), shape_type(_shape_type), is_saveas_op(false), is_geometry_only(true), table_p(NULL), is_table_only(false), is_save_centroids(false),spatial_ref(NULL) { if( project_p) { project_file_name = project_p->GetProjectTitle(); table_p = project_p->GetTableInt(); } Init(parent, pos); - type = 2; +} + +ExportDataDlg::ExportDataDlg(wxWindow* parent, Shapefile::ShapeType _shape_type, std::vector& _geometries, OGRSpatialReference* _spatial_ref, OGRTable* table, const wxPoint& pos, const wxSize& size) +: is_selected_only(false), project_p(NULL), geometries(_geometries), shape_type(_shape_type), is_saveas_op(true), is_geometry_only(false), table_p(table), is_table_only(false), is_save_centroids(false), spatial_ref(_spatial_ref) +{ + Init(parent, pos); } // Export POINT data only, e.g. centroids/mean centers @@ -107,7 +111,7 @@ ExportDataDlg::ExportDataDlg(wxWindow* parent, bool isSelectedOnly, const wxPoint& pos, const wxSize& size) -: is_selected_only(isSelectedOnly), project_p(_project), is_saveas_op(false), shape_type(_shape_type),is_geometry_only(true), table_p(NULL), is_table_only(false), is_save_centroids(true) +: is_selected_only(isSelectedOnly), project_p(_project), is_saveas_op(false), shape_type(_shape_type),is_geometry_only(true), table_p(NULL), is_table_only(false), is_save_centroids(true), spatial_ref(NULL) { if( project_p) { @@ -119,7 +123,6 @@ ExportDataDlg::ExportDataDlg(wxWindow* parent, geometries.push_back((GdaShape*)_geometries[i]); } Init(parent, pos); - type = 2; } // Export in-memory table (e.g. space-time table) @@ -127,10 +130,9 @@ ExportDataDlg::ExportDataDlg(wxWindow* parent, TableInterface* _table, const wxPoint& pos, const wxSize& size) -: is_selected_only(false), project_p(NULL), is_saveas_op(false), shape_type(Shapefile::NULL_SHAPE), is_geometry_only(false), is_table_only(true), table_p(_table), is_save_centroids(false) +: is_selected_only(false), project_p(NULL), is_saveas_op(false), shape_type(Shapefile::NULL_SHAPE), is_geometry_only(false), is_table_only(true), table_p(_table), is_save_centroids(false), spatial_ref(NULL) { Init(parent, pos); - type = 2; } @@ -144,19 +146,18 @@ void ExportDataDlg::Init(wxWindow* parent, const wxPoint& pos) if (is_table_only) ds_names.Remove("ESRI Shapefile (*.shp)|*.shp"); + //ds_names.Remove("dBase database file (*.dbf)|*.dbf"); ds_names.Remove("MS Excel (*.xls)|*.xls"); //ds_names.Remove("MS Office Open XML Spreadsheet (*.xlsx)|*.xlsx"); //ds_names.Remove("U.S. Census TIGER/Line (*.tiger)|*.tiger"); //ds_names.Remove("Idrisi Vector (*.vct)|*.vct"); - if( GeneralWxUtils::isWindows()){ + + if( GeneralWxUtils::isWindows()) ds_names.Remove("ESRI Personal Geodatabase (*.mdb)|*.mdb"); - } - Bind( wxEVT_COMMAND_MENU_SELECTED, - &ExportDataDlg::BrowseExportDataSource, - this, DatasourceDlg::ID_DS_START, - ID_DS_START + ds_names.Count()); + Bind(wxEVT_COMMAND_MENU_SELECTED, &ExportDataDlg::BrowseExportDataSource, this, GdaConst::ID_CONNECT_POPUP_MENU, GdaConst::ID_CONNECT_POPUP_MENU + ds_names.Count()); + SetParent(parent); CreateControls(); SetPosition(pos); @@ -166,7 +167,7 @@ void ExportDataDlg::Init(wxWindow* parent, const wxPoint& pos) void ExportDataDlg::CreateControls() { - wxXmlResource::Get()->LoadFrame(this, GetParent(), "IDD_EXPORT_OGRDATA"); + wxXmlResource::Get()->LoadDialog(this, GetParent(), "IDD_EXPORT_OGRDATA"); FindWindow(XRCID("wxID_OK"))->Enable(true); m_database_table = XRCCTRL(*this, "IDC_CDS_DB_TABLE",AutoTextCtrl); m_chk_create_project = XRCCTRL(*this, "IDC_CREATE_PROJECT_FILE",wxCheckBox); @@ -189,7 +190,7 @@ void ExportDataDlg::BrowseExportDataSource ( wxCommandEvent& event ) // for datasource file, we should support many file types: // SHP, DBF, CSV, GML, ... //bool table_only = m_chk_table_only->IsChecked(); - int index = event.GetId() - ID_DS_START; + int index = event.GetId() - GdaConst::ID_CONNECT_POPUP_MENU; wxString name = ds_names[index]; wxString wildcard; wildcard << name ; @@ -221,9 +222,9 @@ void ExportDataDlg::BrowseExportDataSource ( wxCommandEvent& event ) } // construct the export datasource file name wxString ext_str; - if (ds_file_path.GetExt().IsEmpty()){ + if (ds_file_path.GetExt().IsEmpty()) { wxString msg = wxString::Format(_("Can't get datasource type from: %s\n\nPlease select datasource supported by GeoDa or add extension to file datasource."), ds_file_path.GetFullPath()); - wxMessageDialog dlg(this, msg, "Warning", wxOK | wxICON_WARNING); + wxMessageDialog dlg(this, msg, _("Warning"), wxOK | wxICON_WARNING); dlg.ShowModal(); return; } else { @@ -250,9 +251,7 @@ void ExportDataDlg::OnOkClick( wxCommandEvent& event ) wxLogMessage(_("ds:") + ds_name); if (ds_name.length() <= 0 ) { - wxMessageDialog dlg(this, _("Please specify a valid data source name."), - _("Warning"), - wxOK | wxICON_WARNING); + wxMessageDialog dlg(this, _("Please specify a valid data source name."), _("Warning"), wxOK | wxICON_WARNING); dlg.ShowModal(); return; } @@ -261,14 +260,15 @@ void ExportDataDlg::OnOkClick( wxCommandEvent& event ) wxString tmp_ds_name; try{ - OGRSpatialReference* spatial_ref = NULL; - if ( project_p == NULL ) { //project does not exist, could be created a datasource from - //geometries only, e.g. boundray file + //geometries only, e.g. boundray file or in-memory geometries&table + if (spatial_ref && table_p) { + // https://github.com/GeoDaCenter/geoda/issues/1046 + + } } else { //case: save current open datasource as a new datasource - spatial_ref = project_p->GetSpatialReference(); // warning if saveas not compaptible GdaConst::DataSourceType o_ds_type = project_p->GetDatasourceType(); @@ -309,7 +309,6 @@ void ExportDataDlg::OnOkClick( wxCommandEvent& event ) } } - if (o_ds_table_only && !n_ds_table_only) { if (project_p && project_p->main_data.records.size() ==0) { if (ds_type == GdaConst::ds_geo_json || @@ -332,7 +331,6 @@ void ExportDataDlg::OnOkClick( wxCommandEvent& event ) } } } - // by default the datasource will be re-created, except for some special // cases: e.g. sqlite, ESRI FileGDB if (datasource_type == 0) { @@ -355,9 +353,6 @@ void ExportDataDlg::OnOkClick( wxCommandEvent& event ) } } } - - - if( !CreateOGRLayer(ds_name, spatial_ref, is_update) ) { wxString msg = _("Save As has been cancelled."); throw GdaException(msg.mb_str(), GdaException::NORMAL); @@ -380,7 +375,8 @@ void ExportDataDlg::OnOkClick( wxCommandEvent& event ) wxFileDialog dlg(this, file_dlg_title, wxEmptyString, wxEmptyString, file_dlg_type, wxFD_SAVE | wxFD_OVERWRITE_PROMPT); - if (dlg.ShowModal() != wxID_OK) return; + if (dlg.ShowModal() != wxID_OK) + return; wxFileName f(dlg.GetPath()); f.SetExt("gda"); proj_fname = f.GetFullPath(); @@ -390,8 +386,7 @@ void ExportDataDlg::OnOkClick( wxCommandEvent& event ) // save project file wxFileName new_proj_fname(proj_fname); wxString proj_title = new_proj_fname.GetName(); - LayerConfiguration* layer_conf - = project_conf->GetLayerConfiguration(); + LayerConfiguration* layer_conf = project_conf->GetLayerConfiguration(); layer_conf->SetName(layer_name); layer_conf->UpdateDataSource(datasource); project_conf->Save(proj_fname); @@ -425,11 +420,10 @@ void ExportDataDlg::OnOkClick( wxCommandEvent& event ) //wxString msg = "Export successfully."; //msg << "\n\nTips: if you want to use exported project/datasource, please" // << " close current project and then open exported project/datasource."; - //wxMessageDialog dlg(this, msg , "Info", wxOK | wxICON_INFORMATION); + //wxMessageDialog dlg(this, msg , _("Info"), wxOK | wxICON_INFORMATION); //dlg.ShowModal(); - is_ok_clicked = true; - EndDialog(); + EndDialog(wxID_OK); } /** @@ -488,7 +482,6 @@ ExportDataDlg::CreateOGRLayer(wxString& ds_name, // for shp/dbf reading, we need to convert Main data to GdaShape first // this will spend some time, but keep the rest of code clean. // Note: potential speed/memory performance issue - vector selected_rows; if ( project_p != NULL && geometries.empty() && !is_save_centroids ) { @@ -511,7 +504,15 @@ ExportDataDlg::CreateOGRLayer(wxString& ds_name, PointContents* pc; for (int i=0; imain_data.records[i].contents_p; - geometries.push_back(new GdaPoint(wxRealPoint(pc->x, pc->y))); + if (pc->x == 0 && pc->y==0 && + (pc->x < project_p->main_data.header.bbox_x_min || + pc->x > project_p->main_data.header.bbox_x_max) && + (pc->y < project_p->main_data.header.bbox_y_min || + pc->y > project_p->main_data.header.bbox_y_max)) + { + geometries.push_back(new GdaPoint()); + } else + geometries.push_back(new GdaPoint(wxRealPoint(pc->x, pc->y))); } shape_type = Shapefile::POINT_TYP; } @@ -690,11 +691,11 @@ IDataSource* ExportDataDlg::GetDatasource() } // check if empty, prompt user to input - if (dbhost.IsEmpty()) error_msg = "Please input database host."; - else if (dbname.IsEmpty()) error_msg= "Please input database name."; - else if (dbport.IsEmpty()) error_msg= "Please input database port."; - else if (dbuser.IsEmpty()) error_msg= "Please input user name."; - else if (layer_name.IsEmpty()) error_msg= "Please input table name."; + if (dbhost.IsEmpty()) error_msg = _("Please input database host."); + else if (dbname.IsEmpty()) error_msg= _("Please input database name."); + else if (dbport.IsEmpty()) error_msg= _("Please input database port."); + else if (dbuser.IsEmpty()) error_msg= _("Please input user name."); + else if (layer_name.IsEmpty()) error_msg= _("Please input table name."); if (!error_msg.IsEmpty()) throw GdaException(error_msg.mb_str()); @@ -707,10 +708,12 @@ IDataSource* ExportDataDlg::GetDatasource() std::string key(m_cartodb_key->GetValue().Trim().mb_str()); if (user.empty()) { - throw GdaException("Please input Carto User Name."); + wxString msg = _("Please input Carto User Name."); + throw GdaException(msg.mb_str()); } if (key.empty()) { - throw GdaException("Please input Carto App Key."); + wxString msg = _("Please input Carto App Key."); + throw GdaException(msg.mb_str()); } CPLSetConfigOption("CARTODB_API_KEY", key.c_str()); @@ -719,7 +722,7 @@ IDataSource* ExportDataDlg::GetDatasource() CartoDBProxy::GetInstance().SetKey(key); CartoDBProxy::GetInstance().SetUserName(user); - wxString url = "CartoDB:" + user; + wxString url = "Carto:" + user; ds_format = IDataSource::GetDataTypeNameByGdaDSType(GdaConst::ds_cartodb); diff --git a/DialogTools/ExportDataDlg.h b/DialogTools/ExportDataDlg.h index 757404b47..2b1e5578f 100644 --- a/DialogTools/ExportDataDlg.h +++ b/DialogTools/ExportDataDlg.h @@ -56,6 +56,16 @@ class ExportDataDlg: public DatasourceDlg const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize); + // save in-memory geometries&table + ExportDataDlg(wxWindow* parent, + Shapefile::ShapeType _shape_type, + std::vector& _geometries, + OGRSpatialReference* spatial_ref, + OGRTable* table, + const wxPoint& pos = wxDefaultPosition, + const wxSize& size = wxDefaultSize); + + // Save centroids ExportDataDlg(wxWindow* parent, std::vector& _geometries, Shapefile::ShapeType _shape_type, @@ -75,7 +85,6 @@ class ExportDataDlg: public DatasourceDlg void BrowseExportDataSource( wxCommandEvent& event ); virtual void OnOkClick( wxCommandEvent& event ); -public: bool IsTableOnly(); wxString GetDatasourceName() { return datasource_name; } wxString GetDatasourceFormat() { return ds_format; } @@ -88,6 +97,8 @@ class ExportDataDlg: public DatasourceDlg TableInterface* table_p; vector geometries; Shapefile::ShapeType shape_type; + OGRSpatialReference* spatial_ref; + wxString project_file_name; wxFileName ds_file_path; wxString ds_format; @@ -101,7 +112,6 @@ class ExportDataDlg: public DatasourceDlg // so its memory will be maintained (no cleanup). bool is_geometry_only; bool is_table_only; - bool is_save_centroids; IDataSource* GetDatasource(); diff --git a/DialogTools/FieldNameCorrectionDlg.cpp b/DialogTools/FieldNameCorrectionDlg.cpp index 3a7f030df..0a15d8d14 100644 --- a/DialogTools/FieldNameCorrectionDlg.cpp +++ b/DialogTools/FieldNameCorrectionDlg.cpp @@ -40,7 +40,7 @@ END_EVENT_TABLE() ScrolledWidgetsPane::ScrolledWidgetsPane(wxWindow* parent, wxWindowID id, GdaConst::DataSourceType ds_type, vector& all_fname) -: wxScrolledWindow(parent, id), ds_type(ds_type), need_correction(false) +: wxScrolledWindow(parent, id, wxDefaultPosition, wxSize(700,300)), ds_type(ds_type), need_correction(false) { vector merged_field_names; set bad_fnames, dup_fname, uniq_upper_fname; @@ -85,8 +85,11 @@ ScrolledWidgetsPane::ScrolledWidgetsPane(wxWindow* parent, wxWindowID id, vector& merged_field_names, set& dup_fname, set& bad_fname) -: wxScrolledWindow(parent, id), field_names_dict(fnames_dict), ds_type(ds_type), -merged_field_names(merged_field_names), need_correction(true) +: wxScrolledWindow(parent, id, wxDefaultPosition, wxSize(700,300)), +field_names_dict(fnames_dict), +ds_type(ds_type), +merged_field_names(merged_field_names), +need_correction(true) { Init(merged_field_names, dup_fname, bad_fname); } @@ -98,6 +101,7 @@ ScrolledWidgetsPane::~ScrolledWidgetsPane() delete txt_fname[i]; delete txt_input[i]; delete txt_info[i]; + delete input_info[i]; } } @@ -116,27 +120,34 @@ void ScrolledWidgetsPane::Init(vector& dup_fname_idx_s, n_fields = dup_fname_idx_s.size() + bad_fname_idx_s.size(); int nrow = n_fields + 2; // for buttons - int ncol = 3; + int ncol = 4; wxString warn_msg; - wxString DUP_WARN = "Duplicate field name."; - wxString INV_WARN = "Field name is not valid."; + wxString DUP_WARN = _("(Duplicate field name)"); + wxString INV_WARN = _("(Field name is not valid)"); - wxFlexGridSizer* sizer = new wxFlexGridSizer(nrow, ncol, 0, 0); + wxFlexGridSizer* sizer = new wxFlexGridSizer(nrow, ncol, 10, 0); // add a series of widgets + SetBackgroundColour(*wxWHITE); txt_fname.clear(); // ID_FNAME_STAT_TXT_BASE txt_input.clear(); // ID_INPUT_TXT_CTRL_BASE txt_info.clear(); // ID_INFO_STAT_TXT_BASE + input_info.clear(); // titile - wxStaticText* txt_oname=new wxStaticText(this, wxID_ANY, "Field name:"); - sizer->Add(txt_oname, 0, wxALIGN_LEFT|wxALL, 15); - wxStaticText* txt_newname=new wxStaticText(this,wxID_ANY,"New field name:"); - sizer->Add(txt_newname, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL, 15); - wxStaticText* txt_orest=new wxStaticText(this, wxID_ANY, "Field restrictions:"); - sizer->Add(txt_orest, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL, 15); + wxStaticText* txt_oname=new wxStaticText(this, wxID_ANY, _("Current field name:")); + sizer->Add(txt_oname, 0, wxALIGN_LEFT); + + wxStaticText* txt_orest=new wxStaticText(this, wxID_ANY, wxEmptyString); + sizer->Add(txt_orest, 0); + + wxStaticText* txt_newname=new wxStaticText(this,wxID_ANY, _("Suggested field name:")); + sizer->Add(txt_newname, 0, wxALIGN_LEFT|wxLEFT, 10); + + wxStaticText* txt_input_info =new wxStaticText(this, wxID_ANY, wxEmptyString); + sizer->Add(txt_input_info, 0); size_t ctrl_cnt = 0; @@ -146,18 +157,26 @@ void ScrolledWidgetsPane::Init(vector& dup_fname_idx_s, wxString field_name = old_field_names[fname_idx]; warn_msg=DUP_WARN; - wxString id_name1, id_name2, id_name3; + wxString id_name1, id_name2, id_name3, id_name4; id_name1 << "ID_FNAME_STAT_TXT_BASE" << ctrl_cnt; id_name2 << "ID_INPUT_TXT_CTRL_BASE" << ctrl_cnt; id_name3 << "ID_INFO_STAT_TXT_BASE" << ctrl_cnt; + id_name4 << "ID_INPUT_INFO_STAT_TXT_BASE" << ctrl_cnt; wxString user_field_name = GetSuggestFieldName(fname_idx); txt_fname.push_back(new wxStaticText(this, XRCID(id_name1), field_name)); - sizer->Add(txt_fname[ctrl_cnt], 0, wxALIGN_LEFT|wxALL, 5); - txt_input.push_back(new wxTextCtrl(this, XRCID(id_name2), user_field_name, wxDefaultPosition,wxSize(240,-1))); - sizer->Add(txt_input[ctrl_cnt], 0, wxALIGN_LEFT|wxALL, 5); + sizer->Add(txt_fname[ctrl_cnt], 0, wxALIGN_LEFT|wxALL); + txt_info.push_back(new wxStaticText(this, XRCID(id_name3), warn_msg)); - sizer->Add(txt_info[ctrl_cnt], 0, wxALIGN_LEFT|wxALL, 5); + sizer->Add(txt_info[ctrl_cnt], 0, wxALIGN_LEFT|wxALL); + + wxTextCtrl* user_input = new wxTextCtrl(this, XRCID(id_name2), user_field_name, wxDefaultPosition,wxSize(240,-1),wxTE_PROCESS_ENTER); + user_input->Bind(wxEVT_TEXT_ENTER, &ScrolledWidgetsPane::OnUserInput, this); + txt_input.push_back(user_input); + sizer->Add(txt_input[ctrl_cnt], 0, wxALIGN_LEFT|wxLEFT, 10); + + input_info.push_back(new wxStaticText(this, XRCID(id_name4), wxEmptyString)); + sizer->Add(input_info[ctrl_cnt], 0, wxALIGN_LEFT|wxLEFT, 2); ++ctrl_cnt; } @@ -168,37 +187,41 @@ void ScrolledWidgetsPane::Init(vector& dup_fname_idx_s, wxString field_name = old_field_names[fname_idx]; warn_msg=INV_WARN; - wxString id_name1, id_name2, id_name3; + wxString id_name1, id_name2, id_name3, id_name4; id_name1 << "ID_FNAME_STAT_TXT_BASE" << ctrl_cnt; id_name2 << "ID_INPUT_TXT_CTRL_BASE" << ctrl_cnt; id_name3 << "ID_INFO_STAT_TXT_BASE" << ctrl_cnt; + id_name4 << "ID_INPUT_INFO_STAT_TXT_BASE" << ctrl_cnt; wxString user_field_name = GetSuggestFieldName(fname_idx); txt_fname.push_back(new wxStaticText(this, XRCID(id_name1), field_name)); - sizer->Add(txt_fname[ctrl_cnt], 0, wxALIGN_LEFT|wxALL, 5); - txt_input.push_back(new wxTextCtrl(this, XRCID(id_name2), user_field_name, wxDefaultPosition,wxSize(240,-1))); - sizer->Add(txt_input[ctrl_cnt], 0, wxALIGN_LEFT|wxALL, 5); + sizer->Add(txt_fname[ctrl_cnt], 0, wxALIGN_LEFT|wxALL); + txt_info.push_back(new wxStaticText(this, XRCID(id_name3), warn_msg)); - sizer->Add(txt_info[ctrl_cnt], 0, wxALIGN_LEFT|wxALL, 5); + sizer->Add(txt_info[ctrl_cnt], 0, wxALIGN_LEFT|wxALL); + + wxTextCtrl* user_input = new wxTextCtrl(this, XRCID(id_name2), user_field_name, wxDefaultPosition,wxSize(240,-1),wxTE_PROCESS_ENTER); + user_input->Bind(wxEVT_TEXT_ENTER, &ScrolledWidgetsPane::OnUserInput, this); + txt_input.push_back(user_input); + sizer->Add(txt_input[ctrl_cnt], 0, wxALIGN_LEFT|wxLEFT, 10); + + input_info.push_back(new wxStaticText(this, XRCID(id_name4), wxEmptyString)); + sizer->Add(input_info[ctrl_cnt], 0, wxALIGN_LEFT|wxLEFT, 2); ++ctrl_cnt; } - // buttons - wxStaticText* txt_dummy = new wxStaticText(this, wxID_ANY, ""); - sizer->Add(txt_dummy, 0, wxALIGN_LEFT | wxALL, 5); - wxBoxSizer* btnSizer = new wxBoxSizer(wxHORIZONTAL); - wxButton* ok_btn = new wxButton(this, wxID_OK, "OK"); - btnSizer->Add(ok_btn, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL,15); - wxButton* exit_btn = new wxButton(this, wxID_CANCEL, "Cancel"); - btnSizer->Add(exit_btn, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL,15); - sizer->Add(btnSizer, 0, wxALIGN_LEFT | wxALL, 15); - - this->SetSizer(sizer); + wxBoxSizer* sizerAll = new wxBoxSizer(wxVERTICAL); + sizerAll->Add(sizer, 1, wxEXPAND|wxALL, 15); + SetSizer(sizerAll); + SetAutoLayout(true); + sizerAll->Fit(this); + // this part makes the scrollbars show up this->FitInside(); // ask the sizer about the needed size this->SetScrollRate(5, 5); - + + Centre(); } void ScrolledWidgetsPane::Init(vector& merged_field_names, @@ -221,12 +244,12 @@ void ScrolledWidgetsPane::Init(vector& merged_field_names, n_fields = dup_fname.size() + bad_fname.size(); int nrow = n_fields + 2; - int ncol = 3; + int ncol = 4; wxString warn_msg; - wxString DUP_WARN = "Duplicate field name."; - wxString INV_WARN = "Field name is not valid."; + wxString DUP_WARN = _("(Duplicate field name)"); + wxString INV_WARN = _("(Field name is not valid)"); - wxFlexGridSizer* sizer = new wxFlexGridSizer(nrow, ncol, 0, 0); + wxFlexGridSizer* sizer = new wxFlexGridSizer(nrow, ncol, 10, 0); // add a series of widgets num_controls = merged_field_names.size(); @@ -234,15 +257,21 @@ void ScrolledWidgetsPane::Init(vector& merged_field_names, txt_fname.clear(); // ID_FNAME_STAT_TXT_BASE txt_input.clear(); // ID_INPUT_TXT_CTRL_BASE txt_info.clear(); // ID_INFO_STAT_TXT_BASE + input_info.clear(); // titile - wxStaticText* txt_oname=new wxStaticText(this, wxID_ANY, "Field name:"); - sizer->Add(txt_oname, 0, wxALIGN_LEFT|wxALL, 15); - wxStaticText* txt_newname=new wxStaticText(this,wxID_ANY,"New field name:"); - sizer->Add(txt_newname, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL, 15); - wxStaticText* txt_orest=new wxStaticText(this, wxID_ANY, "Field restrictions:"); - sizer->Add(txt_orest, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL, 15); + wxStaticText* txt_oname=new wxStaticText(this, wxID_ANY, "Current field name:"); + sizer->Add(txt_oname, 0, wxALIGN_LEFT); + + wxStaticText* txt_orest=new wxStaticText(this, wxID_ANY, ""); + sizer->Add(txt_orest, 0); + wxStaticText* txt_newname=new wxStaticText(this,wxID_ANY,"Suggested field name:"); + sizer->Add(txt_newname, 0, wxALIGN_LEFT, 15); + + wxStaticText* txt_input_info =new wxStaticText(this, wxID_ANY, wxEmptyString); + sizer->Add(txt_input_info, 0); + size_t ctrl_cnt = 0; for (set::iterator it=dup_fname.begin(); @@ -250,19 +279,27 @@ void ScrolledWidgetsPane::Init(vector& merged_field_names, wxString field_name = *it; warn_msg=DUP_WARN; - wxString id_name1, id_name2, id_name3; + wxString id_name1, id_name2, id_name3, id_name4; id_name1 << "ID_FNAME_STAT_TXT_BASE" << ctrl_cnt; id_name2 << "ID_INPUT_TXT_CTRL_BASE" << ctrl_cnt; id_name3 << "ID_INFO_STAT_TXT_BASE" << ctrl_cnt; + id_name4 << "ID_INPUT_INFO_STAT_TXT_BASE" << ctrl_cnt; wxString user_field_name = GetSuggestFieldName(field_name); txt_fname.push_back(new wxStaticText(this, XRCID(id_name1), field_name)); - sizer->Add(txt_fname[ctrl_cnt], 0, wxALIGN_LEFT|wxALL, 5); - txt_input.push_back(new wxTextCtrl(this, XRCID(id_name2), user_field_name, wxDefaultPosition,wxSize(240,-1))); - sizer->Add(txt_input[ctrl_cnt], 0, wxALIGN_LEFT|wxALL, 5); + sizer->Add(txt_fname[ctrl_cnt], 0, wxALIGN_LEFT|wxALL); + txt_info.push_back(new wxStaticText(this, XRCID(id_name3), warn_msg)); - sizer->Add(txt_info[ctrl_cnt], 0, wxALIGN_LEFT|wxALL, 5); + sizer->Add(txt_info[ctrl_cnt], 0, wxALIGN_LEFT|wxALL); + + wxTextCtrl* user_input = new wxTextCtrl(this, XRCID(id_name2), user_field_name, wxDefaultPosition,wxSize(240,-1),wxTE_PROCESS_ENTER); + user_input->Bind(wxEVT_TEXT_ENTER, &ScrolledWidgetsPane::OnUserInput, this); + txt_input.push_back(user_input); + sizer->Add(txt_input[ctrl_cnt], 0, wxALIGN_LEFT|wxLEFT, 10); + input_info.push_back(new wxStaticText(this, XRCID(id_name4), wxEmptyString)); + sizer->Add(input_info[ctrl_cnt], 0, wxALIGN_LEFT|wxLEFT, 2); + ++ctrl_cnt; } @@ -271,37 +308,41 @@ void ScrolledWidgetsPane::Init(vector& merged_field_names, wxString field_name = *it; warn_msg=INV_WARN; - wxString id_name1, id_name2, id_name3; + wxString id_name1, id_name2, id_name3, id_name4; id_name1 << "ID_FNAME_STAT_TXT_BASE" << ctrl_cnt; id_name2 << "ID_INPUT_TXT_CTRL_BASE" << ctrl_cnt; id_name3 << "ID_INFO_STAT_TXT_BASE" << ctrl_cnt; + id_name4 << "ID_INPUT_INFO_STAT_TXT_BASE" << ctrl_cnt; wxString user_field_name = GetSuggestFieldName(field_name); txt_fname.push_back(new wxStaticText(this, XRCID(id_name1), field_name)); - sizer->Add(txt_fname[ctrl_cnt], 0, wxALIGN_LEFT|wxALL, 5); - txt_input.push_back(new wxTextCtrl(this, XRCID(id_name2), user_field_name, wxDefaultPosition,wxSize(240,-1))); - sizer->Add(txt_input[ctrl_cnt], 0, wxALIGN_LEFT|wxALL, 5); + sizer->Add(txt_fname[ctrl_cnt], 0, wxALIGN_LEFT|wxALL, 0); + txt_info.push_back(new wxStaticText(this, XRCID(id_name3), warn_msg)); - sizer->Add(txt_info[ctrl_cnt], 0, wxALIGN_LEFT|wxALL, 5); + sizer->Add(txt_info[ctrl_cnt], 0, wxALIGN_LEFT|wxALL, 0); + + wxTextCtrl* user_input = new wxTextCtrl(this, XRCID(id_name2), user_field_name, wxDefaultPosition,wxSize(240,-1),wxTE_PROCESS_ENTER); + user_input->Bind(wxEVT_TEXT_ENTER, &ScrolledWidgetsPane::OnUserInput, this); + txt_input.push_back(user_input); + sizer->Add(txt_input[ctrl_cnt], 0, wxALIGN_LEFT|wxLEFT, 10); + + input_info.push_back(new wxStaticText(this, XRCID(id_name4), wxEmptyString)); + sizer->Add(input_info[ctrl_cnt], 0, wxALIGN_LEFT|wxLEFT, 2); ++ctrl_cnt; } - - // buttons - wxStaticText* txt_dummy = new wxStaticText(this, wxID_ANY, ""); - sizer->Add(txt_dummy, 0, wxALIGN_LEFT | wxALL, 5); - wxBoxSizer* btnSizer = new wxBoxSizer(wxHORIZONTAL); - wxButton* ok_btn = new wxButton(this, wxID_OK, "OK"); - btnSizer->Add(ok_btn, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL,15); - wxButton* exit_btn = new wxButton(this, wxID_CANCEL, "Cancel"); - btnSizer->Add(exit_btn, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxALL,15); - sizer->Add(btnSizer, 0, wxALIGN_LEFT | wxALL, 15); - - this->SetSizer(sizer); - // this part makes the scrollbars show up - this->FitInside(); // ask the sizer about the needed size - this->SetScrollRate(5, 5); - + + wxBoxSizer* sizerAll = new wxBoxSizer(wxVERTICAL); + sizerAll->Add(sizer, 1, wxEXPAND|wxALL, 0); + SetSizer(sizerAll); + SetAutoLayout(true); + sizerAll->Fit(this); + + // this part makes the scrollbars show up + this->FitInside(); // ask the sizer about the needed size + this->SetScrollRate(5, 5); + + Centre(); } // give suggested field name based on GdaConst::DataSourceType @@ -321,6 +362,8 @@ wxString ScrolledWidgetsPane::GetSuggestFieldName(int field_idx) // put it to new field name list new_field_names[field_idx] = new_name; + + user_input_dict[old_name] = field_idx; // add any new suggest name to search dict field_dict[new_name] = true; @@ -352,6 +395,8 @@ wxString ScrolledWidgetsPane::GetSuggestFieldName(const wxString& old_name) wxString ScrolledWidgetsPane::TruncateFieldName(const wxString& old_name, int max_len) { + wxLogMessage("ScrolledWidgetsPane::TruncateFieldName"); + wxLogMessage(old_name); if (GdaConst::datasrc_field_lens.find(ds_type) == GdaConst::datasrc_field_lens.end()) { @@ -373,11 +418,14 @@ wxString ScrolledWidgetsPane::TruncateFieldName(const wxString& old_name, new_name << old_name.substr(0, front_chars) << separator << old_name.substr(str_len - back_chars); + wxLogMessage(new_name); return new_name; } wxString ScrolledWidgetsPane::RemoveIllegalChars(const wxString& old_name) { + wxLogMessage("ScrolledWidgetsPane::RemoveIllegalChars"); + wxLogMessage(old_name); if (GdaConst::datasrc_field_illegal_regex.find(ds_type) == GdaConst::datasrc_field_illegal_regex.end()) { @@ -392,12 +440,17 @@ wxString ScrolledWidgetsPane::RemoveIllegalChars(const wxString& old_name) regex.ReplaceAll(&new_name, ""); if (new_name.size()==0) new_name = "NONAME"; + + wxLogMessage(new_name); return new_name; } wxString ScrolledWidgetsPane::RenameDupFieldName(const wxString& old_name) { + wxLogMessage("ScrolledWidgetsPane::RenameDupFieldName"); + wxLogMessage(old_name); + wxString new_name(old_name); while (field_dict.find(new_name) != field_dict.end() || field_dict.find(new_name.Upper()) != field_dict.end() || @@ -426,11 +479,14 @@ wxString ScrolledWidgetsPane::RenameDupFieldName(const wxString& old_name) new_name = first_part + "_" + last_part; } } + wxLogMessage(new_name); return new_name; } bool ScrolledWidgetsPane::IsFieldNameValid(const wxString& col_name) { + wxLogMessage("ScrolledWidgetsPane::IsFieldNameValid"); + wxLogMessage(col_name); if ( GdaConst::datasrc_field_lens.find(ds_type) == GdaConst::datasrc_field_lens.end() ) @@ -459,58 +515,72 @@ bool ScrolledWidgetsPane::IsFieldNameValid(const wxString& col_name) return false; } +void ScrolledWidgetsPane::OnUserInput(wxCommandEvent& ev) +{ + CheckUserInput(); +} + bool ScrolledWidgetsPane::CheckUserInput() { - // check user input + wxString str_dup_field = _("Input is duplicated."); + wxString str_invalid_field = _("Input is not valid."); + + // reset + map current_inputs; for ( size_t i=0, sz=txt_input.size(); iGetValue(); - if ( !IsFieldNameValid(user_field_name) ) { - txt_input[i]->SetForegroundColour(*wxRED); - txt_info[i]->SetLabel("Field name is not valid."); - return false; - } else { - txt_input[i]->SetForegroundColour(*wxBLACK); - wxString orig_fname = txt_fname[i]->GetLabel(); - - if (field_names_dict.find(orig_fname) != field_names_dict.end()) - { - field_names_dict[orig_fname] = user_field_name; - } - } - } else { - txt_input[i]->SetForegroundColour(*wxRED); - txt_info[i]->SetLabel("Field name is not valid."); - return false; - } - } - - // re-check for duplicated names - map uniq_fnames; - - map::iterator iter; - for (iter = field_names_dict.begin(); - iter != field_names_dict.end(); ++iter ) - { - if (uniq_fnames.find(iter->second) == uniq_fnames.end()){ - uniq_fnames[iter->second] = 1; - } else { - uniq_fnames[iter->second] += 1; + txt_input[i]->SetForegroundColour(*wxBLACK); + input_info[i]->SetLabel(wxEmptyString); + wxString user_field_name = txt_input[i]->GetValue(); + user_field_name.Trim(); + current_inputs[user_field_name]++;; } } - if (uniq_fnames.size() != field_names_dict.size()) { - for ( size_t i=0, sz=txt_input.size(); iGetValue(); - if (uniq_fnames[user_field_name] > 1) { + user_field_name.Trim(); + if (current_inputs[user_field_name]>1) { + // re-check if any input itself is duplicated + txt_input[i]->SetForegroundColour(*wxRED); + input_info[i]->SetLabel(str_dup_field); + success = false; + } else if ( !IsFieldNameValid(user_field_name) ) { + // re-check if input is valid txt_input[i]->SetForegroundColour(*wxRED); - txt_info[i]->SetLabel("Duplicate field name."); + input_info[i]->SetLabel(str_invalid_field); + success = false; + } else { + // re-check if any input is duplicated with what's in table + if (field_names_dict.find(user_field_name) != field_names_dict.end()) { + txt_input[i]->SetForegroundColour(*wxRED); + input_info[i]->SetLabel(str_dup_field); + success = false; + } + } + if (success) { + wxString old_name = txt_fname[i]->GetLabel(); + if (field_names_dict.find(old_name) != field_names_dict.end()) { + field_names_dict[old_name] = user_field_name; + if (user_input_dict.find(old_name) != user_input_dict.end() ) { + new_field_names[user_input_dict[old_name]] = user_field_name; + } + } } + } else { + // input is empty + txt_input[i]->SetForegroundColour(*wxRED); + input_info[i]->SetLabel(str_invalid_field); + success = false; } - - return false; + if (!success) _success = success; } - return true; + + return _success; } @@ -534,20 +604,40 @@ FieldNameCorrectionDlg:: FieldNameCorrectionDlg(GdaConst::DataSourceType ds_type, vector& all_fname, wxString title) -: wxDialog(NULL, -1, title, wxDefaultPosition, wxSize(680,300)) +: wxDialog(NULL, -1, title, wxDefaultPosition, wxDefaultSize,wxDEFAULT_DIALOG_STYLE|wxRESIZE_BORDER) { - - + wxPanel *panel = new wxPanel(this); - wxBoxSizer* sizer = new wxBoxSizer(wxHORIZONTAL); - fieldPane = new ScrolledWidgetsPane(this, wxID_ANY, ds_type, all_fname); - need_correction = fieldPane->need_correction; - sizer->Add(fieldPane, 1, wxEXPAND); - //sizer->Fit(this); - this->SetSizer(sizer); - // this part makes the scrollbars show up - //this->FitInside(); - //sizer->SetSizeHints(this); + // panel + wxBoxSizer *vbox = new wxBoxSizer(wxVERTICAL); + fieldPane = new ScrolledWidgetsPane(panel, wxID_ANY, + ds_type, + all_fname); + need_correction = fieldPane->need_correction; + + // buttons + wxButton* ok_btn = new wxButton(panel, wxID_OK, _("OK")); + wxButton* exit_btn = new wxButton(panel, wxID_CANCEL, _("Cancel")); + wxBoxSizer* btnSizer = new wxBoxSizer(wxHORIZONTAL); + btnSizer->Add(ok_btn, 1, wxALIGN_CENTER|wxALL,15); + btnSizer->Add(exit_btn, 1, wxALIGN_CENTER|wxALL,15); + + vbox->Add(fieldPane, 1, wxEXPAND | wxALL, 10); + vbox->Add(btnSizer, 0, wxALIGN_CENTER | wxALL, 10); + + wxBoxSizer *container = new wxBoxSizer(wxHORIZONTAL); + container->Add(vbox,1, wxEXPAND|wxALL, 0); + + panel->SetSizer(container); + + wxBoxSizer* sizerAll = new wxBoxSizer(wxVERTICAL); + sizerAll->Add(panel, 1, wxEXPAND|wxALL, 0); + SetSizer(sizerAll); + SetAutoLayout(true); + sizerAll->Fit(this); + + + Centre(); } FieldNameCorrectionDlg:: @@ -557,29 +647,54 @@ FieldNameCorrectionDlg(GdaConst::DataSourceType ds_type, set& dup_fname, set& bad_fname, wxString title) -: wxDialog(NULL, -1, title, wxDefaultPosition, wxSize(600,300)) +: wxDialog(NULL, -1, title, wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE|wxRESIZE_BORDER) { wxLogMessage("Open FieldNameCorrectionDlg:"); - wxBoxSizer* sizer = new wxBoxSizer(wxHORIZONTAL); - fieldPane = new ScrolledWidgetsPane(this, wxID_ANY, + wxPanel *panel = new wxPanel(this); + + // panel + wxBoxSizer *vbox = new wxBoxSizer(wxVERTICAL); + fieldPane = new ScrolledWidgetsPane(panel, wxID_ANY, ds_type, fnames_dict, merged_field_names, dup_fname, bad_fname); - sizer->Add(fieldPane, 1, wxEXPAND, 120); - SetSizer(sizer); - //sizer->Fit(this); - //sizer->SetSizeHints(this); + + // buttons + wxButton* ok_btn = new wxButton(panel, wxID_OK, _("OK")); + wxButton* exit_btn = new wxButton(panel, wxID_CANCEL, _("Cancel")); + wxBoxSizer* btnSizer = new wxBoxSizer(wxHORIZONTAL); + btnSizer->Add(ok_btn, 1, wxALIGN_CENTER|wxALL,15); + btnSizer->Add(exit_btn, 1, wxALIGN_CENTER|wxALL,15); + + vbox->Add(fieldPane, 1, wxEXPAND | wxALL, 10); + vbox->Add(btnSizer, 0, wxALIGN_CENTER | wxALL, 10); + + wxBoxSizer *container = new wxBoxSizer(wxHORIZONTAL); + container->Add(vbox,1, wxEXPAND|wxALL, 0); + + panel->SetSizer(container); + + wxBoxSizer* sizerAll = new wxBoxSizer(wxVERTICAL); + sizerAll->Add(panel, 1, wxEXPAND|wxALL, 0); + SetSizer(sizerAll); + SetAutoLayout(true); + sizerAll->Fit(this); + + + Centre(); } FieldNameCorrectionDlg::~FieldNameCorrectionDlg() { + wxLogMessage("In FieldNameCorrectionDlg"); if (fieldPane) { delete fieldPane; fieldPane = 0; } + wxLogMessage("Out FieldNameCorrectionDlg"); } diff --git a/DialogTools/FieldNameCorrectionDlg.h b/DialogTools/FieldNameCorrectionDlg.h index 0e49e79de..27479d930 100644 --- a/DialogTools/FieldNameCorrectionDlg.h +++ b/DialogTools/FieldNameCorrectionDlg.h @@ -40,6 +40,8 @@ class ScrolledWidgetsPane : public wxScrolledWindow map field_dict; vector merged_field_names; + map user_input_dict; + vector old_field_names; vector new_field_names; @@ -49,26 +51,27 @@ class ScrolledWidgetsPane : public wxScrolledWindow std::vector txt_fname; // ID_FNAME_STAT_TXT_BASE std::vector txt_input; // ID_INPUT_TXT_CTRL_BASE std::vector txt_info; // ID_INFO_STAT_TXT_BASE + std::vector input_info; // ID_INPUT_INFO_STAT_TXT_BASE wxButton* ok_btn; // wxID_OK wxButton* exit_btn; // wxID_CANCEL bool need_correction; - -public: ScrolledWidgetsPane(wxWindow* parent, wxWindowID id); + ScrolledWidgetsPane(wxWindow* parent, + wxWindowID id, + GdaConst::DataSourceType ds_type, + vector& all_fname); ScrolledWidgetsPane(wxWindow* parent, wxWindowID id, - GdaConst::DataSourceType ds_type, - vector& all_fname); - ScrolledWidgetsPane(wxWindow* parent, wxWindowID id, - GdaConst::DataSourceType ds_type, - map& fnames_dict, - vector& merged_field_names, - set& dup_fname, - set& bad_fname); + GdaConst::DataSourceType ds_type, + map& fnames_dict, + vector& merged_field_names, + set& dup_fname, + set& bad_fname); virtual ~ScrolledWidgetsPane(); - + + void OnUserInput(wxCommandEvent& ev); wxString GetSuggestFieldName(const wxString& old_name); wxString GetSuggestFieldName(int field_idx); wxString RenameDupFieldName(const wxString& old_name); @@ -80,7 +83,9 @@ class ScrolledWidgetsPane : public wxScrolledWindow vector GetNewFieldNames(); void Init(vector& merged_field_names, - set& dup_fname, set& bad_fname); + set& dup_fname, + set& bad_fname); + void Init(vector& dup_fname_idx_s, vector& bad_fname_idx_s); bool CheckUserInput(); @@ -96,14 +101,14 @@ class FieldNameCorrectionDlg: public wxDialog public: FieldNameCorrectionDlg(GdaConst::DataSourceType ds_type, vector& all_fname, - wxString title="Field Name Correction"); + wxString title="Update Field Name"); FieldNameCorrectionDlg(GdaConst::DataSourceType ds_type, map& fnames_dict, vector& merged_field_names, set& dup_fname, set& bad_fname, - wxString title="Field Name Correction"); + wxString title="Update Field Name"); virtual ~FieldNameCorrectionDlg(); bool NeedCorrection() { return need_correction;} @@ -123,4 +128,4 @@ class FieldNameCorrectionDlg: public wxDialog DECLARE_EVENT_TABLE() }; -#endif \ No newline at end of file +#endif diff --git a/DialogTools/FieldNewCalcBinDlg.cpp b/DialogTools/FieldNewCalcBinDlg.cpp index 11ce1da0d..7f214db6b 100644 --- a/DialogTools/FieldNewCalcBinDlg.cpp +++ b/DialogTools/FieldNewCalcBinDlg.cpp @@ -106,7 +106,7 @@ void FieldNewCalcBinDlg::Apply() { if (m_result->GetSelection() == wxNOT_FOUND) { wxString msg("Please choose a result field."); - wxMessageDialog dlg (this, msg, "Error", wxOK | wxICON_ERROR); + wxMessageDialog dlg (this, msg, _("Error"), wxOK | wxICON_ERROR); dlg.ShowModal(); return; } @@ -124,7 +124,7 @@ void FieldNewCalcBinDlg::Apply() || (var2_col == wxNOT_FOUND && !m_valid_const2)) { wxString msg("Operation requires two valid " "variable names or constants."); - wxMessageDialog dlg (this, msg, "Error", wxOK | wxICON_ERROR); + wxMessageDialog dlg (this, msg, _("Error"), wxOK | wxICON_ERROR); dlg.ShowModal(); return; } @@ -137,7 +137,7 @@ void FieldNewCalcBinDlg::Apply() { wxString msg("When \"all times\" selected for either variable, result " "field must also be \"all times.\""); - wxMessageDialog dlg (this, msg, "Error", wxOK | wxICON_ERROR); + wxMessageDialog dlg (this, msg, _("Error"), wxOK | wxICON_ERROR); dlg.ShowModal(); return; } @@ -320,7 +320,9 @@ void FieldNewCalcBinDlg::InitFieldChoices() if (m_var1->GetCount() == prev_cnt) { // only the time field changed if (m_var1_sel != wxNOT_FOUND) { - m_var1->SetSelection(m_var1_sel); + m_var1->SetSelection(m_var1_sel); + m_var1->SetSelection(m_var1_sel); + m_var1->SetValue(m_var1->GetStringSelection()); } else { m_var1->SetValue(var1_val_orig); } @@ -337,7 +339,9 @@ void FieldNewCalcBinDlg::InitFieldChoices() if (m_var2->GetCount() == prev_cnt) { // only the time field changed if (m_var2_sel != wxNOT_FOUND) { - m_var2->SetSelection(m_var2_sel); + m_var2->SetSelection(m_var2_sel); + m_var2->SetSelection(m_var2_sel); + m_var2->SetValue(m_var2->GetStringSelection()); } else { m_var2->SetValue(var2_val_orig); } diff --git a/DialogTools/FieldNewCalcBinDlg.h b/DialogTools/FieldNewCalcBinDlg.h index 968a29eff..f25035bfa 100644 --- a/DialogTools/FieldNewCalcBinDlg.h +++ b/DialogTools/FieldNewCalcBinDlg.h @@ -41,7 +41,7 @@ class FieldNewCalcBinDlg: public wxPanel FieldNewCalcBinDlg(Project* project, wxWindow* parent, wxWindowID id = wxID_ANY, - const wxString& caption = "Bivariate", + const wxString& caption = _("Bivariate"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxTAB_TRAVERSAL ); diff --git a/DialogTools/FieldNewCalcDateTimeDlg.cpp b/DialogTools/FieldNewCalcDateTimeDlg.cpp new file mode 100644 index 000000000..c95a1dcf3 --- /dev/null +++ b/DialogTools/FieldNewCalcDateTimeDlg.cpp @@ -0,0 +1,407 @@ +/** + * GeoDa TM, Copyright (C) 2011-2015 by Luc Anselin - all rights reserved + * + * This file is part of GeoDa. + * + * GeoDa is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * GeoDa is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "../Project.h" +#include "../DataViewer/TableInterface.h" +#include "../DataViewer/TimeState.h" +#include "../DataViewer/DataViewerAddColDlg.h" +#include "../GenUtils.h" +#include "../logger.h" +#include "FieldNewCalcSpecialDlg.h" +#include "FieldNewCalcUniDlg.h" +#include "FieldNewCalcDateTimeDlg.h" +#include "FieldNewCalcBinDlg.h" +#include "FieldNewCalcLagDlg.h" +#include "FieldNewCalcRateDlg.h" + +BEGIN_EVENT_TABLE( FieldNewCalcDateTimeDlg, wxPanel ) + EVT_BUTTON( XRCID("ID_ADD_COLUMN"), FieldNewCalcDateTimeDlg::OnAddColumnClick ) + EVT_CHOICE( XRCID("IDC_DT_RESULT"), + FieldNewCalcDateTimeDlg::OnUnaryResultUpdated ) + EVT_CHOICE( XRCID("IDC_DT_RESULT_TM"), + FieldNewCalcDateTimeDlg::OnUnaryResultTmUpdated ) + EVT_CHOICE( XRCID("IDC_DT_OPERATOR"), + FieldNewCalcDateTimeDlg::OnUnaryOperatorUpdated ) + EVT_TEXT( XRCID("IDC_DT_OPERAND"), + FieldNewCalcDateTimeDlg::OnUnaryOperandUpdated ) + EVT_COMBOBOX( XRCID("IDC_DT_OPERAND"), + FieldNewCalcDateTimeDlg::OnUnaryOperandUpdated ) + EVT_CHOICE( XRCID("IDC_DT_OPERAND_TM"), + FieldNewCalcDateTimeDlg::OnUnaryOperandTmUpdated ) +END_EVENT_TABLE() + +FieldNewCalcDateTimeDlg::FieldNewCalcDateTimeDlg(Project* project_s, + wxWindow* parent, + wxWindowID id, const wxString& caption, + const wxPoint& pos, const wxSize& size, + long style ) +: all_init(false), op_string(6), project(project_s), +table_int(project_s->GetTableInt()), +m_valid_const(false), m_const(1), m_var_sel(wxNOT_FOUND), +is_space_time(project_s->GetTableInt()->IsTimeVariant()) +{ + SetParent(parent); + CreateControls(); + Centre(); + + op_string[get_year_op] = "Get Year"; + op_string[get_month_op] = "Get Month"; + op_string[get_day_op] = "Get Day"; + op_string[get_hour_op] = "Get Hour"; + op_string[get_minute_op] = "Get Minute"; + op_string[get_second_op] = "Get Second"; + + for (int i=0, iend=op_string.size(); iAppend(op_string[i]); + } + m_op->SetSelection(0); + + InitFieldChoices(); + all_init = true; +} + +void FieldNewCalcDateTimeDlg::CreateControls() +{ + wxXmlResource::Get()->LoadPanel(this, GetParent(), "IDD_FIELDCALC_DT"); + m_result = XRCCTRL(*this, "IDC_DT_RESULT", wxChoice); + m_result_tm = XRCCTRL(*this, "IDC_DT_RESULT_TM", wxChoice); + InitTime(m_result_tm); + m_op = XRCCTRL(*this, "IDC_DT_OPERATOR", wxChoice); + m_var = XRCCTRL(*this, "IDC_DT_OPERAND", wxComboBox); + m_var_tm = XRCCTRL(*this, "IDC_DT_OPERAND_TM", wxChoice); + InitTime(m_var_tm); +} + +void FieldNewCalcDateTimeDlg::Apply() +{ + if (m_result->GetSelection() == wxNOT_FOUND) { + wxString msg = _("Please choose a Result field."); + wxMessageDialog dlg (this, msg, _("Error"), wxOK | wxICON_ERROR); + dlg.ShowModal(); + return; + } + int result_col = col_id_map[m_result->GetSelection()]; + + int var_col = wxNOT_FOUND; + if (m_var_sel != wxNOT_FOUND) { + var_col = dt_col_id_map[m_var_sel]; + } + if (var_col == wxNOT_FOUND && !m_valid_const) { + wxString msg = _("Operation requires a valid field name or constant."); + wxMessageDialog dlg (this, msg, _("Error"), wxOK | wxICON_ERROR); + dlg.ShowModal(); + return; + } + + if (is_space_time && var_col != wxNOT_FOUND && + !IsAllTime(result_col, m_result_tm->GetSelection()) && + IsAllTime(var_col, m_var_tm->GetSelection())) { + wxString msg = _("When \"all times\" selected for variable, result " + "field must also be \"all times.\""); + wxMessageDialog dlg (this, msg, _("Error"), wxOK | wxICON_ERROR); + dlg.ShowModal(); + return; + } + + TableState* ts = project->GetTableState(); + wxString grp_nm = table_int->GetColName(result_col); + if (!Project::CanModifyGrpAndShowMsgIfNot(ts, grp_nm)) return; + + + std::vector time_list; + if (IsAllTime(result_col, m_result_tm->GetSelection())) { + int ts = project->GetTableInt()->GetTimeSteps(); + time_list.resize(ts); + for (int i=0; iGetSelection() : 0; + time_list.resize(1); + time_list[0] = tm; + } + + int rows = table_int->GetNumberRows(); + std::vector data(rows, 0); // date/time + std::vector undefined(rows, false); + + if (var_col != wxNOT_FOUND && + !IsAllTime(var_col, m_var_tm->GetSelection())) + { + int tm = IsTimeVariant(var_col) ? m_var_tm->GetSelection() : 0; + table_int->GetColData(var_col,tm, data); + table_int->GetColUndefined(var_col, tm, undefined); + } else { + for (int i=0; i r_data(rows, 0); + std::vector r_undefined(rows, false); + + for (int t=0; tGetSelection())) + { + table_int->GetColData(var_col, time_list[t], data); + table_int->GetColUndefined(var_col, time_list[t], undefined); + } + for (int i=0; iGetSelection()) { + case get_year_op: + { + for (int i=0; iSetColData(result_col, time_list[t], r_data); + table_int->SetColUndefined(result_col, time_list[t], r_undefined); + + } +} + +void FieldNewCalcDateTimeDlg::InitFieldChoices() +{ + table_int->FillNumericColIdMap(col_id_map); + table_int->FillDateTimeColIdMap(dt_col_id_map); + + // integer/double fields + wxString var_val_orig = m_var->GetValue(); + int sel_temp = m_var_sel; + m_var->Clear(); + m_var_sel = sel_temp; + m_var_str.resize(dt_col_id_map.size()); + wxString v_tm; + if (is_space_time) { + v_tm << " (" << m_var_tm->GetStringSelection() << ")"; + } + for (int i=0, iend=dt_col_id_map.size(); iGetColTimeSteps(dt_col_id_map[i]) > 1) { + m_var->Append(table_int->GetColName(dt_col_id_map[i]) + v_tm); + m_var_str[i] = table_int->GetColName(dt_col_id_map[i]) + v_tm; + } else { + m_var->Append(table_int->GetColName(dt_col_id_map[i])); + m_var_str[i] = table_int->GetColName(dt_col_id_map[i]); + } + } + + // date/time fields + wxString r_str_sel = m_result->GetStringSelection(); + int r_sel = m_result->GetSelection(); + int prev_cnt = m_result->GetCount(); + m_result->Clear(); + wxString r_tm; + if (is_space_time) { + r_tm << " (" << m_result_tm->GetStringSelection() << ")"; + } + for (int i=0, iend=col_id_map.size(); iGetColTimeSteps(col_id_map[i]) > 1) { + m_result->Append(table_int->GetColName(col_id_map[i]) + r_tm); + } else { + m_result->Append(table_int->GetColName(col_id_map[i])); + } + } + if (m_result->GetCount() == prev_cnt) { + // only the time field changed + m_result->SetSelection(r_sel); + } else { + // a new variable might have been added, so find old string + m_result->SetSelection(m_result->FindString(r_str_sel)); + } + + if (m_var->GetCount() == prev_cnt) { + // only the time field changed + if (m_var_sel != wxNOT_FOUND) { + m_var->SetSelection(m_var_sel); + } else { + m_var->SetValue(var_val_orig); + } + } else { + // a new variable might have been added, so find old string + if (m_var_sel != wxNOT_FOUND) { + m_var->SetSelection(m_var->FindString(var_val_orig)); + m_var_sel = m_var->GetSelection(); + } else { + m_var->SetValue(var_val_orig); + } + } + + Display(); +} + +void FieldNewCalcDateTimeDlg::UpdateOtherPanels() +{ + s_panel->InitFieldChoices(); + b_panel->InitFieldChoices(); + l_panel->InitFieldChoices(); + r_panel->InitFieldChoices(); +} + +void FieldNewCalcDateTimeDlg::Display() +{ +} + +bool FieldNewCalcDateTimeDlg::IsTimeVariant(int col_id) +{ + if (!is_space_time) return false; + return (table_int->IsColTimeVariant(col_id)); +} + +bool FieldNewCalcDateTimeDlg::IsAllTime(int col_id, int tm_sel) +{ + if (!is_space_time) return false; + if (!table_int->IsColTimeVariant(col_id)) return false; + return tm_sel == project->GetTableInt()->GetTimeSteps(); +} + +void FieldNewCalcDateTimeDlg::OnUnaryResultUpdated( wxCommandEvent& event ) +{ + int sel = m_result->GetSelection(); + m_result_tm->Enable(sel != wxNOT_FOUND && + IsTimeVariant(col_id_map[sel])); + Display(); +} + +void FieldNewCalcDateTimeDlg::OnUnaryResultTmUpdated( wxCommandEvent& event ) +{ + InitFieldChoices(); + Display(); +} + +void FieldNewCalcDateTimeDlg::OnUnaryOperatorUpdated( wxCommandEvent& event ) +{ + Display(); +} + +void FieldNewCalcDateTimeDlg::OnUnaryOperandUpdated( wxCommandEvent& event ) +{ + if (!all_init) return; + + wxString var_val = m_var->GetValue(); + var_val.Trim(false); + var_val.Trim(true); + if (m_var->GetValue() != m_var->GetStringSelection()) { + // User has typed something in manually. + // if value matches some item on list, then set list to that + // otherwise, set selection back to wxNOT_FOUND + m_var_sel = wxNOT_FOUND; + for (int i=0, i_end=m_var_str.size(); m_var_sel==-1 && iSetSelection(m_var_sel); + } else { + m_valid_const = var_val.ToDouble(&m_const); + } + } else { + m_var_sel = m_var->GetSelection(); + } + m_var_tm->Enable(m_var_sel != wxNOT_FOUND && + table_int->GetColTimeSteps(col_id_map[m_var_sel]) > 1); + Display(); +} + +void FieldNewCalcDateTimeDlg::OnUnaryOperandTmUpdated( wxCommandEvent& event ) +{ + InitFieldChoices(); + Display(); +} + +void FieldNewCalcDateTimeDlg::OnAddColumnClick( wxCommandEvent& event ) +{ + DataViewerAddColDlg dlg(project, this); + if (dlg.ShowModal() != wxID_OK) return; + InitFieldChoices(); + wxString sel_str = dlg.GetColName(); + if (table_int->GetColTimeSteps(dlg.GetColId()) > 1) { + sel_str << " (" << m_result_tm->GetStringSelection() << ")"; + } + m_result->SetSelection(m_result->FindString(sel_str)); + OnUnaryResultUpdated(event); + UpdateOtherPanels(); +} + +void FieldNewCalcDateTimeDlg::InitTime(wxChoice* time_list) +{ + time_list->Clear(); + for (int i=0; iGetTableInt()->GetTimeSteps(); i++) { + wxString t; + t << project->GetTableInt()->GetTimeString(i); + time_list->Append(t); + } + time_list->Append("all times"); + time_list->SetSelection(project->GetTableInt()->GetTimeSteps()); + time_list->Disable(); + time_list->Show(is_space_time); +} diff --git a/DialogTools/FieldNewCalcDateTimeDlg.h b/DialogTools/FieldNewCalcDateTimeDlg.h new file mode 100644 index 000000000..9acb1307b --- /dev/null +++ b/DialogTools/FieldNewCalcDateTimeDlg.h @@ -0,0 +1,113 @@ +/** + * GeoDa TM, Copyright (C) 2011-2015 by Luc Anselin - all rights reserved + * + * This file is part of GeoDa. + * + * GeoDa is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * GeoDa is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#ifndef __GEODA_CENTER_FIELD_NEW_CALC_DT_DLG_H__ +#define __GEODA_CENTER_FIELD_NEW_CALC_DT_DLG_H__ + +#include +#include +#include +#include +#include + +class Project; +class TableInterface; +class FieldNewCalcSpecialDlg; +class FieldNewCalcBinDlg; +class FieldNewCalcLagDlg; +class FieldNewCalcRateDlg; + +class FieldNewCalcDateTimeDlg: public wxPanel +{ + DECLARE_EVENT_TABLE() + +public: + FieldNewCalcDateTimeDlg(Project* project, + wxWindow* parent, + wxWindowID id = wxID_ANY, + const wxString& caption = _("Date/Time"), + const wxPoint& pos = wxDefaultPosition, + const wxSize& size = wxDefaultSize, + long style = wxTAB_TRAVERSAL ); + + void CreateControls(); + + void OnAddColumnClick( wxCommandEvent& event ); + void OnUnaryResultUpdated( wxCommandEvent& event ); + void OnUnaryResultTmUpdated( wxCommandEvent& event ); + void OnUnaryOperatorUpdated( wxCommandEvent& event ); + void OnUnaryOperandUpdated( wxCommandEvent& event ); + void OnUnaryOperandTmUpdated( wxCommandEvent& event ); + + void UpdateOtherPanels(); + void SetOtherPanelPointers(FieldNewCalcSpecialDlg* s_panel_s, + FieldNewCalcBinDlg* b_panel_s, + FieldNewCalcLagDlg* l_panel_s, + FieldNewCalcRateDlg* r_panel_s) + { + s_panel=s_panel_s; b_panel=b_panel_s; + l_panel = l_panel_s; r_panel=r_panel_s; + } + FieldNewCalcSpecialDlg* s_panel; + FieldNewCalcBinDlg* b_panel; + FieldNewCalcLagDlg* l_panel; + FieldNewCalcRateDlg* r_panel; + + bool IsTimeVariant(int col_id); + bool IsAllTime(int col_id, int tm_sel); + + bool all_init; + bool is_space_time; + std::vector m_var_str; + wxChoice* m_result; + wxChoice* m_result_tm; + wxChoice* m_op; + wxComboBox* m_var; + wxChoice* m_var_tm; + double m_const; + bool m_valid_const; + int m_var_sel; + + Project* project; + TableInterface* table_int; + // col_id_map[i] is a map from the i'th numeric item in the + // fields drop-down to the actual col_id_map. Items + // in the fields dropdown are in the order displayed + // in wxGrid + std::vector col_id_map; + + std::vector dt_col_id_map; + + void Apply(); + void InitFieldChoices(); + void InitTime(wxChoice* time_list); + void Display(); + + enum OpType { + get_year_op = 0, + get_month_op = 1, + get_day_op = 2, + get_hour_op = 3, + get_minute_op = 4, + get_second_op = 5 + }; + std::vector op_string; +}; + +#endif diff --git a/DialogTools/FieldNewCalcLagDlg.cpp b/DialogTools/FieldNewCalcLagDlg.cpp index b3740d9fb..ff22c759d 100644 --- a/DialogTools/FieldNewCalcLagDlg.cpp +++ b/DialogTools/FieldNewCalcLagDlg.cpp @@ -47,8 +47,9 @@ BEGIN_EVENT_TABLE( FieldNewCalcLagDlg, wxPanel ) EVT_CHOICE( XRCID("IDC_LAG_OPERAND"), FieldNewCalcLagDlg::OnLagOperandUpdated ) EVT_CHOICE( XRCID("IDC_LAG_OPERAND_TM"), - FieldNewCalcLagDlg::OnLagOperandTmUpdated ) - EVT_BUTTON( XRCID("ID_OPEN_WEIGHT"), FieldNewCalcLagDlg::OnOpenWeightClick ) + FieldNewCalcLagDlg::OnLagOperandTmUpdated ) + + EVT_BUTTON( XRCID("ID_OPEN_WEIGHT"), FieldNewCalcLagDlg::OnOpenWeightClick ) END_EVENT_TABLE() FieldNewCalcLagDlg::FieldNewCalcLagDlg(Project* project_s, @@ -84,27 +85,32 @@ void FieldNewCalcLagDlg::CreateControls() InitTime(m_var_tm); m_text = XRCCTRL(*this, "IDC_EDIT6", wxTextCtrl); m_text->SetMaxLength(0); + + // ID_LAG_USE_ROWSTAND_W ID_LAG_INCLUDE_DIAGNOAL_W + m_row_stand = XRCCTRL(*this, "ID_LAG_USE_ROWSTAND_W", wxCheckBox); + m_self_neighbor = XRCCTRL(*this, "ID_LAG_INCLUDE_DIAGNOAL_W", wxCheckBox); + } void FieldNewCalcLagDlg::Apply() { if (m_result->GetSelection() == wxNOT_FOUND) { - wxString msg("Please select a results field."); - wxMessageDialog dlg (this, msg, "Error", wxOK | wxICON_ERROR); + wxString msg = _("Please select a results field."); + wxMessageDialog dlg (this, msg, _("Error"), wxOK | wxICON_ERROR); dlg.ShowModal(); return; } if (GetWeightsId().is_nil()) { - wxString msg("Please specify a Weights matrix."); - wxMessageDialog dlg (this, msg, "Error", wxOK | wxICON_ERROR); + wxString msg = _("Please specify a Weights matrix."); + wxMessageDialog dlg (this, msg, _("Error"), wxOK | wxICON_ERROR); dlg.ShowModal(); return; } if (m_var->GetSelection() == wxNOT_FOUND) { - wxString msg("Please select an Variable field."); - wxMessageDialog dlg (this, msg, "Error", wxOK | wxICON_ERROR); + wxString msg = _("Please select an Variable field."); + wxMessageDialog dlg (this, msg, _("Error"), wxOK | wxICON_ERROR); dlg.ShowModal(); return; } @@ -119,9 +125,9 @@ void FieldNewCalcLagDlg::Apply() if (is_space_time && !IsAllTime(result_col, m_result_tm->GetSelection()) && IsAllTime(var_col, m_var_tm->GetSelection())) { - wxString msg("When \"all times\" selected for variable, result " + wxString msg = _("When \"all times\" selected for variable, result " "field must also be \"all times.\""); - wxMessageDialog dlg (this, msg, "Error", wxOK | wxICON_ERROR); + wxMessageDialog dlg (this, msg, _("Error"), wxOK | wxICON_ERROR); dlg.ShowModal(); return; } @@ -155,13 +161,15 @@ void FieldNewCalcLagDlg::Apply() GalWeight* gw = w_man_int->GetGal(id); W = gw ? gw->gal : NULL; if (W == NULL) { - wxString msg("Was not able to load weights matrix."); - wxMessageDialog dlg (this, msg, "Error", wxOK | wxICON_ERROR); + wxString msg = _("Was not able to load weights matrix."); + wxMessageDialog dlg (this, msg, _("Error"), wxOK | wxICON_ERROR); dlg.ShowModal(); return; } } - + + bool not_binary_w = w_man_int->IsBinaryWeights(id); + for (int t=0; tGetColData(var_col, time_list[t], data); table_int->GetColUndefined(var_col, time_list[t], undefined); } - // Row-standardized lag calculation. + for (int i=0, iend=table_int->GetNumberRows(); i & w_values = W[i].GetNbrWeights(); + + int self_idx = -1; for (int j=0, sz=W[i].Size(); jIsChecked() ) { + lag += data[i]; + nn += 1; + } + if (m_row_stand->IsChecked()) { + lag = nn > 0 ? lag / nn : 0; + } + + } else { + // inverse or kernel weights + if (m_row_stand->IsChecked()) { + lag = nn > 0 ? lag / nn : 0; + } + if (m_self_neighbor->IsChecked() ) { + if (self_idx > 0) { + // only case: kernel weights with diagonal + lag += data[i] * w_values[self_idx]; + } else { + lag += data[i]; + } + } + } + + r_data[i] = lag; + } } table_int->SetColData(result_col, time_list[t], r_data); table_int->SetColUndefined(result_col, time_list[t], r_undefined); @@ -303,7 +354,8 @@ void FieldNewCalcLagDlg::InitWeightsList() for (long i=0; iSetSelection(i); } - } + } + SetupRowstandControls(); } /** Returns weights selection or nil if none selected */ @@ -315,6 +367,31 @@ boost::uuids::uuid FieldNewCalcLagDlg::GetWeightsId() } return w_ids[sel]; } + +void FieldNewCalcLagDlg::SetupRowstandControls() +{ + long sel = m_weights->GetSelection(); + if (sel >= 0) { + bool flag = true; + m_row_stand->SetValue(true); + m_self_neighbor->SetValue(false); + + boost::uuids::uuid id = GetWeightsId(); + WeightsMetaInfo::WeightTypeEnum type = w_man_int->GetWeightsType(id); + if (type == WeightsMetaInfo::WT_kernel) { + m_row_stand->SetValue(false); + m_self_neighbor->SetValue(true); + flag = false; + } else if (type == WeightsMetaInfo::WT_knn || type == WeightsMetaInfo::WT_threshold) { + if (w_man_int->IsBinaryWeights(id)) { + m_row_stand->SetValue(false); + m_self_neighbor->SetValue(false); + } + } + m_row_stand->Enable(flag); + m_self_neighbor->Enable(flag); + } +} void FieldNewCalcLagDlg::OnLagResultUpdated( wxCommandEvent& event ) { @@ -332,7 +409,8 @@ void FieldNewCalcLagDlg::OnLagResultTmUpdated( wxCommandEvent& event ) void FieldNewCalcLagDlg::OnCurrentusedWUpdated( wxCommandEvent& event ) { - Display(); + Display(); + SetupRowstandControls(); } void FieldNewCalcLagDlg::OnLagOperandUpdated( wxCommandEvent& event ) diff --git a/DialogTools/FieldNewCalcLagDlg.h b/DialogTools/FieldNewCalcLagDlg.h index 4e784d015..92663ca29 100644 --- a/DialogTools/FieldNewCalcLagDlg.h +++ b/DialogTools/FieldNewCalcLagDlg.h @@ -22,7 +22,7 @@ #include #include -#include +#include class Project; class TableInterface; @@ -39,7 +39,7 @@ class FieldNewCalcLagDlg: public wxPanel FieldNewCalcLagDlg(Project* project, wxWindow* parent, wxWindowID id = wxID_ANY, - const wxString& caption = "Spatial Lag", + const wxString& caption = _("Spatial Lag"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxTAB_TRAVERSAL ); @@ -53,14 +53,16 @@ class FieldNewCalcLagDlg: public wxPanel void OnLagOperandUpdated( wxCommandEvent& event ); void OnLagOperandTmUpdated( wxCommandEvent& event ); void OnOpenWeightClick( wxCommandEvent& event ); - + void UpdateOtherPanels(); void SetOtherPanelPointers(FieldNewCalcSpecialDlg* s_panel_s, FieldNewCalcUniDlg* u_panel_s, FieldNewCalcBinDlg* b_panel_s, - FieldNewCalcRateDlg* r_panel_s) { + FieldNewCalcRateDlg* r_panel_s) + { s_panel=s_panel_s; u_panel=u_panel_s; - b_panel=b_panel_s; r_panel=r_panel_s; } + b_panel=b_panel_s; r_panel=r_panel_s; + } FieldNewCalcSpecialDlg* s_panel; FieldNewCalcUniDlg* u_panel; FieldNewCalcBinDlg* b_panel; @@ -75,11 +77,15 @@ class FieldNewCalcLagDlg: public wxPanel bool is_space_time; wxChoice* m_result; wxChoice* m_result_tm; - wxChoice* m_weights; + wxChoice* m_weights; std::vector w_ids; wxChoice* m_var; wxChoice* m_var_tm; wxTextCtrl* m_text; + wxCheckBox* m_row_stand; + wxCheckBox* m_self_neighbor; + + Project* project; WeightsManInterface* w_man_int; TableInterface* table_int; @@ -92,7 +98,7 @@ class FieldNewCalcLagDlg: public wxPanel void Apply(); void InitFieldChoices(); void InitTime(wxChoice* time_list); - + void SetupRowstandControls(); void Display(); }; diff --git a/DialogTools/FieldNewCalcRateDlg.cpp b/DialogTools/FieldNewCalcRateDlg.cpp index f3a02f643..ad178d8ad 100644 --- a/DialogTools/FieldNewCalcRateDlg.cpp +++ b/DialogTools/FieldNewCalcRateDlg.cpp @@ -29,7 +29,6 @@ #include "../DataViewer/TableInterface.h" #include "../DataViewer/TimeState.h" #include "../DataViewer/DataViewerAddColDlg.h" -#include "ExportDataDlg.h" #include "FieldNewCalcSpecialDlg.h" #include "FieldNewCalcUniDlg.h" #include "FieldNewCalcBinDlg.h" @@ -111,31 +110,31 @@ void FieldNewCalcRateDlg::SaveValidSubsetAs() void FieldNewCalcRateDlg::Apply() { if (m_result->GetSelection() == wxNOT_FOUND) { - wxString msg("Please select a results field."); - wxMessageDialog dlg (this, msg, "Error", wxOK | wxICON_ERROR); + wxString msg = _("Please select a results field."); + wxMessageDialog dlg (this, msg, _("Error"), wxOK | wxICON_ERROR); dlg.ShowModal(); return; } const int op = m_method->GetSelection(); if ((op == 3 || op == 4) && GetWeightsId().is_nil()) { - wxString msg("Weight matrix required for chosen spatial " + wxString msg = _("Weight matrix required for chosen spatial " "rate method."); - wxMessageDialog dlg (this, msg, "Error", wxOK | wxICON_ERROR); + wxMessageDialog dlg (this, msg, _("Error"), wxOK | wxICON_ERROR); dlg.ShowModal(); return; } if (m_event->GetSelection() == wxNOT_FOUND) { - wxString msg("Please select an Event field."); - wxMessageDialog dlg (this, msg, "Error", wxOK | wxICON_ERROR); + wxString msg = _("Please select an Event field."); + wxMessageDialog dlg (this, msg, _("Error"), wxOK | wxICON_ERROR); dlg.ShowModal(); return; } if (m_base->GetSelection() == wxNOT_FOUND) { - wxString msg("Please select an Base field."); - wxMessageDialog dlg (this, msg, "Error", wxOK | wxICON_ERROR); + wxString msg = _("Please select an Base field."); + wxMessageDialog dlg (this, msg, _("Error"), wxOK | wxICON_ERROR); dlg.ShowModal(); return; } @@ -152,9 +151,8 @@ void FieldNewCalcRateDlg::Apply() (IsAllTime(cop1, m_event_tm->GetSelection()) || IsAllTime(cop2, m_base_tm->GetSelection()))) { - wxString msg("When \"all times\" selected for either variable, result " - "field must also be \"all times.\""); - wxMessageDialog dlg (this, msg, "Error", wxOK | wxICON_ERROR); + wxString msg = _("When \"all times\" selected for either variable, result field must also be \"all times.\""); + wxMessageDialog dlg (this, msg, _("Error"), wxOK | wxICON_ERROR); dlg.ShowModal(); return; } @@ -162,8 +160,8 @@ void FieldNewCalcRateDlg::Apply() boost::uuids::uuid weights_id = GetWeightsId(); if (op == 3 || op == 4) { if (!w_man_int->IsValid(weights_id)) { - wxString msg("Was not able to load weights matrix."); - wxMessageDialog dlg (this, msg, "Error", wxOK | wxICON_ERROR); + wxString msg= _("Was not able to load weights matrix."); + wxMessageDialog dlg (this, msg, _("Error"), wxOK | wxICON_ERROR); dlg.ShowModal(); return; } @@ -276,16 +274,13 @@ void FieldNewCalcRateDlg::Apply() if (r) delete [] r; r = NULL; if (has_undefined) { - wxString msg("Some calculated values were undefined and this is " - "most likely due to neighborless observations in the " - "weight matrix. Rate calculation successful for " - "observations with neighbors."); - wxMessageDialog dlg (this, msg, "Success / Warning", + wxString msg = _("Some calculated values were undefined and this is most likely due to neighborless observations in the weight matrix. Rate calculation successful for observations with neighbors."); + wxMessageDialog dlg (this, msg, _("Success / Warning"), wxOK | wxICON_INFORMATION); dlg.ShowModal(); } else { - wxString msg("Rate calculation successful."); - wxMessageDialog dlg (this, msg, "Success", wxOK | wxICON_INFORMATION); + wxString msg = _("Rate calculation successful."); + wxMessageDialog dlg (this, msg, _("Success"), wxOK | wxICON_INFORMATION); dlg.ShowModal(); } } diff --git a/DialogTools/FieldNewCalcRateDlg.h b/DialogTools/FieldNewCalcRateDlg.h index 66d8c1c2e..5c9611328 100644 --- a/DialogTools/FieldNewCalcRateDlg.h +++ b/DialogTools/FieldNewCalcRateDlg.h @@ -40,7 +40,7 @@ class FieldNewCalcRateDlg: public wxPanel FieldNewCalcRateDlg(Project* project, wxWindow* parent, wxWindowID id = wxID_ANY, - const wxString& caption = "Rates", + const wxString& caption = _("Rates"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxTAB_TRAVERSAL ); diff --git a/DialogTools/FieldNewCalcSheetDlg.cpp b/DialogTools/FieldNewCalcSheetDlg.cpp index cbe9c951f..2d2ac4b51 100644 --- a/DialogTools/FieldNewCalcSheetDlg.cpp +++ b/DialogTools/FieldNewCalcSheetDlg.cpp @@ -56,17 +56,20 @@ w_man_state(project_s->GetWManState()) pBin = new FieldNewCalcBinDlg(project, m_note); pLag = new FieldNewCalcLagDlg(project, m_note); pRate = new FieldNewCalcRateDlg(project, m_note); + pDT = new FieldNewCalcDateTimeDlg(project, m_note); pSpecial->SetOtherPanelPointers(pUni, pBin, pLag, pRate); pUni->SetOtherPanelPointers(pSpecial, pBin, pLag, pRate); pBin->SetOtherPanelPointers(pSpecial, pUni, pLag, pRate); pLag->SetOtherPanelPointers(pSpecial, pUni, pBin, pRate); pRate->SetOtherPanelPointers(pSpecial, pUni, pBin, pLag); + pDT->SetOtherPanelPointers(pSpecial, pBin, pLag, pRate); m_note->AddPage(pSpecial, "Special"); m_note->AddPage(pUni, "Univariate"); m_note->AddPage(pBin, "Bivariate"); m_note->AddPage(pLag, "Spatial Lag"); m_note->AddPage(pRate, "Rates"); + m_note->AddPage(pDT, "Date/Time"); pLag->InitWeightsList(); pRate->InitWeightsList(); this->SetSize(-1,-1,-1,-1); @@ -99,7 +102,7 @@ void FieldNewCalcSheetDlg::CreateControls() { wxXmlResource::Get()->LoadDialog(this, GetParent(), "IDD_FIELDCALC_SHEET"); m_note = XRCCTRL(*this, "ID_NOTEBOOK", wxNotebook); -} +} void FieldNewCalcSheetDlg::OnPageChange( wxBookCtrlEvent& event ) { @@ -116,14 +119,28 @@ void FieldNewCalcSheetDlg::OnPageChange( wxBookCtrlEvent& event ) var_sel_idx = pLag->m_result->GetCurrentSelection(); else if (tab_idx == 4) var_sel_idx = pRate->m_result->GetCurrentSelection(); + else if (tab_idx == 5) + var_sel_idx = pDT->m_result->GetCurrentSelection(); - { - pSpecial->m_result->SetSelection(var_sel_idx); - pUni->m_result->SetSelection(var_sel_idx); - pBin->m_result->SetSelection(var_sel_idx); - pLag->m_result->SetSelection(var_sel_idx); - pRate->m_result->SetSelection(var_sel_idx); + { + /* + pSpecial->m_result->SetSelection(var_sel_idx); + pSpecial->InitFieldChoices(); + pUni->m_result->SetSelection(var_sel_idx); + pUni->InitFieldChoices(); + pBin->m_result->SetSelection(var_sel_idx); + pBin->InitFieldChoices(); + pLag->m_result->SetSelection(var_sel_idx); + pLag->InitFieldChoices(); + pRate->m_result->SetSelection(var_sel_idx); + pRate->InitFieldChoices(); + pDT->m_result->SetSelection(var_sel_idx); + pDT->InitFieldChoices(); + */ } + wxString msg; + msg << "page idx: " << var_sel_idx; + wxLogMessage(msg); } void FieldNewCalcSheetDlg::OnApplyClick( wxCommandEvent& event ) @@ -137,6 +154,7 @@ void FieldNewCalcSheetDlg::OnApplyClick( wxCommandEvent& event ) pBin->InitFieldChoices(); pLag->InitFieldChoices(); pRate->InitFieldChoices(); + pDT->InitFieldChoices(); break; case 1: pUni->Apply(); @@ -144,6 +162,7 @@ void FieldNewCalcSheetDlg::OnApplyClick( wxCommandEvent& event ) pBin->InitFieldChoices(); pLag->InitFieldChoices(); pRate->InitFieldChoices(); + pDT->InitFieldChoices(); break; case 2: pBin->Apply(); @@ -151,6 +170,7 @@ void FieldNewCalcSheetDlg::OnApplyClick( wxCommandEvent& event ) pUni->InitFieldChoices(); pLag->InitFieldChoices(); pRate->InitFieldChoices(); + pDT->InitFieldChoices(); break; case 3: pLag->Apply(); @@ -158,6 +178,7 @@ void FieldNewCalcSheetDlg::OnApplyClick( wxCommandEvent& event ) pUni->InitFieldChoices(); pBin->InitFieldChoices(); pRate->InitFieldChoices(); + pDT->InitFieldChoices(); break; case 4: pRate->Apply(); @@ -165,6 +186,15 @@ void FieldNewCalcSheetDlg::OnApplyClick( wxCommandEvent& event ) pUni->InitFieldChoices(); pBin->InitFieldChoices(); pLag->InitFieldChoices(); + pDT->InitFieldChoices(); + break; + case 5: + pDT->Apply(); + pSpecial->InitFieldChoices(); + pUni->InitFieldChoices(); + pBin->InitFieldChoices(); + pLag->InitFieldChoices(); + pRate->InitFieldChoices(); break; default: pSpecial->InitFieldChoices(); @@ -194,6 +224,7 @@ void FieldNewCalcSheetDlg::update(TableState* o) pBin->InitFieldChoices(); pLag->InitFieldChoices(); pRate->InitFieldChoices(); + pDT->InitFieldChoices(); } void FieldNewCalcSheetDlg::update(WeightsManState* o) diff --git a/DialogTools/FieldNewCalcSheetDlg.h b/DialogTools/FieldNewCalcSheetDlg.h index 8714296bd..2de4169eb 100644 --- a/DialogTools/FieldNewCalcSheetDlg.h +++ b/DialogTools/FieldNewCalcSheetDlg.h @@ -24,6 +24,7 @@ #include #include "FieldNewCalcSpecialDlg.h" #include "FieldNewCalcBinDlg.h" +#include "FieldNewCalcDateTimeDlg.h" #include "FieldNewCalcLagDlg.h" #include "FieldNewCalcRateDlg.h" #include "FieldNewCalcUniDlg.h" @@ -51,7 +52,7 @@ class FieldNewCalcSheetDlg: public wxDialog, public FramesManagerObserver, virtual ~FieldNewCalcSheetDlg(); bool Create( wxWindow* parent, wxWindowID id = -1, - const wxString& caption = "Var Calc Container", + const wxString& caption = _("Var Calc Container"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxDEFAULT_DIALOG_STYLE ); @@ -84,6 +85,7 @@ class FieldNewCalcSheetDlg: public wxDialog, public FramesManagerObserver, FieldNewCalcLagDlg* pLag; FieldNewCalcRateDlg* pRate; FieldNewCalcUniDlg* pUni; + FieldNewCalcDateTimeDlg* pDT; FramesManager* frames_manager; TableState* table_state; diff --git a/DialogTools/FieldNewCalcSpecialDlg.cpp b/DialogTools/FieldNewCalcSpecialDlg.cpp index 5705e001b..d5ee4e159 100644 --- a/DialogTools/FieldNewCalcSpecialDlg.cpp +++ b/DialogTools/FieldNewCalcSpecialDlg.cpp @@ -27,9 +27,11 @@ #include #include #include +#include #include "../GenUtils.h" #include "../Project.h" #include "../DataViewer/TableInterface.h" +#include "../DataViewer/TableFrame.h" #include "../DataViewer/TimeState.h" #include "../DataViewer/DataViewerAddColDlg.h" #include "../logger.h" @@ -107,7 +109,7 @@ void FieldNewCalcSpecialDlg::Apply() { if (m_result->GetSelection() == wxNOT_FOUND) { wxString msg("Please choose a result field."); - wxMessageDialog dlg (this, msg, "Error", wxOK | wxICON_ERROR); + wxMessageDialog dlg (this, msg, _("Error"), wxOK | wxICON_ERROR); dlg.ShowModal(); return; } @@ -125,7 +127,7 @@ void FieldNewCalcSpecialDlg::Apply() wxString msg("Normal distribution requires valid real numbers for " "mean and standard deviation. The standard " "deviation must be positive and non-zero."); - wxMessageDialog dlg (this, msg, "Error", wxOK | wxICON_ERROR); + wxMessageDialog dlg (this, msg, _("Error"), wxOK | wxICON_ERROR); dlg.ShowModal(); return; } @@ -202,17 +204,36 @@ void FieldNewCalcSpecialDlg::Apply() break; case enumerate: { + std::vector row_order; + TableFrame* tf = 0; + wxGrid* g = project->FindTableGrid(); + if (g) tf = (TableFrame*) g->GetParent()->GetParent(); // wxPanelGetRowOrder(); + } + if (col_type == GdaConst::double_type) { std::vector data(n_rows, 0); - for (int i=0; iSetColData(result_col, time_list[t], data); } else if (col_type == GdaConst::long64_type) { std::vector data(n_rows, 0); - for (int i=0; iSetColData(result_col, time_list[t], data); } else if (col_type == GdaConst::string_type) { std::vector data(n_rows, wxEmptyString); - for (int i=0; iSetColData(result_col, time_list[t], data); } table_int->SetColUndefined(result_col, time_list[t], undefined); @@ -251,7 +272,14 @@ void FieldNewCalcSpecialDlg::InitFieldChoices() m_result->SetSelection(r_sel); } else { m_result->SetSelection(m_result->FindString(r_str_sel)); - } + } + + int sel = m_result->GetSelection(); + if (sel != wxNOT_FOUND) { + m_result_tm->Enable(IsTimeVariant(col_id_map[sel])); + } else { + m_result_tm->Disable(); + } Display(); } @@ -281,14 +309,15 @@ void FieldNewCalcSpecialDlg::Display() m_var2->Show(op_sel == normal_rand); if (op_sel == normal_rand) { - if (!var1.IsEmpty() && !var2.IsEmpty()) { - rhs << "Random Gaussian dist with mean=" << var1; - rhs << ", sd=" << var2; + if (!var1.IsEmpty() && !var2.IsEmpty()) { + rhs = _("Random Gaussian dist with mean=%s, sd=%s"); + rhs = wxString::Format(rhs, var1, var2); + } } else if (op_sel == uniform_rand) { - rhs = "Random uniform dist on unit interval"; + rhs = _("Random uniform dist on unit interval"); } else { // op_sel == enumerate - rhs = "enumerate as 1, 2, 3, ..."; + rhs = _("enumerate as 1, 2, 3, ..."); } if (lhs.IsEmpty() && rhs.IsEmpty()) { @@ -383,8 +412,13 @@ void FieldNewCalcSpecialDlg::InitTime(wxChoice* time_list) time_list->Append(t); } time_list->Append("all times"); - time_list->SetSelection(project->GetTableInt()->GetTimeSteps()); - time_list->Disable(); + time_list->SetSelection(project->GetTableInt()->GetTimeSteps()); + int sel = m_result->GetSelection(); + if (sel != wxNOT_FOUND) { + time_list->Enable(IsTimeVariant(col_id_map[sel])); + } else { + time_list->Disable(); + } time_list->Show(is_space_time); } diff --git a/DialogTools/FieldNewCalcSpecialDlg.h b/DialogTools/FieldNewCalcSpecialDlg.h index 6e99f06ca..0757af53e 100644 --- a/DialogTools/FieldNewCalcSpecialDlg.h +++ b/DialogTools/FieldNewCalcSpecialDlg.h @@ -42,7 +42,7 @@ class FieldNewCalcSpecialDlg: public wxPanel FieldNewCalcSpecialDlg(Project* project, wxWindow* parent, wxWindowID id = wxID_ANY, - const wxString& caption = "Special", + const wxString& caption = _("Special"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxTAB_TRAVERSAL ); diff --git a/DialogTools/FieldNewCalcUniDlg.cpp b/DialogTools/FieldNewCalcUniDlg.cpp index a09f56aea..009d22a97 100644 --- a/DialogTools/FieldNewCalcUniDlg.cpp +++ b/DialogTools/FieldNewCalcUniDlg.cpp @@ -30,7 +30,7 @@ #include "../Project.h" #include "../DataViewer/TableInterface.h" #include "../DataViewer/TimeState.h" -#include "../DataViewer/DataViewerAddColDlg.h" +#include "../DataViewer/DataViewerAddColDlg.h" #include "../GenUtils.h" #include "../logger.h" #include "FieldNewCalcSpecialDlg.h" @@ -60,7 +60,7 @@ FieldNewCalcUniDlg::FieldNewCalcUniDlg(Project* project_s, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style ) -: all_init(false), op_string(9), project(project_s), +: all_init(false), op_string(10), project(project_s), table_int(project_s->GetTableInt()), m_valid_const(false), m_const(1), m_var_sel(wxNOT_FOUND), is_space_time(project_s->GetTableInt()->IsTimeVariant()) @@ -76,7 +76,8 @@ is_space_time(project_s->GetTableInt()->IsTimeVariant()) op_string[log_10_op] = "LOG (base 10)"; op_string[log_e_op] = "LOG (base e)"; op_string[dev_from_mean_op] = "DEVIATION FROM MEAN"; - op_string[standardize_op] = "STANDARDIZED"; + op_string[standardize_op] = "STANDARDIZED (Z)"; + op_string[mad_op] = "STANDARDIZED (MAD)"; op_string[shuffle_op] = "SHUFFLE"; for (int i=0, iend=op_string.size(); iGetSelection() == wxNOT_FOUND) { wxString msg("Please choose a Result field."); - wxMessageDialog dlg (this, msg, "Error", wxOK | wxICON_ERROR); + wxMessageDialog dlg (this, msg, _("Error"), wxOK | wxICON_ERROR); dlg.ShowModal(); return; } @@ -118,7 +119,7 @@ void FieldNewCalcUniDlg::Apply() } if (var_col == wxNOT_FOUND && !m_valid_const) { wxString msg("Operation requires a valid field name or constant."); - wxMessageDialog dlg (this, msg, "Error", wxOK | wxICON_ERROR); + wxMessageDialog dlg (this, msg, _("Error"), wxOK | wxICON_ERROR); dlg.ShowModal(); return; } @@ -128,7 +129,7 @@ void FieldNewCalcUniDlg::Apply() IsAllTime(var_col, m_var_tm->GetSelection())) { wxString msg("When \"all times\" selected for variable, result " "field must also be \"all times.\""); - wxMessageDialog dlg (this, msg, "Error", wxOK | wxICON_ERROR); + wxMessageDialog dlg (this, msg, _("Error"), wxOK | wxICON_ERROR); dlg.ShowModal(); return; } @@ -246,7 +247,7 @@ void FieldNewCalcUniDlg::Apply() msg << "Observation " << i; msg << " is undefined. "; msg << "Operation aborted."; - wxMessageDialog dlg (this, msg, "Error", + wxMessageDialog dlg (this, msg, _("Error"), wxOK | wxICON_ERROR); dlg.ShowModal(); return; @@ -264,7 +265,7 @@ void FieldNewCalcUniDlg::Apply() msg << "Observation "; msg << i << " is undefined. "; msg << "Operation aborted."; - wxMessageDialog dlg (this, msg, "Error", + wxMessageDialog dlg (this, msg, _("Error"), wxOK | wxICON_ERROR); dlg.ShowModal(); return; @@ -275,13 +276,22 @@ void FieldNewCalcUniDlg::Apply() for (int i=0; iGetCount() == prev_cnt) { // only the time field changed if (m_var_sel != wxNOT_FOUND) { - m_var->SetSelection(m_var_sel); + m_var->SetSelection(m_var_sel); + m_var->SetValue(m_var->GetStringSelection()); } else { m_var->SetValue(var_val_orig); } @@ -416,7 +427,9 @@ void FieldNewCalcUniDlg::Display() } else if (op_sel == dev_from_mean_op) { if (!var.IsEmpty()) rhs << "dev from mean of " << var; } else if (op_sel == standardize_op) { - if (!var.IsEmpty()) rhs << "standardized dev from mean of " << var; + if (!var.IsEmpty()) rhs << "standardized dev from mean of " << var; + } else if (op_sel == mad_op) { + if (!var.IsEmpty()) rhs << "mean abosolute deviation of " << var; } else { // op_sel == shuffle_op if (!var.IsEmpty()) rhs << "randomly permute values in " << var; } @@ -493,8 +506,8 @@ void FieldNewCalcUniDlg::OnUnaryOperandUpdated( wxCommandEvent& event ) } else { m_var_sel = m_var->GetSelection(); } - m_var_tm->Enable(m_var_sel != wxNOT_FOUND && - table_int->GetColTimeSteps(col_id_map[m_var_sel]) > 1); + m_var_tm->Enable(m_var_sel != wxNOT_FOUND && + table_int->GetColTimeSteps(col_id_map[m_var_sel]) > 1); Display(); } diff --git a/DialogTools/FieldNewCalcUniDlg.h b/DialogTools/FieldNewCalcUniDlg.h index 4873ac74c..bd7598d85 100644 --- a/DialogTools/FieldNewCalcUniDlg.h +++ b/DialogTools/FieldNewCalcUniDlg.h @@ -41,7 +41,7 @@ class FieldNewCalcUniDlg: public wxPanel FieldNewCalcUniDlg(Project* project, wxWindow* parent, wxWindowID id = wxID_ANY, - const wxString& caption = "Univariate", + const wxString& caption = _("Univariate"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxTAB_TRAVERSAL ); @@ -106,7 +106,8 @@ class FieldNewCalcUniDlg: public wxPanel log_e_op = 5, dev_from_mean_op = 6, standardize_op = 7, - shuffle_op = 8 + shuffle_op = 8, + mad_op = 9 }; std::vector op_string; }; diff --git a/DialogTools/GeocodingDlg.cpp b/DialogTools/GeocodingDlg.cpp new file mode 100644 index 000000000..24ddf0fad --- /dev/null +++ b/DialogTools/GeocodingDlg.cpp @@ -0,0 +1,348 @@ +/** + * GeoDa TM, Copyright (C) 2011-2015 by Luc Anselin - all rights reserved + * + * This file is part of GeoDa. + * + * GeoDa is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * GeoDa is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + + + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "../logger.h" +#include "../FramesManager.h" +#include "../Project.h" +#include "../Algorithms/geocoding.h" + +#include "GeocodingDlg.h" + +BEGIN_EVENT_TABLE( GeocodingDlg, wxDialog ) +EVT_CLOSE( GeocodingDlg::OnClose ) +END_EVENT_TABLE() + +using namespace std; + +GeocodingDlg::GeocodingDlg(wxWindow* parent, Project* p, const wxString& title, const wxPoint& pos, const wxSize& size ) +: wxDialog(NULL, -1, title, wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE|wxRESIZE_BORDER), +frames_manager(p->GetFramesManager()), project(p), table_int(p->GetTableInt()), table_state(p->GetTableState()), t(NULL), stop(false) +{ + wxLogMessage("Open GeocodingDlg()."); + CreateControls(); + Init(); + frames_manager->registerObserver(this); + table_state->registerObserver(this); +} + +GeocodingDlg::~GeocodingDlg() +{ + if (t!= NULL) { + stop = true; + t->join(); + delete t; + t = NULL; + } + + frames_manager->removeObserver(this); + table_state->removeObserver(this); +} + +void GeocodingDlg::OnClose(wxCloseEvent& ev) +{ + Destroy(); +} + +void GeocodingDlg::update(FramesManager* o) +{ +} + +void GeocodingDlg::update(TableState* o) +{ +} +void GeocodingDlg::Init() +{ + m_choice_vars->Clear(); + std::vector names; + + table_int->FillStringNameList(names); + for (int i=0; iAppend(names[i]); + } + m_choice_vars->SetSelection(0); + + m_google_input->Clear(); + m_google_input->SetValue(""); + m_google_input->SetFocus(); + m_google_input->SetCanFocus(true); + + m_prg->SetValue(0); +} + +void GeocodingDlg::CreateControls() +{ + wxPanel *panel = new wxPanel(this); + + wxBoxSizer *vbox = new wxBoxSizer(wxVERTICAL); + + // Input + wxStaticText* st01 = new wxStaticText(panel, wxID_ANY, _("Select variable with addresses:")); + m_choice_vars = new wxChoice(panel, wxID_ANY, wxDefaultPosition); + wxBoxSizer *hbox01 = new wxBoxSizer(wxHORIZONTAL); + hbox01->Add(st01, 0, wxRIGHT, 10); + hbox01->Add(m_choice_vars, 1, wxEXPAND); + + wxStaticBoxSizer *hbox0 = new wxStaticBoxSizer(wxHORIZONTAL, panel, _("Input:")); + hbox0->Add(hbox01, 1, wxEXPAND | wxALL, 10); + + // parameters + wxNotebook* notebook = new wxNotebook(panel, wxID_ANY, wxDefaultPosition, wxDefaultSize); + wxNotebookPage* google_page = new wxNotebookPage(notebook, -1, wxDefaultPosition, wxSize(560, 180)); + notebook->AddPage(google_page, _("Google Places API")); + + wxFlexGridSizer* gbox = new wxFlexGridSizer(5,1,10,0); + + wxStaticText* st11 = new wxStaticText(google_page, wxID_ANY, _("Enter your Google API keys (one key per line)")); + m_google_input = new wxTextCtrl(google_page, wxID_ANY, "", wxDefaultPosition, wxSize(500, 120), wxTE_MULTILINE); + wxHyperlinkCtrl* lnk = new wxHyperlinkCtrl(google_page, wxID_ANY, _("Click here to get a Google API key"), "https://developers.google.com/maps/documentation/geocoding/start"); + + wxBoxSizer *vbox10 = new wxBoxSizer(wxVERTICAL); + vbox10->Add(st11, 0, wxALL, 5); + vbox10->Add(m_google_input, 1, wxEXPAND|wxALL, 5); + vbox10->Add(lnk, 0, wxALL, 5); + + wxBoxSizer *nb_box1 = new wxBoxSizer(wxVERTICAL); + nb_box1->Add(vbox10, 1, wxEXPAND | wxALL, 20); + nb_box1->Fit(google_page); + + google_page->SetSizer(nb_box1); + + wxStaticBoxSizer *hbox = new wxStaticBoxSizer(wxHORIZONTAL, panel, _("Parameters:")); + hbox->Add(notebook, 0, wxEXPAND); + + // output + wxStaticText* st21 = new wxStaticText(panel, wxID_ANY, _("Save latitude to field:")); + m_lat = new wxTextCtrl(panel, wxID_ANY, "G_LAT"); + + wxStaticText* st22 = new wxStaticText(panel, wxID_ANY, _("Save longitude to field:")); + m_lng = new wxTextCtrl(panel, wxID_ANY, "G_LNG"); + + wxFlexGridSizer* grid_sizer1 = new wxFlexGridSizer(2, 2, 5, 5); + grid_sizer1->Add(st21); + grid_sizer1->Add(m_lat); + grid_sizer1->Add(st22); + grid_sizer1->Add(m_lng); + + wxStaticBoxSizer *hbox1 = new wxStaticBoxSizer(wxHORIZONTAL, panel, _("Output:")); + //hbox1->Add(st21); + hbox1->Add(grid_sizer1, 0, wxEXPAND | wxALL, 10); + + // buttons + okButton = new wxButton(panel, wxID_OK, _("Run"), wxDefaultPosition, + wxSize(70, 30)); + stopButton = new wxButton(panel, wxID_ANY, _("Stop"), wxDefaultPosition, + wxSize(70, 30)); + closeButton = new wxButton(panel, wxID_EXIT, _("Close"), + wxDefaultPosition, wxSize(70, 30)); + wxBoxSizer *hbox2 = new wxBoxSizer(wxHORIZONTAL); + hbox2->Add(okButton, 1, wxALIGN_CENTER | wxALL, 5); + hbox2->Add(stopButton, 1, wxALIGN_CENTER | wxALL, 5); + hbox2->Add(closeButton, 1, wxALIGN_CENTER | wxALL, 5); + + // progress bar + m_prg = new wxGauge(panel, wxID_ANY, project->GetNumRecords()); + + // Container + vbox->Add(hbox0, 0, wxEXPAND | wxALL, 10); + vbox->Add(hbox, 0, wxALIGN_CENTER | wxALL, 10); + vbox->Add(hbox1, 0, wxEXPAND | wxALL, 10); + vbox->Add(m_prg, 0, wxEXPAND | wxALL, 10); + vbox->Add(hbox2, 0, wxALIGN_CENTER | wxALL, 10); + + wxBoxSizer *container = new wxBoxSizer(wxHORIZONTAL); + container->Add(vbox); + + panel->SetSizer(container); + + wxBoxSizer* sizerAll = new wxBoxSizer(wxVERTICAL); + sizerAll->Add(panel, 1, wxEXPAND|wxALL, 0); + SetSizer(sizerAll); + //SetAutoLayout(true); + sizerAll->Fit(this); + + Centre(); + + // Events + okButton->Bind(wxEVT_BUTTON, &GeocodingDlg::OnOkClick, this); + stopButton->Bind(wxEVT_BUTTON, &GeocodingDlg::OnStopClick, this); + closeButton->Bind(wxEVT_BUTTON, &GeocodingDlg::OnCloseClick, this); +} + +void GeocodingDlg::OnOkClick( wxCommandEvent& event ) +{ + wxLogMessage("In GeocodingDlg::OnOkClick()"); + if (t!= NULL) { + t->join(); + delete t; + t = NULL; + } + t = new boost::thread(boost::bind(&GeocodingDlg::run, this)); +} + +void GeocodingDlg::OnStopClick( wxCommandEvent& event ) +{ + stop = true; + okButton->Enable(); + stopButton->Disable(); + closeButton->Enable(); +} + +void GeocodingDlg::run() +{ + wxLogMessage("In GeocodingDlg::run()"); + + // get select variable + wxString sel_var = m_choice_vars->GetString(m_choice_vars->GetSelection()); + if (sel_var.empty()) { + wxMessageDialog dlg(this, _("Please select a field with addresses."), _("Warning"), + wxOK | wxICON_INFORMATION); + dlg.ShowModal(); + return; + } + // get keys + wxString google_keys = m_google_input->GetValue(); + if (google_keys.empty() ) { + wxMessageDialog dlg(this, _("Please enter Google key(s)."), _("Warning"), + wxOK | wxICON_INFORMATION); + dlg.ShowModal(); + return; + } + vector keys; + wxStringTokenizer tokenizer(google_keys, "\n"); + while ( tokenizer.HasMoreTokens() ) { + wxString token = tokenizer.GetNextToken(); + keys.push_back(token.Trim()); + } + + // detect output fields + wxString lat_fname = m_lat->GetValue(); + if (lat_fname.empty()) { + wxMessageDialog dlg(this, _("Please input a field name for saving latitude"), _("Warning"),wxOK | wxICON_INFORMATION); + dlg.ShowModal(); + return; + } + wxString lng_fname = m_lng->GetValue(); + if (lng_fname.empty()) { + wxMessageDialog dlg(this, _("Please input a field name for saving longitude"), _("Warning"), wxOK | wxICON_INFORMATION); + dlg.ShowModal(); + return; + } + int time=0; + int col_lat = table_int->FindColId(lat_fname); + if ( col_lat != wxNOT_FOUND) { + // detect if column is integer field, if not raise a warning + if (table_int->GetColType(col_lat) != GdaConst::double_type ) { + wxString msg = _("This field name already exists (non-float type). Please input a unique name."); + wxMessageDialog dlg(this, msg, _("Warning"), wxOK | wxICON_WARNING ); + dlg.ShowModal(); + return; + } + } + int col_lng = table_int->FindColId(lng_fname); + if ( col_lng != wxNOT_FOUND) { + // detect if column is integer field, if not raise a warning + if (table_int->GetColType(col_lng) != GdaConst::double_type ) { + wxString msg = _("This field name already exists (non-float type). Please input a unique name."); + wxMessageDialog dlg(this, msg, _("Warning"), wxOK | wxICON_WARNING ); + dlg.ShowModal(); + return; + } + } + + // start + stop = false; + okButton->Disable(); + stopButton->Enable(); + closeButton->Disable(); + m_prg->SetValue(1); + + int n_rows = project->GetNumRecords(); + std::vector addresses; + int col_var = table_int->FindColId(sel_var); + table_int->GetColData(col_var, time, addresses); + + vector lats(n_rows); + vector lngs(n_rows); + vector undefs(n_rows, true); + + if ( col_lat != wxNOT_FOUND) + table_int->GetColData(col_lat, time, lats, undefs); + if ( col_lng != wxNOT_FOUND) + table_int->GetColData(col_lng, time, lngs, undefs); + + GoogleGeoCoder coder(keys); + coder.geocoding(addresses, lats, lngs, undefs, m_prg, &stop); + + if ( col_lat == wxNOT_FOUND) { + int col_insert_pos = table_int->GetNumberCols(); + int time_steps = 1; + int m_length_val = GdaConst::default_dbf_double_len; + int m_decimals_val = GdaConst::default_dbf_double_decimals; + col_lat = table_int->InsertCol(GdaConst::double_type, lat_fname, col_insert_pos, time_steps, m_length_val, m_decimals_val); + } + if ( col_lng == wxNOT_FOUND) { + int col_insert_pos = table_int->GetNumberCols(); + int time_steps = 1; + int m_length_val = GdaConst::default_dbf_double_len; + int m_decimals_val = GdaConst::default_dbf_double_decimals; + col_lng = table_int->InsertCol(GdaConst::double_type, lng_fname, col_insert_pos, time_steps, m_length_val, m_decimals_val); + } + table_int->SetColData(col_lat, time, coder.lats, coder.undefs); + table_int->SetColData(col_lng, time, coder.lngs, coder.undefs); + + wxString msg = _("Successful Geocode. Please check results in Table."); + if (!coder.error_msg.empty()) { + msg << "\n\nDetails:\n\n"; + msg << coder.error_msg; + } + wxMessageDialog dlg(this, msg, _("Info"), wxOK | wxICON_INFORMATION); + dlg.ShowModal(); + stop = false; + + okButton->Enable(); + stopButton->Disable(); + closeButton->Enable(); + //EndDialog(wxID_OK); +} + +void GeocodingDlg::OnCloseClick( wxCommandEvent& event ) +{ + wxLogMessage("In GeocodingDlg::OnOkClick()"); + + EndDialog(wxID_CANCEL); +} diff --git a/DialogTools/GeocodingDlg.h b/DialogTools/GeocodingDlg.h new file mode 100644 index 000000000..6a853cb4f --- /dev/null +++ b/DialogTools/GeocodingDlg.h @@ -0,0 +1,92 @@ +/** + * GeoDa TM, Copyright (C) 2011-2015 by Luc Anselin - all rights reserved + * + * This file is part of GeoDa. + * + * GeoDa is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * GeoDa is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +#ifndef __GEODA_CENTER_GEOCODING_DLG_H__ +#define __GEODA_CENTER_GEOCODING_DLG_H__ + + +#include +#include +#include + +#include "../FramesManager.h" +#include "../FramesManagerObserver.h" +#include "../Project.h" + +class FramesManager; +class TableInterface; +class Project; + +using namespace std; + +class GeocodingDlg : public wxDialog, public FramesManagerObserver, public TableStateObserver +{ +public: + GeocodingDlg(wxWindow* parent, Project* p, + const wxString& title = _("Geocode Setting Dialog"), + const wxPoint& pos = wxDefaultPosition, + const wxSize& size = wxDefaultSize ); + + ~GeocodingDlg(); + + /** Implementation of FramesManagerObserver interface */ + virtual void update(FramesManager* o); + virtual void update(TableState* o); + /** This method is only here temporarily until all observer classes + support dynamic time changes such as swap, rename and add/remove. */ + virtual bool AllowTimelineChanges() { return true; } + /** Does this observer allow data modifications to named group. */ + virtual bool AllowGroupModify(const wxString& grp_nm) { return true; } + /** Does this observer allow Table/Geometry row additions and deletions. */ + virtual bool AllowObservationAddDelete(){ return true; } + + void Init(); + + void CreateControls(); + void run(); + + void OnClose(wxCloseEvent& ev); + void OnOkClick( wxCommandEvent& event ); + void OnStopClick( wxCommandEvent& event ); + void OnCloseClick( wxCommandEvent& event ); + +protected: + wxFrame *parent; + Project* project; + TableInterface* table_int; + FramesManager* frames_manager; + TableState* table_state; + + boost::thread* t; + bool stop; + + wxChoice* m_choice_vars; + wxTextCtrl* m_lat; + wxTextCtrl* m_lng; + wxTextCtrl* m_google_input; + + wxButton *okButton; + wxButton *stopButton; + wxButton *closeButton; + + wxGauge* m_prg; + + DECLARE_EVENT_TABLE() +}; + +#endif diff --git a/DialogTools/HClusterDlg.cpp b/DialogTools/HClusterDlg.cpp index 93af3574b..107834348 100644 --- a/DialogTools/HClusterDlg.cpp +++ b/DialogTools/HClusterDlg.cpp @@ -21,11 +21,14 @@ #include #include +#include #include +#include #include #include #include #include +#include #include #include #include @@ -34,30 +37,34 @@ #include #include #include - +#include #include "../Explore/MapNewView.h" #include "../Project.h" #include "../Algorithms/cluster.h" #include "../GeneralWxUtils.h" #include "../GenUtils.h" +#include "../Algorithms/DataUtils.h" +#include "../Algorithms/fastcluster.h" +#include "../VarCalc/WeightsManInterface.h" +#include "../ShapeOperations/WeightUtils.h" +#include "../Algorithms/redcap.h" #include "SaveToTableDlg.h" #include "HClusterDlg.h" + + BEGIN_EVENT_TABLE( HClusterDlg, wxDialog ) EVT_CLOSE( HClusterDlg::OnClose ) END_EVENT_TABLE() HClusterDlg::HClusterDlg(wxFrame* parent_s, Project* project_s) -: frames_manager(project_s->GetFramesManager()), -wxDialog(NULL, -1, _("Hierarchical Clustering Settings"), wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE|wxRESIZE_BORDER) +: AbstractClusterDlg(parent_s, project_s, _("Hierarchical Clustering Settings")) { wxLogMessage("Open HClusterDlg."); - SetMinSize(wxSize(860,640)); - parent = parent_s; project = project_s; @@ -71,13 +78,11 @@ wxDialog(NULL, -1, _("Hierarchical Clustering Settings"), wxDefaultPosition, wxD CreateControls(); } - frames_manager->registerObserver(this); highlight_state->registerObserver(this); } HClusterDlg::~HClusterDlg() { - frames_manager->removeObserver(this); highlight_state->removeObserver(this); } @@ -92,6 +97,17 @@ void HClusterDlg::Highlight(int id) highlight_state->notifyObservers(this); } +void HClusterDlg::Highlight(vector& ids) +{ + vector& hs = highlight_state->GetHighlight(); + + for (int i=0; iSetEventType(HLStateInt::delta); + highlight_state->notifyObservers(this); +} + bool HClusterDlg::Init() { if (project == NULL) @@ -101,7 +117,7 @@ bool HClusterDlg::Init() if (table_int == NULL) return false; - + num_obs = project->GetNumRecords(); table_int->GetTimeStrings(tm_strs); return true; @@ -109,40 +125,24 @@ bool HClusterDlg::Init() void HClusterDlg::CreateControls() { - wxPanel *panel = new wxPanel(this); - - wxBoxSizer *vbox = new wxBoxSizer(wxVERTICAL); + wxScrolledWindow* scrl = new wxScrolledWindow(this, wxID_ANY, wxDefaultPosition, wxSize(880,780), wxHSCROLL|wxVSCROLL ); + scrl->SetScrollRate( 5, 5 ); + + wxPanel *panel = new wxPanel(scrl); // Input - wxStaticText* st = new wxStaticText (panel, wxID_ANY, _("Select Variables"), - wxDefaultPosition, wxDefaultSize); + wxBoxSizer *vbox = new wxBoxSizer(wxVERTICAL); + AddInputCtrls(panel, vbox); - wxListBox* box = new wxListBox(panel, wxID_ANY, wxDefaultPosition, - wxSize(250,250), 0, NULL, - wxLB_MULTIPLE | wxLB_HSCROLL| wxLB_NEEDED_SB); - wxCheckBox* cbox = new wxCheckBox(panel, wxID_ANY, _("Use Geometric Centroids")); - wxStaticBoxSizer *hbox0 = new wxStaticBoxSizer(wxVERTICAL, panel, "Input:"); - hbox0->Add(st, 0, wxALIGN_CENTER | wxLEFT | wxRIGHT, 10); - hbox0->Add(box, 1, wxEXPAND | wxLEFT | wxRIGHT | wxBOTTOM, 10); - hbox0->Add(cbox, 0, wxLEFT | wxRIGHT, 10); - - if (project->IsTableOnlyProject()) { - cbox->Disable(); - } // Parameters wxFlexGridSizer* gbox = new wxFlexGridSizer(5,2,5,0); - wxStaticText* st14 = new wxStaticText(panel, wxID_ANY, _("Transformation:"), - wxDefaultPosition, wxSize(120,-1)); - const wxString _transform[3] = {"Raw", "Demean", "Standardize"}; - combo_tranform = new wxChoice(panel, wxID_ANY, wxDefaultPosition, wxSize(120,-1), 3, _transform); - combo_tranform->SetSelection(2); - gbox->Add(st14, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT | wxLEFT, 10); - gbox->Add(combo_tranform, 1, wxEXPAND); + // Transformation + AddTransformation(panel, gbox); wxStaticText* st12 = new wxStaticText(panel, wxID_ANY, _("Method:"), wxDefaultPosition, wxSize(120,-1)); - wxString choices12[] = {"Single-linkage","Complete-linkage","Average-linkage","Centroid-linkage"}; + wxString choices12[] = {"Single-linkage","Ward's-linkage", "Complete-linkage","Average-linkage"}; wxChoice* box12 = new wxChoice(panel, wxID_ANY, wxDefaultPosition, wxSize(120,-1), 4, choices12); box12->SetSelection(1); @@ -151,44 +151,61 @@ void HClusterDlg::CreateControls() wxStaticText* st13 = new wxStaticText(panel, wxID_ANY, _("Distance Function:"), wxDefaultPosition, wxSize(120,-1)); - wxString choices13[] = {"Distance", "--Euclidean", "--City-block", "Correlation", "--Pearson","--Absolute Pearson", "Cosine", "--Signed", "--Un-signed", "Rank", "--Spearman", "--Kendal"}; - wxChoice* box13 = new wxChoice(panel, wxID_ANY, wxDefaultPosition, wxSize(120,-1), 12, choices13); - box13->SetSelection(1); + wxString choices13[] = {"Euclidean", "Manhattan"}; + wxChoice* box13 = new wxChoice(panel, wxID_ANY, wxDefaultPosition, wxSize(120,-1), 2, choices13); + box13->SetSelection(0); gbox->Add(st13, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT | wxLEFT, 10); gbox->Add(box13, 1, wxEXPAND); - wxStaticBoxSizer *hbox = new wxStaticBoxSizer(wxHORIZONTAL, panel, "Parameters:"); + wxStaticText* st17 = new wxStaticText(panel, wxID_ANY, _("Spatially Constraint:"), + wxDefaultPosition, wxSize(128,-1)); + chk_contiguity = new wxCheckBox(panel, wxID_ANY, ""); + gbox->Add(st17, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT | wxLEFT, 10); + gbox->Add(chk_contiguity, 1, wxEXPAND); + chk_contiguity->Disable(); + + wxStaticText* st16 = new wxStaticText(panel, wxID_ANY, _(""), + wxDefaultPosition, wxSize(128,-1)); + combo_weights = new wxChoice(panel, wxID_ANY, wxDefaultPosition, + wxSize(200,-1)); + gbox->Add(st16, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT | wxLEFT, 10); + gbox->Add(combo_weights, 1, wxEXPAND); + combo_weights->Disable(); + + wxStaticBoxSizer *hbox = new wxStaticBoxSizer(wxHORIZONTAL, panel, _("Parameters:")); hbox->Add(gbox, 1, wxEXPAND); - // Output wxFlexGridSizer* gbox1 = new wxFlexGridSizer(5,2,5,0); - wxString choices[] = {"2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20"}; wxStaticText* st1 = new wxStaticText(panel, wxID_ANY, _("Number of Clusters:"), wxDefaultPosition, wxDefaultSize); - wxChoice* box1 = new wxChoice(panel, wxID_ANY, wxDefaultPosition, - wxSize(120,-1), 19, choices); - box1->SetSelection(3); + max_n_clusters = num_obs < 60 ? num_obs : 60; + wxTextValidator validator(wxFILTER_INCLUDE_CHAR_LIST); + wxArrayString list; + wxString valid_chars("0123456789"); + size_t len = valid_chars.Length(); + for (size_t i=0; iAdd(st1, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT | wxLEFT, 10); - gbox1->Add(box1, 1, wxEXPAND); - + gbox1->Add(m_cluster, 1, wxEXPAND); - wxStaticText* st3 = new wxStaticText (panel, wxID_ANY, _("Save Cluster in Field:"), - wxDefaultPosition, wxDefaultSize); - wxTextCtrl *box3 = new wxTextCtrl(panel, wxID_ANY, wxT(""), wxDefaultPosition, wxSize(120,-1)); + wxStaticText* st3 = new wxStaticText (panel, wxID_ANY, _("Save Cluster in Field:"), wxDefaultPosition, wxDefaultSize); + wxTextCtrl *box3 = new wxTextCtrl(panel, wxID_ANY, "CL", wxDefaultPosition, wxSize(120,-1)); gbox1->Add(st3, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT | wxLEFT, 10); - gbox1->Add(box3, 1, wxEXPAND); + gbox1->Add(box3, 1, wxALIGN_CENTER_VERTICAL); - wxStaticBoxSizer *hbox1 = new wxStaticBoxSizer(wxHORIZONTAL, panel, "Output:"); + wxStaticBoxSizer *hbox1 = new wxStaticBoxSizer(wxHORIZONTAL, panel, _("Output:")); hbox1->Add(gbox1, 1, wxEXPAND); // Buttons - wxButton *okButton = new wxButton(panel, wxID_OK, wxT("Run"), wxDefaultPosition, - wxSize(70, 30)); - saveButton = new wxButton(panel, wxID_SAVE, wxT("Save/Show Map"), wxDefaultPosition, wxDefaultSize); - wxButton *closeButton = new wxButton(panel, wxID_EXIT, wxT("Close"), + wxButton *okButton = new wxButton(panel, wxID_OK, _("Run"), wxDefaultPosition, wxSize(70, 30)); + saveButton = new wxButton(panel, wxID_SAVE, _("Save/Show Map"), wxDefaultPosition, wxDefaultSize); + wxButton *closeButton = new wxButton(panel, wxID_EXIT, _("Close"), wxDefaultPosition, wxSize(70, 30)); wxBoxSizer *hbox2 = new wxBoxSizer(wxHORIZONTAL); hbox2->Add(okButton, 0, wxALIGN_CENTER | wxALL, 5); @@ -196,26 +213,31 @@ void HClusterDlg::CreateControls() hbox2->Add(closeButton, 0, wxALIGN_CENTER | wxALL, 5); // Container - vbox->Add(hbox0, 1, wxEXPAND | wxALL, 10); - vbox->Add(hbox, 0, wxALIGN_CENTER | wxALL, 10); - vbox->Add(hbox1, 0, wxALIGN_CENTER | wxTOP | wxLEFT | wxRIGHT, 10); + vbox->Add(hbox, 0, wxEXPAND | wxALL, 10); + vbox->Add(hbox1, 0, wxEXPAND | wxTOP | wxLEFT | wxRIGHT, 10); vbox->Add(hbox2, 0, wxALIGN_CENTER | wxALL, 10); - - - wxBoxSizer *vbox1 = new wxBoxSizer(wxVERTICAL); - m_panel = new DendrogramPanel(panel, wxID_ANY, wxDefaultPosition, wxSize(500,630)); - //m_panel->SetBackgroundColour(*wxWHITE); - vbox1->Add(m_panel, 1, wxEXPAND|wxALL,20); + + // Summary control + notebook = new wxNotebook( panel, wxID_ANY); + m_panel = new DendrogramPanel(max_n_clusters, notebook, wxID_ANY); + notebook->AddPage(m_panel, _("Dendrogram")); + m_reportbox = new SimpleReportTextCtrl(notebook, wxID_ANY, _("(Please save results to see the summary report.)")); + notebook->AddPage(m_reportbox, _("Summary")); + notebook->Connect(wxEVT_NOTEBOOK_PAGE_CHANGING, wxBookCtrlEventHandler(HClusterDlg::OnNotebookChange), NULL, this); + wxBoxSizer *container = new wxBoxSizer(wxHORIZONTAL); container->Add(vbox); - container->Add(vbox1,1, wxEXPAND | wxALL); - + container->Add(notebook,1, wxEXPAND | wxALL); panel->SetSizerAndFit(container); + wxBoxSizer* panelSizer = new wxBoxSizer(wxVERTICAL); + panelSizer->Add(panel, 1, wxEXPAND|wxALL, 0); + + scrl->SetSizer(panelSizer); wxBoxSizer* sizerAll = new wxBoxSizer(wxVERTICAL); - sizerAll->Add(panel, 1, wxEXPAND|wxALL, 0); + sizerAll->Add(scrl, 1, wxEXPAND|wxALL, 0); SetSizer(sizerAll); SetAutoLayout(true); sizerAll->Fit(this); @@ -223,30 +245,52 @@ void HClusterDlg::CreateControls() Centre(); // Content - InitVariableCombobox(box); - combo_n = box1; + //combo_n = box1; m_textbox = box3; - combo_var = box; - m_use_centroids = cbox; //m_iterations = box11; m_method = box12; m_distance = box13; + // init weights + vector weights_ids; + WeightsManInterface* w_man_int = project->GetWManInt(); + w_man_int->GetIds(weights_ids); + + size_t sel_pos=0; + for (size_t i=0; iAppend(w_man_int->GetShortDispName(weights_ids[i])); + if (w_man_int->GetDefault() == weights_ids[i]) + sel_pos = i; + } + if (weights_ids.size() > 0) combo_weights->SetSelection(sel_pos); + // Events - okButton->Bind(wxEVT_BUTTON, &HClusterDlg::OnOK, this); + okButton->Bind(wxEVT_BUTTON, &HClusterDlg::OnOKClick, this); saveButton->Bind(wxEVT_BUTTON, &HClusterDlg::OnSave, this); - closeButton->Bind(wxEVT_BUTTON, &HClusterDlg::OnClickClose, this); - m_distance->Connect(wxEVT_CHOICE, - wxCommandEventHandler(HClusterDlg::OnDistanceChoice), - NULL, this); - combo_n->Connect(wxEVT_CHOICE, - wxCommandEventHandler(HClusterDlg::OnClusterChoice), - NULL, this); - + m_cluster->Connect(wxEVT_TEXT, wxCommandEventHandler(HClusterDlg::OnClusterChoice), NULL, this); + chk_contiguity->Bind(wxEVT_CHECKBOX, &HClusterDlg::OnSpatialConstraintCheck, this); saveButton->Disable(); - combo_n->Disable(); + //combo_n->Disable(); + m_cluster->Disable(); +} + +void HClusterDlg::OnSpatialConstraintCheck(wxCommandEvent& event) +{ + wxLogMessage("On HClusterDlg::OnSpatialConstraintCheck"); + bool checked = chk_contiguity->GetValue(); + + if (checked) { + combo_weights->Enable(); + } else { + combo_weights->Disable(); + } +} +void HClusterDlg::OnNotebookChange(wxBookCtrlEvent& event) +{ + int tab_idx = event.GetOldSelection(); + m_panel->SetActive(tab_idx == 1); } void HClusterDlg::OnSave(wxCommandEvent& event ) @@ -254,7 +298,7 @@ void HClusterDlg::OnSave(wxCommandEvent& event ) wxString field_name = m_textbox->GetValue(); if (field_name.IsEmpty()) { wxString err_msg = _("Please enter a field name for saving clustering results."); - wxMessageDialog dlg(NULL, err_msg, "Error", wxOK | wxICON_ERROR); + wxMessageDialog dlg(NULL, err_msg, _("Error"), wxOK | wxICON_ERROR); dlg.ShowModal(); return; } @@ -274,7 +318,7 @@ void HClusterDlg::OnSave(wxCommandEvent& event ) // detect if column is integer field, if not raise a warning if (table_int->GetColType(col) != GdaConst::long64_type ) { wxString msg = _("This field name already exists (non-integer type). Please input a unique name."); - wxMessageDialog dlg(this, msg, "Warning", wxOK | wxICON_WARNING ); + wxMessageDialog dlg(this, msg, _("Warning"), wxOK | wxICON_WARNING ); dlg.ShowModal(); return; } @@ -285,6 +329,9 @@ void HClusterDlg::OnSave(wxCommandEvent& event ) table_int->SetColUndefined(col, time, clusters_undef); } + // summary + CreateSummary(clusters); + // show a cluster map if (project->IsTableOnlyProject()) { return; @@ -311,6 +358,11 @@ void HClusterDlg::OnSave(wxCommandEvent& event ) wxDefaultPosition, GdaConst::map_default_size); + wxString ttl; + ttl << "Hierachical " << _("Cluster Map ") << "("; + ttl << m_cluster->GetValue(); + ttl << " clusters)"; + nf->SetTitle(ttl); } void HClusterDlg::OnDistanceChoice(wxCommandEvent& event) @@ -329,16 +381,26 @@ void HClusterDlg::OnDistanceChoice(wxCommandEvent& event) void HClusterDlg::OnClusterChoice(wxCommandEvent& event) { - int sel_ncluster = combo_n->GetSelection() + 2; - - // update dendrogram - m_panel->UpdateCluster(sel_ncluster, clusters); + //int sel_ncluster = combo_n->GetSelection() + 2; + wxString tmp_val = m_cluster->GetValue(); + tmp_val.Trim(false); + tmp_val.Trim(true); + long sel_ncluster; + bool is_valid = tmp_val.ToLong(&sel_ncluster); + if (is_valid) { + //sel_ncluster += 2; + // update dendrogram + m_panel->UpdateCluster(sel_ncluster, clusters); + } } void HClusterDlg::UpdateClusterChoice(int n, std::vector& _clusters) { - int sel = n - 2; - combo_n->SetSelection(sel); + //int sel = n - 2; + //combo_n->SetSelection(sel); + wxString str_n; + str_n << n; + m_cluster->SetValue(str_n); for (int i=0; iInsertItems(items,0); - var_box->InsertItems(items,0); -} - -void HClusterDlg::update(FramesManager* o) -{ + for (int i=0; iSetStringSelection(select_vars[i], true); + } } void HClusterDlg::update(HLStateInt* o) @@ -397,195 +459,149 @@ void HClusterDlg::OnClose(wxCloseEvent& ev) Destroy(); } - - -void HClusterDlg::OnOK(wxCommandEvent& event ) +wxString HClusterDlg::_printConfiguration() { - wxLogMessage("Click HClusterDlg::OnOK"); + wxString txt; + txt << _("Number of clusters:\t") << m_cluster->GetValue() << "\n"; - int ncluster = combo_n->GetSelection() + 2; + txt << _("Transformation:\t") << combo_tranform->GetString(combo_tranform->GetSelection()) << "\n"; - bool use_centroids = m_use_centroids->GetValue(); + txt << _("Method:\t") << m_method->GetString(m_method->GetSelection()) << "\n"; - wxArrayInt selections; - combo_var->GetSelections(selections); + txt << _("Distance function:\t") << m_distance->GetString(m_distance->GetSelection()) << "\n"; - int num_var = selections.size(); - if (num_var < 2 && !use_centroids) { - // show message box - wxString err_msg = _("Please select at least 2 variables."); - wxMessageDialog dlg(NULL, err_msg, "Info", wxOK | wxICON_ERROR); - dlg.ShowModal(); - return; - } - - col_ids.resize(num_var); - var_info.resize(num_var); - - for (int i=0; iGetString(idx)]; - - int col = table_int->FindColId(nm); - if (col == wxNOT_FOUND) { - wxString err_msg = wxString::Format(_("Variable %s is no longer in the Table. Please close and reopen the Regression Dialog to synchronize with Table data."), nm); wxMessageDialog dlg(NULL, err_msg, "Error", wxOK | wxICON_ERROR); - dlg.ShowModal(); - return; - } - - int tm = name_to_tm_id[combo_var->GetString(idx)]; - - col_ids[i] = col; - var_info[i].time = tm; - - // Set Primary GdaVarTools::VarInfo attributes - var_info[i].name = nm; - var_info[i].is_time_variant = table_int->IsColTimeVariant(idx); - - // var_info[i].time already set above - table_int->GetMinMaxVals(col_ids[i], var_info[i].min, var_info[i].max); - var_info[i].sync_with_global_time = var_info[i].is_time_variant; - var_info[i].fixed_scale = true; - } - - // Call function to set all Secondary Attributes based on Primary Attributes - GdaVarTools::UpdateVarInfoSecondaryAttribs(var_info); - - int rows = project->GetNumRecords(); - int columns = 0; + return txt; +} + +void HClusterDlg::OnOKClick(wxCommandEvent& event ) +{ + wxLogMessage("Click HClusterDlg::OnOK"); - std::vector data; // data[variable][time][obs] - data.resize(col_ids.size()); - for (int i=0; iGetColData(col_ids[i], data[i]); - } - // get columns (if time variables show) - for (int i=0; iGetSelection() + 2; + long ncluster; + m_cluster->GetValue().ToLong(&ncluster); - // if use centroids - if (use_centroids) { - columns += 2; + int transform = combo_tranform->GetSelection(); + bool success = GetInputData(transform,1); + if (!success) { + return; } - int transform = combo_tranform->GetSelection(); char method = 's'; char dist = 'e'; int transpose = 0; // row wise int* clusterid = new int[rows]; - double* weight = new double[columns]; - for (int j=0; jGetSelection(); - char method_choices[] = {'s','m','a','c'}; + char method_choices[] = {'s','w', 'm','a'}; method = method_choices[method_sel]; int dist_sel = m_distance->GetSelection(); - char dist_choices[] = {'e','e','b','c','c','a','u','u','x','s','s','k'}; + char dist_choices[] = {'e','b'}; dist = dist_choices[dist_sel]; - // init input_data[rows][cols] - double** input_data = new double*[rows]; - int** mask = new int*[rows]; - for (int i=0; iGetValue()) { + vector weights_ids; + WeightsManInterface* w_man_int = project->GetWManInt(); + w_man_int->GetIds(weights_ids); - for (int j=0; j vals; - - for (int k=0; k< rows;k++) { // row - vals.push_back(data[i][j][k]); - } - - if (transform == 2) { - GenUtils::StandardizeData(vals); - } else if (transform == 1 ) { - GenUtils::DeviationFromMean(vals); - } - - for (int k=0; k< rows;k++) { // row - input_data[k][col_ii] = vals[k]; - } - col_ii += 1; - } - } - if (use_centroids) { - std::vector cents = project->GetCentroids(); - std::vector cent_xs; - std::vector cent_ys; + int sel = combo_weights->GetSelection(); + if (sel < 0) sel = 0; + if (sel >= weights_ids.size()) sel = weights_ids.size()-1; + + boost::uuids::uuid w_id = weights_ids[sel]; + GalWeight* gw = w_man_int->GetGal(w_id); - for (int i=0; i< rows; i++) { - cent_xs.push_back(cents[i]->GetX()); - cent_ys.push_back(cents[i]->GetY()); + if (gw == NULL) { + wxMessageDialog dlg (this, _("Invalid Weights Information:\n\n The selected weights file is not valid.\n Please choose another weights file, or use Tools > Weights > Weights Manager\n to define a valid weights file."), _("Warning"), wxOK | wxICON_WARNING); + dlg.ShowModal(); + return; + } + //GeoDaWeight* weights = w_man_int->GetGal(w_id); + // Check connectivity + if (!CheckConnectivity(gw)) { + wxString msg = _("The connectivity of selected spatial weights is incomplete, please adjust the spatial weights."); + wxMessageDialog dlg(this, msg, _("Warning"), wxOK | wxICON_WARNING ); + dlg.ShowModal(); + return; } - if (transform == 2) { - GenUtils::StandardizeData(cent_xs ); - GenUtils::StandardizeData(cent_ys ); - } else if (transform == 1 ) { - GenUtils::DeviationFromMean(cent_xs ); - GenUtils::DeviationFromMean(cent_ys ); + double** ragged_distances = distancematrix(rows, columns, input_data, mask, weight, dist, transpose); + double** distances = DataUtils::fullRaggedMatrix(ragged_distances, rows, rows); + for (int i = 1; i < rows; i++) free(ragged_distances[i]); + free(ragged_distances); + std::vector undefs(rows, false); + SpanningTreeClustering::AbstractClusterFactory* redcap = new SpanningTreeClustering::FirstOrderSLKRedCap(rows, columns, distances, input_data, undefs, gw->gal, NULL, 0); + for (int i=0; iordered_edges.size(); i++) { + Z2[i]->node1 = redcap->ordered_edges[i]->orig->id; + Z2[i]->node2 = redcap->ordered_edges[i]->dest->id; + Z2[i]->dist = redcap->ordered_edges[i]->length; } - - for (int i=0; i< rows; i++) { - input_data[i][col_ii + 0] = cent_xs[i]; - input_data[i][col_ii + 1] = cent_ys[i]; + delete redcap; + + } else { + + double* pwdist = DataUtils::getPairWiseDistance(input_data, rows, columns, DataUtils::EuclideanDistance); + //double* pwdist = DataUtils::getContiguityPairWiseDistance(gw->gal, input_data, rows, columns, DataUtils::EuclideanDistance); + + fastcluster::auto_array_ptr members; + + if (method == 's') { + fastcluster::MST_linkage_core(rows, pwdist, Z2); + } else if (method == 'w') { + members.init(rows, 1); + fastcluster::NN_chain_core(rows, pwdist, members, Z2); + } else if (method == 'm') { + fastcluster::NN_chain_core(rows, pwdist, NULL, Z2); + } else if (method == 'a') { + members.init(rows, 1); + fastcluster::NN_chain_core(rows, pwdist, members, Z2); } + + delete[] pwdist; + + } + std::stable_sort(Z2[0], Z2[rows-1]); + t_index node1, node2; + int i=0; + fastcluster::union_find nodes(rows); + for (fastcluster::node const * NN=Z2[0]; NN!=Z2[rows-1]; ++NN, ++i) { + // Find the cluster identifiers for these points. + node1 = nodes.Find(NN->node1); + node2 = nodes.Find(NN->node2); + // Merge the nodes in the union-find data structure by making them + // children of a new node. + nodes.Union(node1, node2); + + node2 = node2 < rows ? node2 : rows-node2-1; + node1 = node1 < rows ? node1 : rows-node1-1; + + //cout << i<< ":" << node2 <<", " << node1 << ", " << Z2[i]->dist <dist; } - GdaNode* htree = treecluster(rows, columns, input_data, mask, weight, transpose, dist, method, NULL); double cutoffDistance = cuttree (rows, htree, ncluster, clusterid); clusters.clear(); clusters_undef.clear(); - - // clean memory + for (int i=0; i > cluster_ids(ncluster); - - for (int i=0; i < clusters.size(); i++) { - cluster_ids[ clusters[i] - 1 ].push_back(i); - } - - std::sort(cluster_ids.begin(), cluster_ids.end(), GenUtils::less_vectors); - - for (int i=0; i < ncluster; i++) { - int c = i + 1; - for (int j=0; jSetup(htree, rows, ncluster, clusters, cutoffDistance); @@ -593,7 +609,7 @@ void HClusterDlg::OnOK(wxCommandEvent& event ) saveButton->Enable(); - combo_n->Enable(); + m_cluster->Enable(); } @@ -603,14 +619,15 @@ IMPLEMENT_ABSTRACT_CLASS(DendrogramPanel, wxPanel) BEGIN_EVENT_TABLE(DendrogramPanel, wxPanel) EVT_MOUSE_EVENTS(DendrogramPanel::OnEvent) EVT_IDLE(DendrogramPanel::OnIdle) +EVT_PAINT(DendrogramPanel::OnPaint) END_EVENT_TABLE() -DendrogramPanel::DendrogramPanel(wxWindow* parent, wxWindowID id, const wxPoint &pos, const wxSize &size) -: wxPanel(parent, id, pos, size) +DendrogramPanel::DendrogramPanel(int _max_n_clusters, wxWindow* parent, wxWindowID id, const wxPoint &pos, const wxSize &size) +: wxPanel(parent, id, pos, size), max_n_clusters(_max_n_clusters) { SetBackgroundStyle(wxBG_STYLE_CUSTOM); SetBackgroundColour(*wxWHITE); - Connect(wxEVT_PAINT, wxPaintEventHandler(DendrogramPanel::OnPaint)); + //Connect(wxEVT_PAINT, wxPaintEventHandler(DendrogramPanel::OnPaint)); Connect(wxEVT_SIZE, wxSizeEventHandler(DendrogramPanel::OnSize)); layer_bm = NULL; root = NULL; @@ -621,6 +638,7 @@ DendrogramPanel::DendrogramPanel(wxWindow* parent, wxWindowID id, const wxPoint isMovingSplitLine= false; isLayerValid = false; maxDistance = 0.0; + isWindowActive = true; } DendrogramPanel::~DendrogramPanel() @@ -642,6 +660,11 @@ DendrogramPanel::~DendrogramPanel() } } +void DendrogramPanel::SetActive(bool flag) +{ + isWindowActive = flag; +} + void DendrogramPanel::OnEvent( wxMouseEvent& event ) { if (event.LeftDown()) { @@ -655,16 +678,26 @@ void DendrogramPanel::OnEvent( wxMouseEvent& event ) } } if (!isMovingSplitLine) { - // test end_nodes - for (int i=0;icontains(startPos)){ - // highlight i selected - wxWindow* parent = GetParent()->GetParent(); - HClusterDlg* dlg = static_cast(parent); - dlg->Highlight(end_nodes[i]->idx); - break; + // test end_nodes + if ( !event.ShiftDown() && !event.CmdDown() ) { + hl_ids.clear(); + } + for (int i=0;icontains(startPos)) { + hl_ids.push_back(end_nodes[i]->idx); + } + } + // highlight i selected + wxWindow* parent = GetParent(); + while (parent) { + wxWindow* w = parent; + HClusterDlg* dlg = dynamic_cast(w); + if (dlg) { + dlg->Highlight(hl_ids); + break; + } + parent = w->GetParent(); } - } } } else if (event.Dragging()) { if (isLeftDown) { @@ -698,10 +731,11 @@ void DendrogramPanel::OnSize( wxSizeEvent& event) void DendrogramPanel::OnIdle(wxIdleEvent& event) { - if (isResize) { + if (isResize && isWindowActive) { isResize = false; wxSize sz = GetClientSize(); + if (sz.x > 0 && sz.y > 0) { if (layer_bm) { delete layer_bm; layer_bm = 0; @@ -714,6 +748,7 @@ void DendrogramPanel::OnIdle(wxIdleEvent& event) if (root) { init(); } + } } event.Skip(); } @@ -758,7 +793,7 @@ void DendrogramPanel::Setup(GdaNode* _root, int _nelements, int _nclusters, std: cutoffDistance = _cutoff; color_vec.clear(); - CatClassification::PickColorSet(color_vec, CatClassification::unique_color_scheme, nclusters); + CatClassification::PickColorSet(color_vec, nclusters); // top Node will be nelements - 2 accessed_node.clear(); @@ -787,7 +822,7 @@ void DendrogramPanel::OnSplitLineChange(int x) } } - if (nclusters > 20) nclusters = 20; + if (nclusters > max_n_clusters) nclusters = max_n_clusters; int* clusterid = new int[nelements]; cuttree (nelements, root, nclusters, clusterid); @@ -814,22 +849,25 @@ void DendrogramPanel::OnSplitLineChange(int x) } } - wxWindow* parent = GetParent()->GetParent(); - HClusterDlg* dlg = static_cast(parent); - dlg->UpdateClusterChoice(nclusters, clusters); - - color_vec.clear(); - CatClassification::PickColorSet(color_vec, CatClassification::unique_color_scheme, nclusters); - - init(); + wxWindow* parent = GetParent(); + while (parent) { + wxWindow* w = parent; + HClusterDlg* dlg = dynamic_cast(w); + if (dlg) { + dlg->UpdateClusterChoice(nclusters, clusters); + color_vec.clear(); + CatClassification::PickColorSet(color_vec, nclusters); + init(); + break; + } + parent = w->GetParent(); + } } void DendrogramPanel::UpdateCluster(int _nclusters, std::vector& _clusters) { - nclusters = _nclusters; - int* clusterid = new int[nelements]; - cutoffDistance = cuttree (nelements, root, nclusters, clusterid); + cutoffDistance = cuttree (nelements, root, _nclusters, clusterid); for (int i=0; i& _clust delete[] clusterid; // sort result - std::vector > cluster_ids(nclusters); + std::vector > cluster_ids(_nclusters); for (int i=0; i < clusters.size(); i++) { cluster_ids[ clusters[i] - 1 ].push_back(i); @@ -845,7 +883,7 @@ void DendrogramPanel::UpdateCluster(int _nclusters, std::vector& _clust std::sort(cluster_ids.begin(), cluster_ids.end(), GenUtils::less_vectors); - for (int i=0; i < nclusters; i++) { + for (int i=0; i < _nclusters; i++) { int c = i + 1; for (int j=0; j& _clust _clusters[i] = clusters[i]; } - color_vec.clear(); - CatClassification::PickColorSet(color_vec, CatClassification::unique_color_scheme, nclusters); + if (_nclusters < max_n_clusters) { + nclusters = _nclusters; + color_vec.clear(); + CatClassification::PickColorSet(color_vec, nclusters); - init(); + init(); + } } void DendrogramPanel::init() { @@ -897,7 +938,15 @@ void DendrogramPanel::init() { int start_y = 0; accessed_node.clear(); - doDraw(dc, -(nelements-2) - 1, start_y); + + + bool draw_node = nelements < 10000; + if (draw_node) { + doDraw(dc, -(nelements-2) - 1, start_y); + } else { + wxString nodraw_msg = _("(Dendrogram is too complex to draw. Please view clustering results in map.)"); + dc.DrawText(nodraw_msg, 20, 20); + } // draw verticle line if (!isMovingSplitLine) { diff --git a/DialogTools/HClusterDlg.h b/DialogTools/HClusterDlg.h index 19a515953..306a94d47 100644 --- a/DialogTools/HClusterDlg.h +++ b/DialogTools/HClusterDlg.h @@ -26,6 +26,7 @@ #include "../FramesManager.h" #include "../VarTools.h" #include "../logger.h" +#include "AbstractClusterDlg.h" struct GdaNode; class Project; @@ -162,7 +163,7 @@ class DendrogramPanel : public wxPanel { public: //DendrogramPanel(); - DendrogramPanel(wxWindow* parent, wxWindowID id, const wxPoint &pos=wxDefaultPosition, const wxSize &size=wxDefaultSize); + DendrogramPanel(int max_n_clusters, wxWindow* parent, wxWindowID id, const wxPoint &pos=wxDefaultPosition, const wxSize &size=wxDefaultSize); virtual ~DendrogramPanel(); void OnIdle(wxIdleEvent& event); @@ -173,11 +174,17 @@ class DendrogramPanel : public wxPanel void UpdateCluster(int _nclusters, std::vector& _clusters); void OnSplitLineChange(int x); + void SetActive(bool flag); + private: + bool isWindowActive; + int leaves; int levels; int nelements; int nclusters; + + int max_n_clusters; double margin; double currentY; @@ -196,6 +203,7 @@ class DendrogramPanel : public wxPanel bool isLeftMove; bool isMovingSplitLine; wxPoint startPos; + std::vector hl_ids; std::map accessed_node; std::map level_node; @@ -218,67 +226,53 @@ class DendrogramPanel : public wxPanel DECLARE_EVENT_TABLE() }; -class HClusterDlg : public wxDialog, public FramesManagerObserver, public HighlightStateObserver +class HClusterDlg : public AbstractClusterDlg, public HighlightStateObserver { public: HClusterDlg(wxFrame *parent, Project* project); virtual ~HClusterDlg(); void CreateControls(); - bool Init(); + virtual bool Init(); void OnSave(wxCommandEvent& event ); - void OnOK( wxCommandEvent& event ); + void OnOKClick( wxCommandEvent& event ); void OnClickClose( wxCommandEvent& event ); void OnClose(wxCloseEvent& ev); void OnDistanceChoice(wxCommandEvent& event); void OnClusterChoice(wxCommandEvent& event); - + void OnNotebookChange(wxBookCtrlEvent& event); void InitVariableCombobox(wxListBox* var_box); - - /** Implementation of FramesManagerObserver interface */ - virtual void update(FramesManager* o); + void OnSpatialConstraintCheck(wxCommandEvent& event); virtual void update(HLStateInt* o); - HLStateInt* highlight_state; + virtual wxString _printConfiguration(); + + HLStateInt* highlight_state; void UpdateClusterChoice(int n, std::vector& clusters); void Highlight(int id); + void Highlight(vector& ids); - std::vector var_info; - std::vector col_ids; - -private: - wxFrame *parent; - Project* project; - TableInterface* table_int; - std::vector tm_strs; - - FramesManager* frames_manager; +protected: + int max_n_clusters; double cutoffDistance; vector clusters; vector clusters_undef; wxButton *saveButton; - wxListBox* combo_var; wxChoice* combo_n; wxChoice* combo_cov; + wxChoice* combo_weights; wxTextCtrl* m_textbox; - wxCheckBox* m_use_centroids; wxChoice* m_method; wxChoice* m_distance; DendrogramPanel* m_panel; - wxChoice* combo_tranform; - - std::map name_to_nm; - std::map name_to_tm_id; - - unsigned int row_lim; - unsigned int col_lim; - std::vector scores; - double thresh95; + wxTextCtrl* m_cluster; + wxNotebook* notebook; + wxCheckBox* chk_contiguity; DECLARE_EVENT_TABLE() }; diff --git a/DialogTools/HDBScanDlg.cpp b/DialogTools/HDBScanDlg.cpp new file mode 100644 index 000000000..17859dbb7 --- /dev/null +++ b/DialogTools/HDBScanDlg.cpp @@ -0,0 +1,629 @@ +/** + * GeoDa TM, Copyright (C) 2011-2015 by Luc Anselin - all rights reserved + * + * This file is part of GeoDa. + * + * GeoDa is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * GeoDa is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +#include "../Explore/MapNewView.h" +#include "../Project.h" +#include "../Algorithms/cluster.h" +#include "../GeneralWxUtils.h" +#include "../GenUtils.h" +#include "../Algorithms/DataUtils.h" +#include "../Algorithms/distmatrix.h" + +#include "SaveToTableDlg.h" +#include "HDBScanDlg.h" + +BEGIN_EVENT_TABLE( HDBScanDlg, wxDialog ) +EVT_CLOSE( HDBScanDlg::OnClose ) +END_EVENT_TABLE() + + +HDBScanDlg::HDBScanDlg(wxFrame* parent_s, Project* project_s) +: AbstractClusterDlg(parent_s, project_s, _("HDBScan Clustering Settings")) +{ + wxLogMessage("Open HDBScanDlg."); + + parent = parent_s; + project = project_s; + + highlight_state = project->GetHighlightState(); + + bool init_success = Init(); + + if (init_success == false) { + EndDialog(wxID_CANCEL); + } else { + CreateControls(); + } + + highlight_state->registerObserver(this); +} + +HDBScanDlg::~HDBScanDlg() +{ + highlight_state->removeObserver(this); + +} + +void HDBScanDlg::Highlight(int id) +{ + vector& hs = highlight_state->GetHighlight(); + + for (int i=0; iSetEventType(HLStateInt::delta); + highlight_state->notifyObservers(this); +} + +void HDBScanDlg::Highlight(vector& ids) +{ + vector& hs = highlight_state->GetHighlight(); + + for (int i=0; iSetEventType(HLStateInt::delta); + highlight_state->notifyObservers(this); +} + +bool HDBScanDlg::Init() +{ + if (project == NULL) + return false; + + table_int = project->GetTableInt(); + if (table_int == NULL) + return false; + + num_obs = project->GetNumRecords(); + table_int->GetTimeStrings(tm_strs); + + return true; +} + +void HDBScanDlg::CreateControls() +{ + wxScrolledWindow* scrl = new wxScrolledWindow(this, wxID_ANY, wxDefaultPosition, wxSize(880,780), wxHSCROLL|wxVSCROLL ); + scrl->SetScrollRate( 5, 5 ); + + wxPanel *panel = new wxPanel(scrl); + + // Input + wxBoxSizer *vbox = new wxBoxSizer(wxVERTICAL); + AddInputCtrls(panel, vbox); + + // Parameters + wxFlexGridSizer* gbox = new wxFlexGridSizer(10,2,5,0); + + wxStaticText* st2 = new wxStaticText(panel, wxID_ANY, _("Min cluster size:"), + wxDefaultPosition, wxDefaultSize); + wxTextValidator validator(wxFILTER_INCLUDE_CHAR_LIST); + wxArrayString list; + wxString valid_chars(".0123456789"); + size_t len = valid_chars.Length(); + for (size_t i=0; iAdd(st2, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT | wxLEFT, 10); + gbox->Add(m_minpts, 1, wxEXPAND); + + wxStaticText* st14 = new wxStaticText(panel, wxID_ANY, _("Min samples:"), + wxDefaultPosition, wxDefaultSize); + m_minsamples = new wxTextCtrl(panel, wxID_ANY, "10", wxDefaultPosition, wxSize(120, -1),0,validator); + gbox->Add(st14, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT | wxLEFT, 10); + gbox->Add(m_minsamples, 1, wxEXPAND); + + wxStaticText* st15 = new wxStaticText(panel, wxID_ANY, _("Alpha:"), + wxDefaultPosition, wxDefaultSize); + m_alpha = new wxTextCtrl(panel, wxID_ANY, "1.0", wxDefaultPosition, wxSize(120, -1),0,validator); + gbox->Add(st15, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT | wxLEFT, 10); + gbox->Add(m_alpha, 1, wxEXPAND); + + wxStaticText* st16 = new wxStaticText(panel, wxID_ANY, _("Method of selecting clusters:"), + wxDefaultPosition, wxSize(180,-1)); + wxString choices16[] = {"Excess of Mass", "Leaf"}; + m_select_method = new wxChoice(panel, wxID_ANY, wxDefaultPosition, wxSize(138,-1), 2, choices16); + m_select_method->SetSelection(0); + gbox->Add(st16, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT | wxLEFT, 10); + gbox->Add(m_select_method, 1, wxEXPAND); + + + wxStaticText* st17 = new wxStaticText(panel, wxID_ANY, _("Allow a single cluster:"), + wxDefaultPosition, wxSize(138,-1)); + chk_allowsinglecluster = new wxCheckBox(panel, wxID_ANY, ""); + gbox->Add(st17, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT | wxLEFT, 10); + gbox->Add(chk_allowsinglecluster, 1, wxEXPAND); + + // Transformation + AddTransformation(panel, gbox); + + wxStaticText* st13 = new wxStaticText(panel, wxID_ANY, _("Distance Function:"), + wxDefaultPosition, wxSize(120,-1)); + wxString choices13[] = {"Euclidean", "Manhattan"}; + wxChoice* box13 = new wxChoice(panel, wxID_ANY, wxDefaultPosition, wxSize(120,-1), 2, choices13); + box13->SetSelection(0); + gbox->Add(st13, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT | wxLEFT, 10); + gbox->Add(box13, 1, wxEXPAND); + + + wxStaticBoxSizer *hbox = new wxStaticBoxSizer(wxHORIZONTAL, panel, _("Parameters:")); + hbox->Add(gbox, 1, wxEXPAND); + + // Output + wxFlexGridSizer* gbox1 = new wxFlexGridSizer(5,2,5,0); + + /* + wxStaticText* st1 = new wxStaticText(panel, wxID_ANY, _("Number of Clusters:"), + wxDefaultPosition, wxDefaultSize); + max_n_clusters = num_obs < 60 ? num_obs : 60; + m_cluster = new wxTextCtrl(panel, wxID_ANY, "5", wxDefaultPosition, wxSize(120, -1),0,validator); + + gbox1->Add(st1, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT | wxLEFT, 10); + gbox1->Add(m_cluster, 1, wxEXPAND); + */ + + wxStaticText* st3 = new wxStaticText (panel, wxID_ANY, _("Save Cluster in Field:"), wxDefaultPosition, wxDefaultSize); + wxTextCtrl *box3 = new wxTextCtrl(panel, wxID_ANY, "CL", wxDefaultPosition, wxSize(120,-1)); + gbox1->Add(st3, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT | wxLEFT, 10); + gbox1->Add(box3, 1, wxALIGN_CENTER_VERTICAL); + + wxStaticBoxSizer *hbox1 = new wxStaticBoxSizer(wxHORIZONTAL, panel, _("Output:")); + hbox1->Add(gbox1, 1, wxEXPAND); + + // Buttons + wxButton *okButton = new wxButton(panel, wxID_OK, _("Run"), wxDefaultPosition, wxSize(70, 30)); + saveButton = new wxButton(panel, wxID_SAVE, _("Save"), wxDefaultPosition, wxDefaultSize); + wxButton *closeButton = new wxButton(panel, wxID_EXIT, _("Close"), + wxDefaultPosition, wxSize(70, 30)); + wxBoxSizer *hbox2 = new wxBoxSizer(wxHORIZONTAL); + hbox2->Add(okButton, 0, wxALIGN_CENTER | wxALL, 5); + hbox2->Add(saveButton, 0, wxALIGN_CENTER | wxALL, 5); + hbox2->Add(closeButton, 0, wxALIGN_CENTER | wxALL, 5); + + // Container + vbox->Add(hbox, 0, wxEXPAND | wxALL, 10); + vbox->Add(hbox1, 0, wxEXPAND | wxTOP | wxLEFT | wxRIGHT, 10); + vbox->Add(hbox2, 0, wxALIGN_CENTER | wxALL, 10); + + // Summary control + notebook = new wxNotebook( panel, wxID_ANY); + //m_panel = new DendrogramPanel(max_n_clusters, notebook, wxID_ANY); + //notebook->AddPage(m_panel, _("Dendrogram")); + m_reportbox = new SimpleReportTextCtrl(notebook, wxID_ANY, ""); + notebook->AddPage(m_reportbox, _("Summary")); + notebook->Connect(wxEVT_NOTEBOOK_PAGE_CHANGING, wxBookCtrlEventHandler(HDBScanDlg::OnNotebookChange), NULL, this); + + wxBoxSizer *container = new wxBoxSizer(wxHORIZONTAL); + container->Add(vbox); + container->Add(notebook,1, wxEXPAND | wxALL); + + panel->SetSizerAndFit(container); + + wxBoxSizer* panelSizer = new wxBoxSizer(wxVERTICAL); + panelSizer->Add(panel, 1, wxEXPAND|wxALL, 0); + + scrl->SetSizer(panelSizer); + + wxBoxSizer* sizerAll = new wxBoxSizer(wxVERTICAL); + sizerAll->Add(scrl, 1, wxEXPAND|wxALL, 0); + SetSizer(sizerAll); + SetAutoLayout(true); + sizerAll->Fit(this); + + Centre(); + + // Content + m_textbox = box3; + m_distance = box13; + + + // Events + okButton->Bind(wxEVT_BUTTON, &HDBScanDlg::OnOKClick, this); + saveButton->Bind(wxEVT_BUTTON, &HDBScanDlg::OnSave, this); + closeButton->Bind(wxEVT_BUTTON, &HDBScanDlg::OnClickClose, this); + //m_cluster->Connect(wxEVT_TEXT, wxCommandEventHandler(HDBScanDlg::OnClusterChoice), NULL, this); + + saveButton->Disable(); + //combo_n->Disable(); + //m_cluster->Disable(); +} + +void HDBScanDlg::OnNotebookChange(wxBookCtrlEvent& event) +{ + int tab_idx = event.GetOldSelection(); + //m_panel->SetActive(tab_idx == 1); +} + +void HDBScanDlg::OnSave(wxCommandEvent& event ) +{ + // save to table + int new_col = 3; + + std::vector new_data(new_col); + + vector undefs(rows, false); + + + new_data[0].d_val = &core_dist; + new_data[0].label = "Core Dist"; + new_data[0].field_default = "HDB_CORE"; + new_data[0].type = GdaConst::double_type; + new_data[0].undefined = &undefs; + + new_data[1].d_val = &probabilities; + new_data[1].label = "Probabilities"; + new_data[1].field_default = "HDB_PVAL"; + new_data[1].type = GdaConst::double_type; + new_data[1].undefined = &undefs; + + + new_data[2].d_val = &outliers; + new_data[2].label = "Outliers"; + new_data[2].field_default = "HDB_OUT"; + new_data[2].type = GdaConst::double_type; + new_data[2].undefined = &undefs; + + SaveToTableDlg dlg(project, this, new_data, + "Save Results: HDBScan (Core Distances/Probabilities/Outliers)", + wxDefaultPosition, wxSize(400,400)); + dlg.ShowModal(); + + event.Skip(); +} + +void HDBScanDlg::OnDistanceChoice(wxCommandEvent& event) +{ + + if (m_distance->GetSelection() == 0) { + m_distance->SetSelection(1); + } else if (m_distance->GetSelection() == 3) { + m_distance->SetSelection(4); + } else if (m_distance->GetSelection() == 6) { + m_distance->SetSelection(7); + } else if (m_distance->GetSelection() == 9) { + m_distance->SetSelection(10); + } +} + +void HDBScanDlg::OnClusterChoice(wxCommandEvent& event) +{ + //int sel_ncluster = combo_n->GetSelection() + 2; + wxString tmp_val = m_cluster->GetValue(); + tmp_val.Trim(false); + tmp_val.Trim(true); + long sel_ncluster; + bool is_valid = tmp_val.ToLong(&sel_ncluster); + if (is_valid) { + //sel_ncluster += 2; + // update dendrogram + //m_panel->UpdateCluster(sel_ncluster, clusters); + } +} + +void HDBScanDlg::UpdateClusterChoice(int n, std::vector& _clusters) +{ + //int sel = n - 2; + //combo_n->SetSelection(sel); + wxString str_n; + str_n << n; + m_cluster->SetValue(str_n); + for (int i=0; i col_id_map; + table_int->FillNumericColIdMap(col_id_map); + for (int i=0, iend=col_id_map.size(); iGetColName(id); + if (table_int->IsColTimeVariant(id)) { + for (int t=0; tGetColTimeSteps(id); t++) { + wxString nm = name; + nm << " (" << table_int->GetTimeString(t) << ")"; + name_to_nm[nm] = name; + name_to_tm_id[nm] = t; + items.Add(nm); + } + } else { + name_to_nm[name] = name; + name_to_tm_id[name] = 0; + items.Add(name); + } + } + if (!items.IsEmpty()) + var_box->InsertItems(items,0); + + for (int i=0; iSetStringSelection(select_vars[i], true); + } +} + +void HDBScanDlg::update(HLStateInt* o) +{ +} + +void HDBScanDlg::OnClickClose(wxCommandEvent& event ) +{ + wxLogMessage("OnClickClose HDBScanDlg."); + + event.Skip(); + EndDialog(wxID_CANCEL); +} + +void HDBScanDlg::OnClose(wxCloseEvent& ev) +{ + wxLogMessage("Close HDBScanDlg"); + // Note: it seems that if we don't explictly capture the close event + // and call Destory, then the destructor is not called. + Destroy(); +} + +wxString HDBScanDlg::_printConfiguration() +{ + wxString txt; + txt << "Minimum cluster size:\t" << m_minpts->GetValue() << "\n"; + txt << "Minimum samples:\t" << m_minsamples->GetValue() << "\n"; + txt << "Alpha:\t" << m_alpha->GetValue() << "\n"; + txt << "Method of selecting cluster:\t" << m_select_method->GetStringSelection() << "\n"; + wxString single_cluster = chk_allowsinglecluster->IsChecked() ? "Yes" : "No"; + txt << "Allow a single cluster:\t" << single_cluster << "\n"; + txt << "Transformation:\t" << combo_tranform->GetString(combo_tranform->GetSelection()) << "\n"; + txt << "Distance function:\t" << m_distance->GetString(m_distance->GetSelection()) << "\n"; + txt << "Number of clusters (output):\t" << cluster_ids.size() << "\n"; + + return txt; +} + +void HDBScanDlg::OnOKClick(wxCommandEvent& event ) +{ + wxLogMessage("Click HDBScanDlg::OnOK"); + + long minPts = 0; + m_minpts->GetValue().ToLong(&minPts); + if (minPts<=1) { + wxString err_msg = _("Minimum cluster size should be greater than one."); + wxMessageDialog dlg(NULL, err_msg, _("Warning"), wxOK | wxICON_WARNING); + dlg.ShowModal(); + return; + } + + int transform = combo_tranform->GetSelection(); + bool success = GetInputData(transform,1); + if (!success) { + return; + } + + char method = 's'; + char dist = 'e'; + + int transpose = 0; // row wise + + int dist_sel = m_distance->GetSelection(); + char dist_choices[] = {'e','b'}; + dist = dist_choices[dist_sel]; + + long minSamples = 10; + m_minsamples->GetValue().ToLong(&minSamples); + if (minSamples<=1) { + wxString err_msg = _("Minimum samples should be greater than zero."); + wxMessageDialog dlg(NULL, err_msg, _("Warning"), wxOK | wxICON_WARNING); + dlg.ShowModal(); + return; + } + + double alpha = 1; + m_alpha->GetValue().ToDouble(&alpha); + + int cluster_selection_method = m_select_method->GetSelection(); + bool allow_single_cluster = chk_allowsinglecluster->IsChecked(); + + clusters.clear(); + clusters_undef.clear(); + + + // 3gb 3*1024*1024/4 = 786432 + unsigned long long total_pairs = rows * rows; + int block_size = total_pairs / 780000; + + /* + wxString exePath = GenUtils::GetBasemapCacheDir(); + wxString clPath = exePath + "distmat_kernel.cl"; + float* r = gpu_distmatrix(clPath.mb_str(), rows, columns, input_data); + double** _distances = new double*[rows]; + unsigned long long idx; + unsigned long long _row = rows; + for (unsigned long long i=0; i clusters(rows, 0); + vector clusters_undef(rows, false); + + // sort result + std::sort(cluster_ids.begin(), cluster_ids.end(), GenUtils::less_vectors); + + for (int i=0; i < ncluster; i++) { + int c = i + 1; + for (int j=0; jGetValue(); + if (field_name.IsEmpty()) { + wxString err_msg = _("Please enter a field name for saving clustering results."); + wxMessageDialog dlg(NULL, err_msg, _("Error"), wxOK | wxICON_ERROR); + dlg.ShowModal(); + return; + } + + int time=0; + int col = table_int->FindColId(field_name); + if ( col == wxNOT_FOUND) { + int col_insert_pos = table_int->GetNumberCols(); + int time_steps = 1; + int m_length_val = GdaConst::default_dbf_long_len; + int m_decimals_val = 0; + + col = table_int->InsertCol(GdaConst::long64_type, field_name, col_insert_pos, time_steps, m_length_val, m_decimals_val); + } else { + // detect if column is integer field, if not raise a warning + if (table_int->GetColType(col) != GdaConst::long64_type ) { + wxString msg = _("This field name already exists (non-integer type). Please input a unique name."); + wxMessageDialog dlg(this, msg, _("Warning"), wxOK | wxICON_WARNING ); + dlg.ShowModal(); + return; + } + } + + if (col > 0) { + table_int->SetColData(col, time, clusters); + table_int->SetColUndefined(col, time, clusters_undef); + } + + // free memory + for (int i = 1; i < rows; i++) free(distances[i]); + free(distances); + + //delete[] bound_vals; + //bound_vals = NULL; + + // show a cluster map + if (project->IsTableOnlyProject()) { + return; + } + std::vector new_var_info; + std::vector new_col_ids; + new_col_ids.resize(1); + new_var_info.resize(1); + new_col_ids[0] = col; + new_var_info[0].time = 0; + // Set Primary GdaVarTools::VarInfo attributes + new_var_info[0].name = field_name; + new_var_info[0].is_time_variant = table_int->IsColTimeVariant(col); + table_int->GetMinMaxVals(new_col_ids[0], new_var_info[0].min, new_var_info[0].max); + new_var_info[0].sync_with_global_time = new_var_info[0].is_time_variant; + new_var_info[0].fixed_scale = true; + + + MapFrame* nf = new MapFrame(parent, project, + new_var_info, new_col_ids, + CatClassification::unique_values, + MapCanvas::no_smoothing, 4, + boost::uuids::nil_uuid(), + wxDefaultPosition, + GdaConst::map_default_size); + wxString ttl; + ttl << "HDBScan " << _("Cluster Map ") << "("; + ttl << cluster_ids.size(); + ttl << " clusters)"; + nf->SetTitle(ttl); + + if (not_clustered>0) { + nf->SetLegendLabel(0, _("Not Clustered")); + } + + saveButton->Enable(); + + // draw dendrogram + // GdaNode* _root, int _nelements, int _nclusters, std::vector& _clusters, double _cutoff + /*double** sltree =hdb.single_linkage_tree; + GdaNode* htree = new GdaNode[rows-1]; + + for (int i=0; iSetup(htree, rows, not_clustered > 0 ? ncluster +1 : ncluster, clusters, 0); + // free(htree); should be freed in m_panel since drawing still needs it's instance + */ + + saveButton->Enable(); + //m_cluster->Enable(); +} diff --git a/DialogTools/HDBScanDlg.h b/DialogTools/HDBScanDlg.h new file mode 100644 index 000000000..d9ea59773 --- /dev/null +++ b/DialogTools/HDBScanDlg.h @@ -0,0 +1,95 @@ +/** + * GeoDa TM, Copyright (C) 2011-2015 by Luc Anselin - all rights reserved + * + * This file is part of GeoDa. + * + * GeoDa is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * GeoDa is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#ifndef __GEODA_CENTER_HDBSCAN_DLG_H___ +#define __GEODA_CENTER_HDBSCAN_DLG_H___ + +#include +#include + +#include "../FramesManager.h" +#include "../VarTools.h" +#include "../logger.h" +#include "HClusterDlg.h" +#include "AbstractClusterDlg.h" +#include "../Algorithms/hdbscan.h" + +struct GdaNode; +class Project; +class TableInterface; + + +class HDBScanDlg : public AbstractClusterDlg, public HighlightStateObserver +{ +public: + HDBScanDlg(wxFrame *parent, Project* project); + virtual ~HDBScanDlg(); + + void CreateControls(); + virtual bool Init(); + + void OnSave(wxCommandEvent& event ); + void OnOKClick( wxCommandEvent& event ); + void OnClickClose( wxCommandEvent& event ); + void OnClose(wxCloseEvent& ev); + void OnDistanceChoice(wxCommandEvent& event); + void OnClusterChoice(wxCommandEvent& event); + void OnNotebookChange(wxBookCtrlEvent& event); + void InitVariableCombobox(wxListBox* var_box); + + virtual void update(HLStateInt* o); + + virtual wxString _printConfiguration(); + + HLStateInt* highlight_state; + + void UpdateClusterChoice(int n, std::vector& clusters); + void Highlight(int id); + void Highlight(vector& ids); + +protected: + vector core_dist; + vector probabilities; + vector outliers; + vector > cluster_ids; + + int max_n_clusters; + + double cutoffDistance; + vector clusters; + vector clusters_undef; + + wxButton *saveButton; + wxChoice* combo_n; + wxChoice* combo_cov; + wxTextCtrl* m_textbox; + wxChoice* m_distance; + DendrogramPanel* m_panel; + wxTextCtrl* m_minpts; + wxTextCtrl* m_minsamples; + wxTextCtrl* m_alpha; + wxTextCtrl* m_cluster; + wxNotebook* notebook; + wxChoice* m_select_method; + wxCheckBox* chk_allowsinglecluster; + + DECLARE_EVENT_TABLE() +}; + +#endif diff --git a/DialogTools/KMeansDlg.cpp b/DialogTools/KMeansDlg.cpp index 9f54f6588..aea0e9655 100644 --- a/DialogTools/KMeansDlg.cpp +++ b/DialogTools/KMeansDlg.cpp @@ -22,6 +22,9 @@ #include #include +#include +#include + #include #include #include @@ -46,102 +49,58 @@ #include "KMeansDlg.h" -BEGIN_EVENT_TABLE( KMeansDlg, wxDialog ) -EVT_CLOSE( KMeansDlg::OnClose ) +BEGIN_EVENT_TABLE( KClusterDlg, wxDialog ) +EVT_CLOSE( KClusterDlg::OnClose ) END_EVENT_TABLE() -KMeansDlg::KMeansDlg(wxFrame* parent_s, Project* project_s) -: frames_manager(project_s->GetFramesManager()), -wxDialog(NULL, -1, _("K-Means Settings"), wxDefaultPosition, wxDefaultSize, - wxDEFAULT_DIALOG_STYLE|wxRESIZE_BORDER) +KClusterDlg::KClusterDlg(wxFrame* parent_s, Project* project_s, wxString title) +: AbstractClusterDlg(parent_s, project_s, title) { - wxLogMessage("Open KMeanDlg."); - - SetMinSize(wxSize(360,750)); - - parent = parent_s; - project = project_s; - - bool init_success = Init(); - - if (init_success == false) { - EndDialog(wxID_CANCEL); - } else { - CreateControls(); - } - frames_manager->registerObserver(this); -} - -KMeansDlg::~KMeansDlg() -{ - frames_manager->removeObserver(this); -} - -bool KMeansDlg::Init() -{ - if (project == NULL) - return false; - - table_int = project->GetTableInt(); - if (table_int == NULL) - return false; - - - table_int->GetTimeStrings(tm_strs); - - return true; + wxLogMessage("In KClusterDlg()"); + distmatrix = NULL; + show_iteration = true; } -void KMeansDlg::update(FramesManager* o) +KClusterDlg::~KClusterDlg() { - + wxLogMessage("In ~KClusterDlg()"); } -void KMeansDlg::CreateControls() +void KClusterDlg::CreateControls() { - wxPanel *panel = new wxPanel(this); + wxScrolledWindow* scrl = new wxScrolledWindow(this, wxID_ANY, wxDefaultPosition, wxSize(880,820), wxHSCROLL|wxVSCROLL ); + scrl->SetScrollRate( 5, 5 ); + wxPanel *panel = new wxPanel(scrl); wxBoxSizer *vbox = new wxBoxSizer(wxVERTICAL); // Input - wxStaticText* st = new wxStaticText (panel, wxID_ANY, _("Select Variables"), - wxDefaultPosition, wxDefaultSize); - - wxListBox* box = new wxListBox(panel, wxID_ANY, wxDefaultPosition, - wxSize(250,250), 0, NULL, - wxLB_MULTIPLE | wxLB_HSCROLL| wxLB_NEEDED_SB); - wxCheckBox* cbox = new wxCheckBox(panel, wxID_ANY, _("Use Geometric Centroids")); - wxStaticBoxSizer *hbox0 = new wxStaticBoxSizer(wxVERTICAL, panel, "Input:"); - hbox0->Add(st, 0, wxALIGN_CENTER | wxLEFT | wxRIGHT, 10); - hbox0->Add(box, 1, wxEXPAND | wxLEFT | wxRIGHT | wxBOTTOM, 10); - hbox0->Add(cbox, 0, wxLEFT | wxRIGHT, 10); + AddInputCtrls(panel, vbox, true); - if (project->IsTableOnlyProject()) { - cbox->Disable(); - } // Parameters wxFlexGridSizer* gbox = new wxFlexGridSizer(9,2,5,0); - - wxString choices[] = {"2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20"}; - wxStaticText* st1 = new wxStaticText(panel, wxID_ANY, _("Number of Clusters:"), + // NumberOfCluster Control + wxStaticText* st1 = new wxStaticText(panel, wxID_ANY, + _("Number of Clusters:"), wxDefaultPosition, wxSize(128,-1)); - wxChoice* box1 = new wxChoice(panel, wxID_ANY, wxDefaultPosition, - wxSize(200,-1), 9, choices); - box1->SetSelection(3); + combo_n = new wxChoice(panel, wxID_ANY, wxDefaultPosition, wxSize(200,-1), 0, NULL); + max_n_clusters = num_obs < 60 ? num_obs : 60; + for (int i=2; iAppend(wxString::Format("%d", i)); + combo_n->SetSelection(3); gbox->Add(st1, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT | wxLEFT, 10); - gbox->Add(box1, 1, wxEXPAND); - - wxStaticText* st14 = new wxStaticText(panel, wxID_ANY, _("Transformation:"), - wxDefaultPosition, wxSize(120,-1)); - const wxString _transform[3] = {"Raw", "Demean", "Standardize"}; - wxChoice* box01 = new wxChoice(panel, wxID_ANY, wxDefaultPosition, - wxSize(120,-1), 3, _transform); - box01->SetSelection(2); - gbox->Add(st14, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT | wxLEFT, 10); - gbox->Add(box01, 1, wxEXPAND); - - wxStaticText* st16 = new wxStaticText(panel, wxID_ANY, _("Initialization Method:"), + gbox->Add(combo_n, 1, wxEXPAND); + + // Minimum Bound Control + AddMinBound(panel, gbox); + + // Transformation Control + AddTransformation(panel, gbox); + + // Initialization Method + wxStaticText* st16 = new wxStaticText(panel, wxID_ANY, + _("Initialization Method:"), wxDefaultPosition, wxSize(128,-1)); wxString choices16[] = {"KMeans++", "Random"}; combo_method = new wxChoice(panel, wxID_ANY, wxDefaultPosition, @@ -150,19 +109,26 @@ void KMeansDlg::CreateControls() gbox->Add(st16, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT | wxLEFT, 10); gbox->Add(combo_method, 1, wxEXPAND); - - wxStaticText* st10 = new wxStaticText(panel, wxID_ANY, _("Initialization Re-runs:"), + if (!show_initmethod) { + st16->Hide(); + combo_method->Hide(); + combo_method->SetSelection(1); // use Random if hide init + } + + wxStaticText* st10 = new wxStaticText(panel, wxID_ANY, + _("Initialization Re-runs:"), wxDefaultPosition, wxSize(128,-1)); - wxTextCtrl *box10 = new wxTextCtrl(panel, wxID_ANY, wxT("50"), wxDefaultPosition, wxSize(200,-1)); + m_pass = new wxTextCtrl(panel, wxID_ANY, "150", wxDefaultPosition, wxSize(200,-1)); gbox->Add(st10, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT | wxLEFT, 10); - gbox->Add(box10, 1, wxEXPAND); + gbox->Add(m_pass, 1, wxEXPAND); - wxStaticText* st17 = new wxStaticText(panel, wxID_ANY, _("Use specified seed:"), + wxStaticText* st17 = new wxStaticText(panel, wxID_ANY, + _("Use specified seed:"), wxDefaultPosition, wxSize(128,-1)); wxBoxSizer *hbox17 = new wxBoxSizer(wxHORIZONTAL); chk_seed = new wxCheckBox(panel, wxID_ANY, ""); - seedButton = new wxButton(panel, wxID_OK, wxT("Change Seed")); + seedButton = new wxButton(panel, wxID_OK, _("Change Seed")); hbox17->Add(chk_seed,0, wxALIGN_CENTER_VERTICAL); hbox17->Add(seedButton,0,wxALIGN_CENTER_VERTICAL); @@ -171,107 +137,112 @@ void KMeansDlg::CreateControls() gbox->Add(hbox17, 1, wxEXPAND); if (GdaConst::use_gda_user_seed) { - setrandomstate(GdaConst::gda_user_seed); chk_seed->SetValue(true); seedButton->Enable(); } - wxStaticText* st11 = new wxStaticText(panel, wxID_ANY, _("Maximal Iterations:"), + wxStaticText* st11 = new wxStaticText(panel, wxID_ANY, + _("Maximal Iterations:"), wxDefaultPosition, wxSize(128,-1)); - wxTextCtrl *box11 = new wxTextCtrl(panel, wxID_ANY, wxT("300"), wxDefaultPosition, wxSize(200,-1)); + m_iterations = new wxTextCtrl(panel, wxID_ANY, "1000", wxDefaultPosition, wxSize(200,-1)); gbox->Add(st11, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT | wxLEFT, 10); - gbox->Add(box11, 1, wxEXPAND); + gbox->Add(m_iterations, 1, wxEXPAND); - wxStaticText* st12 = new wxStaticText(panel, wxID_ANY, _("Method:"), - wxDefaultPosition, wxSize(128,-1)); - wxString choices12[] = {"Arithmetic Mean", "Arithmetic Median"}; - wxChoice* box12 = new wxChoice(panel, wxID_ANY, wxDefaultPosition, - wxSize(200,-1), 2, choices12); - box12->SetSelection(0); - gbox->Add(st12, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT | wxLEFT, 10); - gbox->Add(box12, 1, wxEXPAND); - - wxStaticText* st13 = new wxStaticText(panel, wxID_ANY, _("Distance Function:"), + if (!show_iteration) { + st11->Hide(); + m_iterations->Hide(); + } + + wxStaticText* st13 = new wxStaticText(panel, wxID_ANY, + _("Distance Function:"), wxDefaultPosition, wxSize(128,-1)); - wxString choices13[] = {"Distance", "--Euclidean", "--City-block", "Correlation", "--Pearson","--Absolute Pearson", "Cosine", "--Signed", "--Un-signed", "Rank", "--Spearman", "--Kendal"}; - wxChoice* box13 = new wxChoice(panel, wxID_ANY, wxDefaultPosition, wxSize(200,-1), 12, choices13); - box13->SetSelection(1); + wxString choices13[] = {"Euclidean", "Manhattan"}; + m_distance = new wxChoice(panel, wxID_ANY, wxDefaultPosition, wxSize(200,-1), 2, choices13); + m_distance->SetSelection(0); gbox->Add(st13, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT | wxLEFT, 10); - gbox->Add(box13, 1, wxEXPAND); + gbox->Add(m_distance, 1, wxEXPAND); + if (!show_distance) { + st13->Hide(); + m_distance->Hide(); + m_distance->SetSelection(1); // set manhattan + } - - wxStaticBoxSizer *hbox = new wxStaticBoxSizer(wxHORIZONTAL, panel, "Parameters:"); + wxStaticBoxSizer *hbox = new wxStaticBoxSizer(wxHORIZONTAL, panel, _("Parameters:")); hbox->Add(gbox, 1, wxEXPAND); // Output wxStaticText* st3 = new wxStaticText (panel, wxID_ANY, _("Save Cluster in Field:"), wxDefaultPosition, wxDefaultSize); - wxTextCtrl *box3 = new wxTextCtrl(panel, wxID_ANY, wxT(""), wxDefaultPosition, wxSize(158,-1)); - wxStaticBoxSizer *hbox1 = new wxStaticBoxSizer(wxHORIZONTAL, panel, "Output:"); + m_textbox = new wxTextCtrl(panel, wxID_ANY, "CL", wxDefaultPosition, wxSize(158,-1)); + wxStaticBoxSizer *hbox1 = new wxStaticBoxSizer(wxHORIZONTAL, panel, _("Output:")); //wxBoxSizer *hbox1 = new wxBoxSizer(wxHORIZONTAL); hbox1->Add(st3, 0, wxALIGN_CENTER_VERTICAL); - hbox1->Add(box3, 1, wxALIGN_CENTER_VERTICAL); - + hbox1->Add(m_textbox, 1, wxALIGN_CENTER_VERTICAL | wxLEFT, 5); // Buttons - wxButton *okButton = new wxButton(panel, wxID_OK, wxT("Run"), wxDefaultPosition, - wxSize(70, 30)); - //wxButton *saveButton = new wxButton(panel, wxID_SAVE, wxT("Save"), wxDefaultPosition, wxSize(70, 30)); - wxButton *closeButton = new wxButton(panel, wxID_EXIT, wxT("Close"), - wxDefaultPosition, wxSize(70, 30)); + wxButton *okButton = new wxButton(panel, wxID_OK, _("Run"), wxDefaultPosition, wxSize(70, 30)); + wxButton *closeButton = new wxButton(panel, wxID_EXIT, _("Close"), wxDefaultPosition, wxSize(70, 30)); wxBoxSizer *hbox2 = new wxBoxSizer(wxHORIZONTAL); hbox2->Add(okButton, 1, wxALIGN_CENTER | wxALL, 5); - //hbox2->Add(saveButton, 1, wxALIGN_CENTER | wxALL, 5); hbox2->Add(closeButton, 1, wxALIGN_CENTER | wxALL, 5); // Container - vbox->Add(hbox0, 1, wxEXPAND | wxALL, 10); vbox->Add(hbox, 0, wxALIGN_CENTER | wxALL, 10); - vbox->Add(hbox1, 0, wxALIGN_CENTER | wxTOP | wxLEFT | wxRIGHT, 10); + vbox->Add(hbox1, 0, wxEXPAND | wxTOP | wxLEFT | wxRIGHT, 10); vbox->Add(hbox2, 0, wxALIGN_CENTER | wxALL, 10); + - + // Summary control + wxBoxSizer *vbox1 = new wxBoxSizer(wxVERTICAL); + wxNotebook* notebook = AddSimpleReportCtrls(panel); + vbox1->Add(notebook, 1, wxEXPAND|wxALL,20); + wxBoxSizer *container = new wxBoxSizer(wxHORIZONTAL); container->Add(vbox); + container->Add(vbox1, 1, wxEXPAND | wxALL); panel->SetSizer(container); + wxBoxSizer* panelSizer = new wxBoxSizer(wxVERTICAL); + panelSizer->Add(panel, 1, wxEXPAND|wxALL, 0); + + scrl->SetSizer(panelSizer); + wxBoxSizer* sizerAll = new wxBoxSizer(wxVERTICAL); - sizerAll->Add(panel, 1, wxEXPAND|wxALL, 0); + sizerAll->Add(scrl, 1, wxEXPAND|wxALL, 0); SetSizer(sizerAll); SetAutoLayout(true); sizerAll->Fit(this); - Centre(); - - - // Content - InitVariableCombobox(box); - combo_n = box1; - m_textbox = box3; - combo_var = box; - m_use_centroids = cbox; - m_iterations = box11; - m_pass = box10; - m_method = box12; - m_distance = box13; - combo_tranform = box01; - // Events - okButton->Bind(wxEVT_BUTTON, &KMeansDlg::OnOK, this); - closeButton->Bind(wxEVT_BUTTON, &KMeansDlg::OnClickClose, this); - chk_seed->Bind(wxEVT_CHECKBOX, &KMeansDlg::OnSeedCheck, this); - seedButton->Bind(wxEVT_BUTTON, &KMeansDlg::OnChangeSeed, this); - - m_distance->Connect(wxEVT_CHOICE, - wxCommandEventHandler(KMeansDlg::OnDistanceChoice), - NULL, this); + okButton->Bind(wxEVT_BUTTON, &KClusterDlg::OnOK, this); + closeButton->Bind(wxEVT_BUTTON, &KClusterDlg::OnClickClose, this); + chk_seed->Bind(wxEVT_CHECKBOX, &KClusterDlg::OnSeedCheck, this); + seedButton->Bind(wxEVT_BUTTON, &KClusterDlg::OnChangeSeed, this); + combo_method->Bind(wxEVT_CHOICE, &KClusterDlg::OnInitMethodChoice, this); + m_distance->Bind(wxEVT_CHOICE, &KClusterDlg::OnDistanceChoice, this); +} + +void KClusterDlg::OnDistanceChoice(wxCommandEvent& event) +{ + if (m_distance->GetSelection() == 1) { + // when Manhattan + // make sure KMedian and KMedoids is select + } } -void KMeansDlg::OnSeedCheck(wxCommandEvent& event) +void KClusterDlg::OnInitMethodChoice(wxCommandEvent& event) +{ + if (combo_method->GetSelection()== 0) { + // when KMeans++ + // make sure no KMedian is select + } +} + +void KClusterDlg::OnSeedCheck(wxCommandEvent& event) { bool use_user_seed = chk_seed->GetValue(); @@ -282,27 +253,30 @@ void KMeansDlg::OnSeedCheck(wxCommandEvent& event) return; } GdaConst::use_gda_user_seed = true; - setrandomstate(GdaConst::gda_user_seed); OGRDataAdapter& ogr_adapt = OGRDataAdapter::GetInstance(); ogr_adapt.AddEntry("use_gda_user_seed", "1"); } else { + GdaConst::use_gda_user_seed = false; + OGRDataAdapter& ogr_adapt = OGRDataAdapter::GetInstance(); + ogr_adapt.AddEntry("use_gda_user_seed", "0"); + seedButton->Disable(); } } -void KMeansDlg::OnChangeSeed(wxCommandEvent& event) +void KClusterDlg::OnChangeSeed(wxCommandEvent& event) { // prompt user to enter user seed (used globally) wxString m; - m << "Enter a seed value for random number generator:"; + m << _("Enter a seed value for random number generator:"); long long unsigned int val; wxString dlg_val; wxString cur_val; cur_val << GdaConst::gda_user_seed; - wxTextEntryDialog dlg(NULL, m, "Enter a seed value", cur_val); + wxTextEntryDialog dlg(NULL, m, _("Enter a seed value"), cur_val); if (dlg.ShowModal() != wxID_OK) return; dlg_val = dlg.GetValue(); dlg_val.Trim(true); @@ -312,7 +286,6 @@ void KMeansDlg::OnChangeSeed(wxCommandEvent& event) uint64_t new_seed_val = val; GdaConst::gda_user_seed = new_seed_val; GdaConst::use_gda_user_seed = true; - setrandomstate(GdaConst::gda_user_seed); OGRDataAdapter& ogr_adapt = OGRDataAdapter::GetInstance(); wxString str_gda_user_seed; @@ -320,9 +293,9 @@ void KMeansDlg::OnChangeSeed(wxCommandEvent& event) ogr_adapt.AddEntry("gda_user_seed", str_gda_user_seed.ToStdString()); ogr_adapt.AddEntry("use_gda_user_seed", "1"); } else { - wxString m; - m << "\"" << dlg_val << "\" is not a valid seed. Seed unchanged."; - wxMessageDialog dlg(NULL, m, "Error", wxOK | wxICON_ERROR); + wxString m = _("\"%s\" is not a valid seed. Seed unchanged."); + m = wxString::Format(m, dlg_val); + wxMessageDialog dlg(NULL, m, _("Error"), wxOK | wxICON_ERROR); dlg.ShowModal(); GdaConst::use_gda_user_seed = false; OGRDataAdapter& ogr_adapt = OGRDataAdapter::GetInstance(); @@ -330,260 +303,285 @@ void KMeansDlg::OnChangeSeed(wxCommandEvent& event) } } -void KMeansDlg::OnDistanceChoice(wxCommandEvent& event) -{ - - if (m_distance->GetSelection() == 0) { - m_distance->SetSelection(1); - } else if (m_distance->GetSelection() == 3) { - m_distance->SetSelection(4); - } else if (m_distance->GetSelection() == 6) { - m_distance->SetSelection(7); - } else if (m_distance->GetSelection() == 9) { - m_distance->SetSelection(10); - } -} - -void KMeansDlg::InitVariableCombobox(wxListBox* var_box) -{ - wxArrayString items; - - std::vector col_id_map; - table_int->FillNumericColIdMap(col_id_map); - for (int i=0, iend=col_id_map.size(); iGetColName(id); - if (table_int->IsColTimeVariant(id)) { - for (int t=0; tGetColTimeSteps(id); t++) { - wxString nm = name; - nm << " (" << table_int->GetTimeString(t) << ")"; - name_to_nm[nm] = name; - name_to_tm_id[nm] = t; - items.Add(nm); - } - } else { - name_to_nm[name] = name; - name_to_tm_id[name] = 0; - items.Add(name); - } - } - - var_box->InsertItems(items,0); -} - -void KMeansDlg::OnClickClose(wxCommandEvent& event ) +void KClusterDlg::OnClickClose(wxCommandEvent& event ) { - wxLogMessage("OnClickClose KMeansDlg."); + wxLogMessage("OnClickClose KClusterDlg."); event.Skip(); EndDialog(wxID_CANCEL); Destroy(); } -void KMeansDlg::OnClose(wxCloseEvent& ev) +void KClusterDlg::OnClose(wxCloseEvent& ev) { - wxLogMessage("Close HClusterDlg"); + wxLogMessage("Close KClusterDlg"); // Note: it seems that if we don't explictly capture the close event // and call Destory, then the destructor is not called. Destroy(); } -void KMeansDlg::OnOK(wxCommandEvent& event ) +wxString KClusterDlg::_printConfiguration() { - wxLogMessage("Click KMeansDlg::OnOK"); + wxString txt; + txt << _("Method:\t") << cluster_method << "\n"; + txt << _("Number of clusters:\t") << combo_n->GetSelection() + 2 << "\n"; + txt << _("Initialization method:\t") << combo_method->GetString(combo_method->GetSelection()) << "\n"; + txt << _("Initialization re-runs:\t") << m_pass->GetValue() << "\n"; + txt << _("Maximum iterations:\t") << m_iterations->GetValue() << "\n"; + + if (chk_floor && chk_floor->IsChecked()) { + int idx = combo_floor->GetSelection(); + wxString nm = name_to_nm[combo_floor->GetString(idx)]; + txt << _("Minimum bound:\t") << txt_floor->GetValue() << "(" << nm << ")" << "\n"; + } - int ncluster = combo_n->GetSelection() + 2; + txt << _("Transformation:\t") << combo_tranform->GetString(combo_tranform->GetSelection()) << "\n"; + + txt << _("Distance function:\t") << m_distance->GetString(m_distance->GetSelection()) << "\n"; - bool use_centroids = m_use_centroids->GetValue(); + return txt; +} + +void KClusterDlg::ComputeDistMatrix(int dist_sel) +{ - wxArrayInt selections; - combo_var->GetSelections(selections); +} + +bool KClusterDlg::CheckContiguity(double w, double& ssd) +{ + int val = w * 100; + m_weight_centroids->SetValue(val); + m_wc_txt->SetValue(wxString::Format("%f", w)); - int num_var = selections.size(); - if (num_var < 2 && !use_centroids) { - // show message box - wxString err_msg = _("Please select at least 2 variables."); - wxMessageDialog dlg(NULL, err_msg, "Info", wxOK | wxICON_ERROR); - dlg.ShowModal(); - return; + vector clusters; + if (Run(clusters) == false) { + m_weight_centroids->SetValue(100); + m_wc_txt->SetValue("1.0"); + return false; } - - wxString field_name = m_textbox->GetValue(); - if (field_name.IsEmpty()) { - wxString err_msg = _("Please enter a field name for saving clustering results."); - wxMessageDialog dlg(NULL, err_msg, "Error", wxOK | wxICON_ERROR); - dlg.ShowModal(); - return; + + // not show print + ssd = CreateSummary(clusters, false); + + if (GetDefaultContiguity() == false) + return false; + + map > groups; + map >::iterator it; + for (int i=0; i g; + g.insert(i); + groups[c] = g; + } else { + groups[c].insert(i); + } } - col_ids.resize(num_var); - var_info.resize(num_var); - - for (int i=0; iGetString(idx)]; - - int col = table_int->FindColId(nm); - if (col == wxNOT_FOUND) { - wxString err_msg = wxString::Format(_("Variable %s is no longer in the Table. Please close and reopen the Regression Dialog to synchronize with Table data."), nm); - wxMessageDialog dlg(NULL, err_msg, "Error", wxOK | wxICON_ERROR); - dlg.ShowModal(); - return; + bool is_cont = true; + set::iterator item_it; + for (it = groups.begin(); it != groups.end(); it++) { + // check each group if contiguity + set g = it->second; + for (item_it=g.begin(); item_it!=g.end(); item_it++) { + int idx = *item_it; + const vector& nbrs = gal[idx].GetNbrs(); + bool not_in_group = true; + for (int i=0; iGetString(idx)]; - - col_ids[i] = col; - var_info[i].time = tm; - - // Set Primary GdaVarTools::VarInfo attributes - var_info[i].name = nm; - var_info[i].is_time_variant = table_int->IsColTimeVariant(idx); - - // var_info[i].time already set above - table_int->GetMinMaxVals(col_ids[i], var_info[i].min, var_info[i].max); - var_info[i].sync_with_global_time = var_info[i].is_time_variant; - var_info[i].fixed_scale = true; + if (!is_cont) + break; } - // Call function to set all Secondary Attributes based on Primary Attributes - GdaVarTools::UpdateVarInfoSecondaryAttribs(var_info); + return is_cont; +} + +void KClusterDlg::BinarySearch(double left, double right, std::vector >& ssd_pairs) +{ + double delta = right - left; + + if ( delta < 0.01 ) + return; + + double mid = left + delta /2.0; - int rows = project->GetNumRecords(); - int columns = 0; + // assume left is always not contiguity and right is always contiguity + //bool l_conti = CheckContiguity(left); + double m_ssd = 0; + bool m_conti = CheckContiguity(mid, m_ssd); - std::vector data; // data[variable][time][obs] - data.resize(col_ids.size()); - for (int i=0; iGetColData(col_ids[i], data[i]); + if ( m_conti ) { + ssd_pairs.push_back( std::make_pair(mid, m_ssd) ); + return BinarySearch(left, mid, ssd_pairs); + + } else { + return BinarySearch(mid, right, ssd_pairs); } - // get columns (if time variables show) - for (int i=0; i > ssd_pairs; + BinarySearch(0.0, 1.0, ssd_pairs); + + if (ssd_pairs.empty()) return; + + double w = ssd_pairs[0].first; + double ssd = ssd_pairs[0].second; + + for (int i=1; i ssd) { + ssd = ssd_pairs[i].second; + w = ssd_pairs[i].first; } } - // if use centroids - if (use_centroids) { - columns += 2; + int val = w * 100; + m_weight_centroids->SetValue(val); + m_wc_txt->SetValue(wxString::Format("%f", w)); +} + +bool KClusterDlg::Run(vector& clusters) +{ + if (GdaConst::use_gda_user_seed) { + setrandomstate(GdaConst::gda_user_seed); + resetrandom(); + } else { + setrandomstate(-1); + resetrandom(); } + int ncluster = combo_n->GetSelection() + 2; int transform = combo_tranform->GetSelection(); - char method = 'a'; // mean, 'm' median - char dist = 'e'; // euclidean + + if (!GetInputData(transform,1)) + return false; + + if (!CheckMinBound()) + return false; + int npass = 10; - int n_maxiter = 300; // max iteration of EM - int transpose = 0; // row wise - int* clusterid = new int[rows]; - double* weight = new double[columns]; - for (int j=0; jGetValue(); + long value_pass; + if(str_pass.ToLong(&value_pass)) { + npass = value_pass; + } + int n_maxiter = 300; // max iteration of EM wxString iterations = m_iterations->GetValue(); long value; if(iterations.ToLong(&value)) { n_maxiter = value; } - if (combo_method->GetSelection() == 0) method = 'b'; // mean with kmeans++ + int meth_sel = combo_method->GetSelection(); - wxString str_pass = m_pass->GetValue(); - long value_pass; - if(str_pass.ToLong(&value_pass)) { - npass = value_pass; - } + // start working + int nCPUs = boost::thread::hardware_concurrency(); + int quotient = npass / nCPUs; + int remainder = npass % nCPUs; + int tot_threads = (quotient > 0) ? nCPUs : remainder; - int method_sel = m_method->GetSelection(); - if (method_sel == 1) method = 'm'; + map >::iterator it; + for (it=sub_clusters.begin(); it!=sub_clusters.end(); it++) { + it->second.clear(); + } + sub_clusters.clear(); int dist_sel = m_distance->GetSelection(); - char dist_choices[] = {'e','e','b','c','c','a','u','u','x','s','s','k'}; - dist = dist_choices[dist_sel]; - // init input_data[rows][cols] - double** input_data = new double*[rows]; - int** mask = new int*[rows]; - for (int i=0; i vals; - - for (int k=0; k< rows;k++) { // row - vals.push_back(data[i][j][k]); - } - - if (transform == 2) { - GenUtils::StandardizeData(vals); - } else if (transform == 1 ) { - GenUtils::DeviationFromMean(vals); - } - - for (int k=0; k< rows;k++) { // row - input_data[k][col_ii] = vals[k]; - } - col_ii += 1; + boost::thread_group threadPool; + for (int i=0; i cents = project->GetCentroids(); - std::vector cent_xs; - std::vector cent_ys; - for (int i=0; i< rows; i++) { - cent_xs.push_back(cents[i]->GetX()); - cent_ys.push_back(cents[i]->GetY()); - } + if (s1 >0) s1 = a + 1; + int n_runs = b - a + 1; - if (transform == 2) { - GenUtils::StandardizeData(cent_xs ); - GenUtils::StandardizeData(cent_ys ); - } else if (transform == 1 ) { - GenUtils::DeviationFromMean(cent_xs ); - GenUtils::DeviationFromMean(cent_ys ); - } + boost::thread* worker = new boost::thread(boost::bind(&KClusterDlg::doRun, this, s1, ncluster, n_runs, n_maxiter, meth_sel, dist_sel, min_bound, bound_vals)); - for (int i=0; i< rows; i++) { - input_data[i][col_ii + 0] = cent_xs[i]; - input_data[i][col_ii + 1] = cent_ys[i]; + threadPool.add_thread(worker); + } + threadPool.join_all(); + + delete[] bound_vals; + + bool start = false; + double min_error = 0; + + for (it=sub_clusters.begin(); it!=sub_clusters.end(); it++) { + double error = it->first; + vector& clst = it->second; + if (start == false ) { + min_error = error; + clusters = clst; + start = true; + } else { + if (error < min_error) { + min_error = error; + clusters = clst; + } } } + return true; +} + +void KClusterDlg::OnOK(wxCommandEvent& event ) +{ + wxLogMessage("Click KClusterDlg::OnOK"); + + int ncluster = combo_n->GetSelection() + 2; + + wxString field_name = m_textbox->GetValue(); + if (field_name.IsEmpty()) { + wxString err_msg = _("Please enter a field name for saving clustering results."); + wxMessageDialog dlg(NULL, err_msg, _("Error"), wxOK | wxICON_ERROR); + dlg.ShowModal(); + return; + } - double error; - int ifound; - kcluster(ncluster, rows, columns, input_data, mask, weight, transpose, npass, n_maxiter, method, dist, clusterid, &error, &ifound); + vector clusters_undef(num_obs, false); vector clusters; - vector clusters_undef; - - // clean memory - for (int i=0; i > cluster_ids(ncluster); - for (int i=0; i < clusters.size(); i++) { cluster_ids[ clusters[i] - 1 ].push_back(i); } - std::sort(cluster_ids.begin(), cluster_ids.end(), GenUtils::less_vectors); for (int i=0; i < ncluster; i++) { @@ -593,6 +591,9 @@ void KMeansDlg::OnOK(wxCommandEvent& event ) clusters[idx] = c; } } + + // summary + CreateSummary(cluster_ids); // save to table int time=0; @@ -608,7 +609,7 @@ void KMeansDlg::OnOK(wxCommandEvent& event ) // detect if column is integer field, if not raise a warning if (table_int->GetColType(col) != GdaConst::long64_type ) { wxString msg = _("This field name already exists (non-integer type). Please input a unique name."); - wxMessageDialog dlg(this, msg, "Warning", wxOK | wxICON_WARNING ); + wxMessageDialog dlg(this, msg, _("Warning"), wxOK | wxICON_WARNING ); dlg.ShowModal(); return; } @@ -623,6 +624,7 @@ void KMeansDlg::OnOK(wxCommandEvent& event ) if (project->IsTableOnlyProject()) { return; } + std::vector new_var_info; std::vector new_col_ids; new_col_ids.resize(1); @@ -644,4 +646,168 @@ void KMeansDlg::OnOK(wxCommandEvent& event ) boost::uuids::nil_uuid(), wxDefaultPosition, GdaConst::map_default_size); + wxString ttl; + ttl << "KMeans " << _("Cluster Map ") << "("; + ttl << ncluster; + ttl << " clusters)"; + nf->SetTitle(ttl); +} + +//////////////////////////////////////////////////////////////////////// +// +// KMeans +//////////////////////////////////////////////////////////////////////// +KMeansDlg::KMeansDlg(wxFrame *parent, Project* project) +: KClusterDlg(parent, project, _("KMeans Dialog")) +{ + wxLogMessage("In KMeansDlg()"); + + show_initmethod = true; + show_distance = true; + show_iteration = true; + cluster_method = "KMeans"; + + CreateControls(); +} + +KMeansDlg::~KMeansDlg() +{ + wxLogMessage("In ~KMeansDlg()"); +} + +void KMeansDlg::doRun(int s1,int ncluster, int npass, int n_maxiter, int meth_sel, int dist_sel, double min_bound, double* bound_vals) +{ + char method = 'a'; // 'a' mean/random, 'b' kmeans++ 'm' median + if (meth_sel == 0) method = 'b'; + + char dist_choices[] = {'e','b'}; + char dist = 'e'; // euclidean + dist = dist_choices[dist_sel]; + + int transpose = 0; // row wise + double error; + int ifound; + int* clusterid = new int[rows]; + + int s2 = s1==0 ? 0 : s1 + npass; + kcluster(ncluster, rows, columns, input_data, mask, weight, transpose, npass, n_maxiter, method, dist, clusterid, &error, &ifound, bound_vals, min_bound, s1, s2); + + vector clusters; + for (int i=0; iSetSelection(1); // set manhattan +} + +KMediansDlg::~KMediansDlg() +{ + wxLogMessage("In ~KMedians()"); +} + +void KMediansDlg::doRun(int s1,int ncluster, int npass, int n_maxiter, int meth_sel, int dist_sel, double min_bound, double* bound_vals) +{ + char method = 'm'; // 'm' median/random + int transpose = 0; // row wise + + char dist_choices[] = {'e','b'}; + char dist = 'e'; // euclidean + dist = dist_choices[dist_sel]; + + double error; + int ifound; + int* clusterid = new int[rows]; + + int s2 = s1==0 ? 0 : s1 + npass; + kcluster(ncluster, rows, columns, input_data, mask, weight, transpose, npass, n_maxiter, method, dist, clusterid, &error, &ifound, bound_vals, min_bound, s1, s2); + + vector clusters; + for (int i=0; iSetSelection(1); // set manhattan +} + +KMedoidsDlg::~KMedoidsDlg() +{ + wxLogMessage("In ~KMedoidsDlg()"); +} + +void KMedoidsDlg::ComputeDistMatrix(int dist_sel) +{ + int transpose = 0; // row wise + char dist = 'b'; // city-block + if (dist_sel == 0) dist = 'e'; + + distmatrix = distancematrix(rows, columns, input_data, mask, weight, dist, transpose); +} + +void KMedoidsDlg::doRun(int s1,int ncluster, int npass, int n_maxiter, int meth_sel, int dist_sel, double min_bound, double* bound_vals) +{ + double error; + int ifound; + int* clusterid = new int[rows]; + + int s2 = s1==0 ? 0 : s1 + npass; + + kmedoids(ncluster, rows, distmatrix, npass, clusterid, &error, &ifound, bound_vals, min_bound, s1, s2); + + set centers; + map > c_dist; + for (int i=0; i clusters(rows); + set::iterator it; + for (it=centers.begin(); it!=centers.end(); it++) { + vector& ids = c_dist[*it]; + for (int i=0; i >& ssd_pairs); + bool CheckContiguity(double w, double& ss); + bool Run(vector& clusters); - void InitVariableCombobox(wxListBox* var_box); + virtual void ComputeDistMatrix(int dist_sel); + virtual wxString _printConfiguration(); + + virtual void doRun(int s1, int ncluster, int npass, int n_maxiter, int meth_sel, int dist_sel, double min_bound, double* bound_vals)=0; - /** Implementation of FramesManagerObserver interface */ - virtual void update(FramesManager* o); - std::vector var_info; std::vector col_ids; + +protected: + virtual void OnAutoWeightCentroids(wxCommandEvent& event); -private: - wxFrame *parent; - Project* project; - TableInterface* table_int; - std::vector tm_strs; - - FramesManager* frames_manager; + bool show_initmethod; + bool show_distance; + bool show_iteration; wxCheckBox* chk_seed; - wxListBox* combo_var; wxChoice* combo_method; - wxChoice* combo_tranform; wxChoice* combo_n; wxChoice* combo_cov; wxTextCtrl* m_textbox; - wxCheckBox* m_use_centroids; wxTextCtrl* m_iterations; wxTextCtrl* m_pass; - - wxChoice* m_method; wxChoice* m_distance; - wxButton* seedButton; - - std::map name_to_nm; - std::map name_to_tm_id; + + wxString cluster_method; unsigned int row_lim; unsigned int col_lim; std::vector scores; double thresh95; + int max_n_clusters; + double** distmatrix; + + map > sub_clusters; + DECLARE_EVENT_TABLE() }; +class KMeansDlg : public KClusterDlg +{ +public: + KMeansDlg(wxFrame *parent, Project* project); + virtual ~KMeansDlg(); + + virtual void doRun(int s1, int ncluster, int npass, int n_maxiter, int meth_sel, int dist_sel, double min_bound, double* bound_vals); +}; + +class KMediansDlg : public KClusterDlg +{ +public: + KMediansDlg(wxFrame *parent, Project* project); + virtual ~KMediansDlg(); + + virtual void doRun(int s1, int ncluster, int npass, int n_maxiter, int meth_sel, int dist_sel, double min_bound, double* bound_vals); +}; + +class KMedoidsDlg : public KClusterDlg +{ +public: + KMedoidsDlg(wxFrame *parent, Project* project); + virtual ~KMedoidsDlg(); + + virtual void ComputeDistMatrix(int dist_sel); + virtual void doRun(int s1, int ncluster, int npass, int n_maxiter, int meth_sel, int dist_sel, double min_bound, double* bound_vals); +}; #endif diff --git a/DialogTools/LisaWhat2OpenDlg.cpp b/DialogTools/LisaWhat2OpenDlg.cpp index df25aa5c3..96a6495a3 100644 --- a/DialogTools/LisaWhat2OpenDlg.cpp +++ b/DialogTools/LisaWhat2OpenDlg.cpp @@ -70,10 +70,12 @@ BEGIN_EVENT_TABLE( GetisWhat2OpenDlg, wxDialog ) EVT_BUTTON( wxID_OK, GetisWhat2OpenDlg::OnOkClick ) END_EVENT_TABLE() -GetisWhat2OpenDlg::GetisWhat2OpenDlg( wxWindow* parent, wxWindowID id, - const wxString& caption, const wxPoint& pos, - const wxSize& size, long style ) +GetisWhat2OpenDlg::GetisWhat2OpenDlg( wxWindow* parent, + bool _show_row_stand, wxWindowID id, + const wxString& caption, const wxPoint& pos, + const wxSize& size, long style ) { + show_row_stand = _show_row_stand; SetParent(parent); CreateControls(); Centre(); @@ -92,6 +94,10 @@ void GetisWhat2OpenDlg::CreateControls() if (FindWindow(XRCID("IDC_CHECK4"))) m_check4 = wxDynamicCast(FindWindow(XRCID("IDC_CHECK4")), wxCheckBox); m_check3->Hide(); + if (!show_row_stand) { + m_check4->SetValue(false); + m_check4->Hide(); + } } void GetisWhat2OpenDlg::OnOkClick( wxCommandEvent& event ) diff --git a/DialogTools/LisaWhat2OpenDlg.h b/DialogTools/LisaWhat2OpenDlg.h index 4eda48d71..414ba3935 100644 --- a/DialogTools/LisaWhat2OpenDlg.h +++ b/DialogTools/LisaWhat2OpenDlg.h @@ -51,7 +51,9 @@ class GetisWhat2OpenDlg: public wxDialog DECLARE_EVENT_TABLE() public: - GetisWhat2OpenDlg( wxWindow* parent, wxWindowID id = -1, + GetisWhat2OpenDlg( wxWindow* parent, + bool show_row_stand = true, + wxWindowID id = -1, const wxString& caption = _("What windows to open?"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, @@ -65,6 +67,7 @@ class GetisWhat2OpenDlg: public wxDialog wxCheckBox* m_check4; + bool show_row_stand; bool m_SigMap; bool m_ClustMap; bool m_RowStand; diff --git a/DialogTools/LocaleSetupDlg.cpp b/DialogTools/LocaleSetupDlg.cpp index 34805a08a..f0d61bd3a 100644 --- a/DialogTools/LocaleSetupDlg.cpp +++ b/DialogTools/LocaleSetupDlg.cpp @@ -87,10 +87,9 @@ void LocaleSetupDlg::OnResetSysLocale( wxCommandEvent& event ) m_txt_thousands->SetValue(thousands_sep); m_txt_decimal->SetValue(decimal_point); - wxString msg = "Reset to system locale successfully. Please re-open " - "current project with system locale."; + wxString msg = _("Reset to system locale successfully. Please re-open current project with system locale."); wxMessageDialog msg_dlg(this, msg, - "Reset to system locale information", + _("Reset to system locale information"), wxOK | wxOK_DEFAULT | wxICON_INFORMATION); msg_dlg.ShowModal(); EndDialog(wxID_OK); diff --git a/DialogTools/MDSDlg.cpp b/DialogTools/MDSDlg.cpp new file mode 100644 index 000000000..33434ad4b --- /dev/null +++ b/DialogTools/MDSDlg.cpp @@ -0,0 +1,334 @@ +/** + * GeoDa TM, Copyright (C) 2011-2015 by Luc Anselin - all rights reserved + * + * This file is part of GeoDa. + * + * GeoDa is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * GeoDa is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include +#include +#include +#include +#include +#include + +#include "../FramesManager.h" +#include "../DataViewer/TableInterface.h" +#include "../Project.h" +#include "../Algorithms/DataUtils.h" +#include "../Algorithms/cluster.h" +#include "../Algorithms/mds.h" +#include "../Explore/ScatterNewPlotView.h" +#include "SaveToTableDlg.h" +#include "MDSDlg.h" + +BEGIN_EVENT_TABLE( MDSDlg, wxDialog ) +EVT_CLOSE( MDSDlg::OnClose ) +END_EVENT_TABLE() + +MDSDlg::MDSDlg(wxFrame *parent_s, Project* project_s) +: AbstractClusterDlg(parent_s, project_s, _("MDS Settings")) +{ + wxLogMessage("Open MDSDlg."); + + CreateControls(); +} + +MDSDlg::~MDSDlg() +{ +} + +void MDSDlg::CreateControls() +{ + wxScrolledWindow* scrl = new wxScrolledWindow(this, wxID_ANY, wxDefaultPosition, wxSize(420,560), wxHSCROLL|wxVSCROLL ); + scrl->SetScrollRate( 5, 5 ); + + wxPanel *panel = new wxPanel(scrl); + + wxBoxSizer *vbox = new wxBoxSizer(wxVERTICAL); + + // Input + AddSimpleInputCtrls(panel, vbox); + + // parameters + wxFlexGridSizer* gbox = new wxFlexGridSizer(5,2,10,0); + + // power iteration option approximation + wxStaticText* st15 = new wxStaticText(panel, wxID_ANY, _("Use Power Iteration:"), wxDefaultPosition, wxSize(134,-1)); + wxBoxSizer *hbox15 = new wxBoxSizer(wxHORIZONTAL); + chk_poweriteration = new wxCheckBox(panel, wxID_ANY, ""); + lbl_poweriteration = new wxStaticText(panel, wxID_ANY, _("# Max Iteration:")); + txt_poweriteration = new wxTextCtrl(panel, wxID_ANY, "100",wxDefaultPosition, wxSize(70,-1)); + txt_poweriteration->SetValidator( wxTextValidator(wxFILTER_NUMERIC) ); + chk_poweriteration->Bind(wxEVT_CHECKBOX, &MDSDlg::OnCheckPowerIteration, this); + if (project->GetNumRecords() < 150) { + lbl_poweriteration->Disable(); + txt_poweriteration->Disable(); + } else { + chk_poweriteration->SetValue(true); + } + hbox15->Add(chk_poweriteration); + hbox15->Add(lbl_poweriteration); + hbox15->Add(txt_poweriteration); + gbox->Add(st15, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT | wxLEFT, 10); + gbox->Add(hbox15, 1, wxEXPAND); + + + wxStaticText* st13 = new wxStaticText(panel, wxID_ANY, _("Distance Function:"), + wxDefaultPosition, wxSize(134,-1)); + wxString choices13[] = {"Euclidean", "Manhattan"}; + m_distance = new wxChoice(panel, wxID_ANY, wxDefaultPosition, wxSize(200,-1), 2, choices13); + m_distance->SetSelection(0); + gbox->Add(st13, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT | wxLEFT, 10); + gbox->Add(m_distance, 1, wxEXPAND); + + // Transformation + AddTransformation(panel, gbox); + + wxStaticBoxSizer *hbox = new wxStaticBoxSizer(wxHORIZONTAL, panel, _("Parameters:")); + hbox->Add(gbox, 1, wxEXPAND); + + // buttons + wxButton *okButton = new wxButton(panel, wxID_OK, _("Run"), wxDefaultPosition, + wxSize(70, 30)); + wxButton *closeButton = new wxButton(panel, wxID_EXIT, _("Close"), + wxDefaultPosition, wxSize(70, 30)); + wxBoxSizer *hbox2 = new wxBoxSizer(wxHORIZONTAL); + hbox2->Add(okButton, 1, wxALIGN_CENTER | wxALL, 5); + hbox2->Add(closeButton, 1, wxALIGN_CENTER | wxALL, 5); + + // Container + vbox->Add(hbox, 0, wxALIGN_CENTER | wxALL, 10); + vbox->Add(hbox2, 0, wxALIGN_CENTER | wxALL, 10); + + wxBoxSizer *container = new wxBoxSizer(wxHORIZONTAL); + container->Add(vbox); + + panel->SetSizer(container); + + wxBoxSizer* panelSizer = new wxBoxSizer(wxVERTICAL); + panelSizer->Add(panel, 1, wxEXPAND|wxALL, 0); + + scrl->SetSizer(panelSizer); + + wxBoxSizer* sizerAll = new wxBoxSizer(wxVERTICAL); + sizerAll->Add(scrl, 1, wxEXPAND|wxALL, 0); + SetSizer(sizerAll); + SetAutoLayout(true); + sizerAll->Fit(this); + + Centre(); + + // Events + okButton->Bind(wxEVT_BUTTON, &MDSDlg::OnOK, this); + closeButton->Bind(wxEVT_BUTTON, &MDSDlg::OnCloseClick, this); +} + +void MDSDlg::OnDistanceChoice(wxCommandEvent& event) +{ + + if (m_distance->GetSelection() == 0) { + m_distance->SetSelection(1); + } else if (m_distance->GetSelection() == 3) { + m_distance->SetSelection(4); + } else if (m_distance->GetSelection() == 6) { + m_distance->SetSelection(7); + } else if (m_distance->GetSelection() == 9) { + m_distance->SetSelection(10); + } + +} + +void MDSDlg::OnCheckPowerIteration(wxCommandEvent& event) +{ + if (chk_poweriteration->IsChecked()) { + txt_poweriteration->Enable(); + lbl_poweriteration->Enable(); + } else { + txt_poweriteration->Disable(); + lbl_poweriteration->Disable(); + } +} + +void MDSDlg::OnClose(wxCloseEvent& ev) +{ + wxLogMessage("Close MDSDlg"); + // Note: it seems that if we don't explictly capture the close event + // and call Destory, then the destructor is not called. + Destroy(); +} + +void MDSDlg::OnCloseClick(wxCommandEvent& event ) +{ + wxLogMessage("Close MDSDlg."); + + event.Skip(); + EndDialog(wxID_CANCEL); + Destroy(); +} + +void MDSDlg::InitVariableCombobox(wxListBox* var_box) +{ + wxLogMessage("InitVariableCombobox MDSDlg."); + + wxArrayString items; + + std::vector col_id_map; + table_int->FillNumericColIdMap(col_id_map); + for (int i=0, iend=col_id_map.size(); iGetColName(id); + if (table_int->IsColTimeVariant(id)) { + for (int t=0; tGetColTimeSteps(id); t++) { + wxString nm = name; + nm << " (" << table_int->GetTimeString(t) << ")"; + name_to_nm[nm] = name; + name_to_tm_id[nm] = t; + items.Add(nm); + } + } else { + name_to_nm[name] = name; + name_to_tm_id[name] = 0; + items.Add(name); + } + } + if (!items.IsEmpty()) + var_box->InsertItems(items,0); +} + +wxString MDSDlg::_printConfiguration() +{ + return ""; +} + +void MDSDlg::OnOK(wxCommandEvent& event ) +{ + wxLogMessage("Click MDSDlg::OnOK"); + + int transform = combo_tranform->GetSelection(); + + if (!GetInputData(transform, 2)) + return; + + double* weight = GetWeights(columns); + + int transpose = 0; // row wise + char dist = 'e'; // euclidean + int dist_sel = m_distance->GetSelection(); + char dist_choices[] = {'e','b'}; + dist = dist_choices[dist_sel]; + + int new_col = 2; + vector > results; + + if (chk_poweriteration->IsChecked()) { + double** ragged_distances = distancematrix(rows, columns, input_data, mask, weight, dist, transpose); + + vector > distances = DataUtils::copyRaggedMatrix(ragged_distances, rows, rows); + for (int i = 1; i < rows; i++) free(ragged_distances[i]); + free(ragged_distances); + + if (dist == 'b') { + for (int i=0; iGetValue(); + long l_iterations = 0; + str_iterations.ToLong(&l_iterations); + FastMDS mds(distances, 2, (int)l_iterations); + results = mds.GetResult(); + + } else { + results.resize(new_col); + for (int i=0; i new_data(new_col); + std::vector > vals(new_col); + std::vector > undefs(new_col); + + for (int j = 0; j < new_col; ++j) { + vals[j].resize(rows); + undefs[j].resize(rows); + for (int i = 0; i < rows; ++i) { + vals[j][i] = double(results[j][i]); + undefs[j][i] = false; + } + new_data[j].d_val = &vals[j]; + new_data[j].label = wxString::Format("V%d", j+1); + new_data[j].field_default = wxString::Format("V%d", j+1); + new_data[j].type = GdaConst::double_type; + new_data[j].undefined = &undefs[j]; + } + + SaveToTableDlg dlg(project, this, new_data, + _("Save Results: MDS"), + wxDefaultPosition, wxSize(400,400)); + if (dlg.ShowModal() == wxID_OK) { + // show in a scatter plot + std::vector& new_col_ids = dlg.new_col_ids; + std::vector& new_col_names = dlg.new_col_names; + + std::vector new_var_info; + new_var_info.resize(2); + + new_var_info[0].time = 0; + // Set Primary GdaVarTools::VarInfo attributes + new_var_info[0].name = new_col_names[0]; + new_var_info[0].is_time_variant = table_int->IsColTimeVariant(new_col_ids[0]); + table_int->GetMinMaxVals(new_col_ids[0], new_var_info[0].min, new_var_info[0].max); + new_var_info[0].sync_with_global_time = new_var_info[0].is_time_variant; + new_var_info[0].fixed_scale = true; + + new_var_info[1].time = 0; + // Set Primary GdaVarTools::VarInfo attributes + new_var_info[1].name = new_col_names[1]; + new_var_info[1].is_time_variant = table_int->IsColTimeVariant(new_col_ids[1]); + table_int->GetMinMaxVals(new_col_ids[1], new_var_info[1].min, new_var_info[1].max); + new_var_info[1].sync_with_global_time = new_var_info[1].is_time_variant; + new_var_info[1].fixed_scale = true; + + wxString title = _("MDS Plot - ") + new_col_names[0] + ", " + new_col_names[1]; + + MDSPlotFrame* subframe = + new MDSPlotFrame(parent, project, + new_var_info, new_col_ids, + false, title, wxDefaultPosition, + GdaConst::scatterplot_default_size, + wxDEFAULT_FRAME_STYLE); + wxCommandEvent ev; + subframe->OnViewLinearSmoother(ev); + subframe->OnDisplayStatistics(ev); + } + + } +} diff --git a/DialogTools/MDSDlg.h b/DialogTools/MDSDlg.h new file mode 100644 index 000000000..930f6926f --- /dev/null +++ b/DialogTools/MDSDlg.h @@ -0,0 +1,63 @@ +/** + * GeoDa TM, Copyright (C) 2011-2015 by Luc Anselin - all rights reserved + * + * This file is part of GeoDa. + * + * GeoDa is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * GeoDa is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#ifndef __GEODA_CENTER_MDS_DLG_H__ +#define __GEODA_CENTER_MDS_DLG_H__ + +#include +#include +#include +#include + +#include "../VarTools.h" +#include "AbstractClusterDlg.h" + +class MDSDlg : public AbstractClusterDlg +{ +public: + MDSDlg(wxFrame *parent, Project* project); + virtual ~MDSDlg(); + + void CreateControls(); + + void OnOK( wxCommandEvent& event ); + + void OnCloseClick( wxCommandEvent& event ); + void OnClose(wxCloseEvent& ev); + void OnDistanceChoice( wxCommandEvent& event ); + void OnCheckPowerIteration( wxCommandEvent& event ); + + void InitVariableCombobox(wxListBox* var_box); + + virtual wxString _printConfiguration(); + + std::vector var_info; + std::vector col_ids; + +protected: + + wxChoice* m_distance; + wxCheckBox* chk_poweriteration; + wxTextCtrl* txt_poweriteration; + wxStaticText* lbl_poweriteration; + + DECLARE_EVENT_TABLE() +}; + +#endif diff --git a/DialogTools/MaxpDlg.cpp b/DialogTools/MaxpDlg.cpp new file mode 100644 index 000000000..be3c6a124 --- /dev/null +++ b/DialogTools/MaxpDlg.cpp @@ -0,0 +1,688 @@ +/** + * GeoDa TM, Copyright (C) 2011-2015 by Luc Anselin - all rights reserved + * + * This file is part of GeoDa. + * + * GeoDa is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * GeoDa is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../VarCalc/WeightsManInterface.h" +#include "../ShapeOperations/OGRDataAdapter.h" +#include "../Explore/MapNewView.h" +#include "../Project.h" +#include "../Algorithms/cluster.h" +#include "../Algorithms/maxp.h" + +#include "../GeneralWxUtils.h" +#include "../GenUtils.h" +#include "SaveToTableDlg.h" +#include "MaxpDlg.h" + + +BEGIN_EVENT_TABLE( MaxpDlg, wxDialog ) +EVT_CLOSE( MaxpDlg::OnClose ) +END_EVENT_TABLE() + +MaxpDlg::MaxpDlg(wxFrame* parent_s, Project* project_s) +: AbstractClusterDlg(parent_s, project_s, _("Max-p Settings")) +{ + wxLogMessage("Open Max-p dialog."); + CreateControls(); +} + +MaxpDlg::~MaxpDlg() +{ + wxLogMessage("On MaxpDlg::~MaxpDlg"); +} + +void MaxpDlg::CreateControls() +{ + wxLogMessage("On MaxpDlg::CreateControls"); + wxScrolledWindow* scrl = new wxScrolledWindow(this, wxID_ANY, wxDefaultPosition, wxSize(800,820), wxHSCROLL|wxVSCROLL ); + scrl->SetScrollRate( 5, 5 ); + + wxPanel *panel = new wxPanel(scrl); + + wxBoxSizer *vbox = new wxBoxSizer(wxVERTICAL); + + // Input + AddSimpleInputCtrls(panel, vbox); + + // Parameters + wxFlexGridSizer* gbox = new wxFlexGridSizer(9,2,5,0); + + // Weights Control + wxStaticText* st16 = new wxStaticText(panel, wxID_ANY, _("Weights:"), wxDefaultPosition, wxSize(128,-1)); + combo_weights = new wxChoice(panel, wxID_ANY, wxDefaultPosition, wxSize(200,-1)); + gbox->Add(st16, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT | wxLEFT, 10); + gbox->Add(combo_weights, 1, wxEXPAND); + + // Minimum Bound Control + AddMinBound(panel, gbox); + + // Min regions + st_minregions = new wxStaticText(panel, wxID_ANY, _("Min # per Region:"), wxDefaultPosition, wxSize(128,-1)); + txt_minregions = new wxTextCtrl(panel, wxID_ANY, _(""), wxDefaultPosition, wxSize(200,-1)); + txt_minregions->SetValidator(wxTextValidator(wxFILTER_NUMERIC)); + gbox->Add(st_minregions, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT | wxLEFT, 10); + gbox->Add(txt_minregions, 1, wxEXPAND); + + wxStaticText* st18 = new wxStaticText(panel, wxID_ANY, _("Initial Groups:"), + wxDefaultPosition, wxSize(128,-1)); + wxBoxSizer *hbox18 = new wxBoxSizer(wxHORIZONTAL); + chk_lisa = new wxCheckBox(panel, wxID_ANY, ""); + combo_lisa = new wxChoice(panel, wxID_ANY, wxDefaultPosition, wxSize(160,-1)); + + hbox18->Add(chk_lisa,0, wxALIGN_CENTER_VERTICAL); + hbox18->Add(combo_lisa,0,wxALIGN_CENTER_VERTICAL); + combo_lisa->Disable(); + gbox->Add(st18, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT | wxLEFT, 10); + gbox->Add(hbox18, 1, wxEXPAND); + + InitLISACombobox(); + + wxStaticText* st11 = new wxStaticText(panel, wxID_ANY, _("# Iterations:"), + wxDefaultPosition, wxSize(128,-1)); + m_iterations = new wxTextCtrl(panel, wxID_ANY, "99", wxDefaultPosition, wxSize(200,-1)); + gbox->Add(st11, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT | wxLEFT, 10); + gbox->Add(m_iterations, 1, wxEXPAND); + + wxStaticText* st19 = new wxStaticText(panel, wxID_ANY, _("Local Search:"), + wxDefaultPosition, wxSize(128,-1)); + wxString choices19[] = {"Greedy", "Tabu Search", "Simulated Annealing"}; + m_localsearch = new wxChoice(panel, wxID_ANY, wxDefaultPosition, wxSize(200,-1), 3, choices19); + m_localsearch->SetSelection(0); + wxBoxSizer *hbox19_1 = new wxBoxSizer(wxHORIZONTAL); + hbox19_1->Add(new wxStaticText(panel, wxID_ANY, _("Tabu Length:"), wxDefaultPosition, wxSize(108,-1))); + m_tabulength = new wxTextCtrl(panel, wxID_ANY, "85"); + hbox19_1->Add(m_tabulength); + m_tabulength->Disable(); + wxBoxSizer *hbox19_2 = new wxBoxSizer(wxHORIZONTAL); + hbox19_2->Add(new wxStaticText(panel, wxID_ANY, _("Cooling Rate:"), wxDefaultPosition, wxSize(108,-1))); + m_coolrate= new wxTextCtrl(panel, wxID_ANY, "0.85"); + hbox19_2->Add(m_coolrate); + m_coolrate->Disable(); + wxBoxSizer *vbox19 = new wxBoxSizer(wxVERTICAL); + vbox19->Add(m_localsearch, 1, wxEXPAND); + vbox19->Add(hbox19_1, 1, wxEXPAND); + vbox19->Add(hbox19_2, 1, wxEXPAND); + gbox->Add(st19, 0, wxALIGN_TOP | wxRIGHT | wxLEFT, 10); + gbox->Add(vbox19, 1, wxEXPAND); + + wxStaticText* st13 = new wxStaticText(panel, wxID_ANY, _("Distance Function:"), + wxDefaultPosition, wxSize(128,-1)); + wxString choices13[] = {"Euclidean", "Manhattan"}; + m_distance = new wxChoice(panel, wxID_ANY, wxDefaultPosition, wxSize(200,-1), 2, choices13); + m_distance->SetSelection(0); + gbox->Add(st13, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT | wxLEFT, 10); + gbox->Add(m_distance, 1, wxEXPAND); + + // Transformation + AddTransformation(panel, gbox); + + wxStaticText* st17 = new wxStaticText(panel, wxID_ANY, _("Use specified seed:"), + wxDefaultPosition, wxSize(128,-1)); + wxBoxSizer *hbox17 = new wxBoxSizer(wxHORIZONTAL); + chk_seed = new wxCheckBox(panel, wxID_ANY, ""); + seedButton = new wxButton(panel, wxID_OK, _("Change Seed")); + + hbox17->Add(chk_seed,0, wxALIGN_CENTER_VERTICAL); + hbox17->Add(seedButton,0,wxALIGN_CENTER_VERTICAL); + seedButton->Disable(); + gbox->Add(st17, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT | wxLEFT, 10); + gbox->Add(hbox17, 1, wxEXPAND); + + if (GdaConst::use_gda_user_seed) { + chk_seed->SetValue(true); + seedButton->Enable(); + } + + wxStaticBoxSizer *hbox = new wxStaticBoxSizer(wxHORIZONTAL, panel, _("Parameters:")); + hbox->Add(gbox, 1, wxEXPAND); + + // Output + wxStaticText* st3 = new wxStaticText (panel, wxID_ANY, _("Save Cluster in Field:"), + wxDefaultPosition, wxDefaultSize); + m_textbox = new wxTextCtrl(panel, wxID_ANY, "CL", wxDefaultPosition, wxSize(158,-1)); + wxStaticBoxSizer *hbox1 = new wxStaticBoxSizer(wxHORIZONTAL, panel, _("Output:")); + //wxBoxSizer *hbox1 = new wxBoxSizer(wxHORIZONTAL); + hbox1->Add(st3, 0, wxALIGN_CENTER_VERTICAL); + hbox1->Add(m_textbox, 1, wxALIGN_CENTER_VERTICAL | wxRIGHT, 10); + + // Buttons + wxButton *okButton = new wxButton(panel, wxID_OK, _("Run"), wxDefaultPosition, + wxSize(70, 30)); + wxButton *closeButton = new wxButton(panel, wxID_EXIT, _("Close"), + wxDefaultPosition, wxSize(70, 30)); + wxBoxSizer *hbox2 = new wxBoxSizer(wxHORIZONTAL); + hbox2->Add(okButton, 1, wxALIGN_CENTER | wxALL, 5); + hbox2->Add(closeButton, 1, wxALIGN_CENTER | wxALL, 5); + + // Container + vbox->Add(hbox, 0, wxALIGN_CENTER | wxALL, 10); + vbox->Add(hbox1, 0, wxEXPAND | wxTOP | wxLEFT | wxRIGHT, 10); + vbox->Add(hbox2, 0, wxALIGN_CENTER | wxALL, 10); + + // Summary control + wxBoxSizer *vbox1 = new wxBoxSizer(wxVERTICAL); + wxNotebook* notebook = AddSimpleReportCtrls(panel); + vbox1->Add(notebook, 1, wxEXPAND|wxALL,20); + + wxBoxSizer *container = new wxBoxSizer(wxHORIZONTAL); + container->Add(vbox); + container->Add(vbox1, 1, wxEXPAND | wxALL); + + panel->SetSizer(container); + + wxBoxSizer* panelSizer = new wxBoxSizer(wxVERTICAL); + panelSizer->Add(panel, 1, wxEXPAND|wxALL, 0); + + scrl->SetSizer(panelSizer); + + + wxBoxSizer* sizerAll = new wxBoxSizer(wxVERTICAL); + sizerAll->Add(scrl, 1, wxEXPAND|wxALL, 0); + SetSizer(sizerAll); + SetAutoLayout(true); + sizerAll->Fit(this); + + + Centre(); + + // Content + InitVariableCombobox(combo_var, false); + + // init weights + vector weights_ids; + WeightsManInterface* w_man_int = project->GetWManInt(); + w_man_int->GetIds(weights_ids); + + size_t sel_pos=0; + for (size_t i=0; iAppend(w_man_int->GetShortDispName(weights_ids[i])); + if (w_man_int->GetDefault() == weights_ids[i]) + sel_pos = i; + } + if (weights_ids.size() > 0) combo_weights->SetSelection(sel_pos); + + // Events + okButton->Bind(wxEVT_BUTTON, &MaxpDlg::OnOK, this); + closeButton->Bind(wxEVT_BUTTON, &MaxpDlg::OnClickClose, this); + chk_seed->Bind(wxEVT_CHECKBOX, &MaxpDlg::OnSeedCheck, this); + seedButton->Bind(wxEVT_BUTTON, &MaxpDlg::OnChangeSeed, this); + chk_lisa->Bind(wxEVT_CHECKBOX, &MaxpDlg::OnLISACheck, this); + m_localsearch->Bind(wxEVT_CHOICE, &MaxpDlg::OnLocalSearch, this); + +} + +void MaxpDlg::OnLocalSearch(wxCommandEvent& event) +{ + wxLogMessage("On MaxpDlg::OnLocalSearch"); + if ( m_localsearch->GetSelection() == 0) { + m_tabulength->Disable(); + m_coolrate->Disable(); + } else if ( m_localsearch->GetSelection() == 1) { + m_tabulength->Enable(); + m_coolrate->Disable(); + } else if ( m_localsearch->GetSelection() == 2) { + m_tabulength->Disable(); + m_coolrate->Enable(); + } +} +void MaxpDlg::OnCheckMinBound(wxCommandEvent& event) +{ + wxLogMessage("On MaxpDlg::OnLISACheck"); + AbstractClusterDlg::OnCheckMinBound(event); + + if (chk_floor->IsChecked()) { + st_minregions->Disable(); + txt_minregions->Disable(); + } else { + st_minregions->Enable(); + txt_minregions->Enable(); + } +} + +void MaxpDlg::OnLISACheck(wxCommandEvent& event) +{ + wxLogMessage("On MaxpDlg::OnLISACheck"); + bool use_lisa_seed = chk_lisa->GetValue(); + + if (use_lisa_seed) { + combo_lisa->Enable(); + } else { + combo_lisa->Disable(); + } +} + +void MaxpDlg::OnSeedCheck(wxCommandEvent& event) +{ + wxLogMessage("On MaxpDlg::OnSeedCheck"); + bool use_user_seed = chk_seed->GetValue(); + + if (use_user_seed) { + seedButton->Enable(); + if (GdaConst::use_gda_user_seed == false && GdaConst::gda_user_seed == 0) { + OnChangeSeed(event); + return; + } + GdaConst::use_gda_user_seed = true; + + OGRDataAdapter& ogr_adapt = OGRDataAdapter::GetInstance(); + ogr_adapt.AddEntry("use_gda_user_seed", "1"); + } else { + seedButton->Disable(); + } +} + +void MaxpDlg::OnChangeSeed(wxCommandEvent& event) +{ + wxLogMessage("On MaxpDlg::OnChangeSeed"); + // prompt user to enter user seed (used globally) + wxString m; + m << _("Enter a seed value for random number generator:"); + + long long unsigned int val; + wxString dlg_val; + wxString cur_val; + cur_val << GdaConst::gda_user_seed; + + wxTextEntryDialog dlg(NULL, m, _("Enter a seed value"), cur_val); + if (dlg.ShowModal() != wxID_OK) return; + dlg_val = dlg.GetValue(); + dlg_val.Trim(true); + dlg_val.Trim(false); + if (dlg_val.IsEmpty()) return; + if (dlg_val.ToULongLong(&val)) { + uint64_t new_seed_val = val; + GdaConst::gda_user_seed = new_seed_val; + GdaConst::use_gda_user_seed = true; + + OGRDataAdapter& ogr_adapt = OGRDataAdapter::GetInstance(); + wxString str_gda_user_seed; + str_gda_user_seed << GdaConst::gda_user_seed; + ogr_adapt.AddEntry("gda_user_seed", str_gda_user_seed.ToStdString()); + ogr_adapt.AddEntry("use_gda_user_seed", "1"); + } else { + wxString m = _("\"%s\" is not a valid seed. Seed unchanged."); + m = wxString::Format(m, dlg_val); + wxMessageDialog dlg(NULL, m, _("Error"), wxOK | wxICON_ERROR); + dlg.ShowModal(); + GdaConst::use_gda_user_seed = false; + OGRDataAdapter& ogr_adapt = OGRDataAdapter::GetInstance(); + ogr_adapt.AddEntry("use_gda_user_seed", "0"); + } +} + +void MaxpDlg::InitLISACombobox() +{ + wxLogMessage("On MaxpDlg::InitVariableCombobox"); + wxArrayString items; + + combo_lisa->Clear(); + + int cnt_lisa = 0; + std::vector col_id_map; + table_int->FillNumericColIdMap(col_id_map); + for (int i=0, iend=col_id_map.size(); iGetColName(id); + GdaConst::FieldType ftype = table_int->GetColType(id); + if (table_int->IsColTimeVariant(id)) { + for (int t=0; tGetColTimeSteps(id); t++) { + wxString nm = name; + nm << " (" << table_int->GetTimeString(t) << ")"; + name_to_nm[nm] = name; + name_to_tm_id[nm] = t; + items.Add(nm); + if (ftype == GdaConst::long64_type) + combo_lisa->Insert(nm, cnt_lisa++); + } + } else { + name_to_nm[name] = name; + name_to_tm_id[name] = 0; + items.Add(name); + if (ftype == GdaConst::long64_type) + combo_lisa->Insert(name, cnt_lisa++); + } + } + + combo_lisa->SetSelection(-1); + combo_lisa->SetStringSelection(select_lisa); +} + +void MaxpDlg::OnClickClose(wxCommandEvent& event ) +{ + wxLogMessage("OnClickClose MaxpDlg."); + + event.Skip(); + EndDialog(wxID_CANCEL); + Destroy(); +} + +void MaxpDlg::OnClose(wxCloseEvent& ev) +{ + wxLogMessage("Close MaxpDlg"); + // Note: it seems that if we don't explictly capture the close event + // and call Destory, then the destructor is not called. + Destroy(); +} + +wxString MaxpDlg::_printConfiguration() +{ + wxString txt; + + txt << _("Weights:") << "\t" << combo_weights->GetString(combo_weights->GetSelection()) << "\n"; + + if (chk_floor && chk_floor->IsChecked() && combo_floor->GetSelection() >= 0) { + int idx = combo_floor->GetSelection(); + wxString nm = name_to_nm[combo_floor->GetString(idx)]; + txt << _("Minimum bound:\t") << txt_floor->GetValue() << "(" << nm << ")" << "\n"; + } else { + txt << _("Minimum region size:\t") << txt_minregions->GetValue() << "\n"; + } + + if (chk_lisa->IsChecked() && combo_lisa->GetSelection() >=0) { + txt << _("Initial groups:\t") << combo_lisa->GetString(combo_lisa->GetSelection()) << "\n"; + } + + txt << _("# iterations:\t") << m_iterations->GetValue() << "\n"; + + int local_search_method = m_localsearch->GetSelection(); + if (local_search_method == 0) { + txt << _("Local search:") << "\t" << _("Greedy") << "\n"; + } else if (local_search_method == 1) { + txt << _("Local search:") << "\t" << _("Tabu Search") << "\n"; + txt << _("Tabu length:") << "\t" << m_tabulength->GetValue() << "\n"; + } else if (local_search_method == 2) { + txt << _("Local search:") << "\t" << _("Simulated Annealing") << "\n"; + txt << _("Cooling rate:") << "\t" << m_coolrate->GetValue() << "\n"; + } + + txt << _("Distance function:\t") << m_distance->GetString(m_distance->GetSelection()) << "\n"; + + txt << _("Transformation:\t") << combo_tranform->GetString(combo_tranform->GetSelection()) << "\n"; + + return txt; +} + +void MaxpDlg::OnOK(wxCommandEvent& event ) +{ + wxLogMessage("Click MaxpDlg::OnOK"); + + if (GdaConst::use_gda_user_seed) { + setrandomstate(GdaConst::gda_user_seed); + resetrandom(); + } else { + setrandomstate(-1); + resetrandom(); + } + + // Get input data + int transform = combo_tranform->GetSelection(); + bool success = GetInputData(transform, 1); + if (!success) { + return; + } + + wxString str_initial = m_iterations->GetValue(); + if (str_initial.IsEmpty()) { + wxString err_msg = _("Please enter iteration number"); + wxMessageDialog dlg(NULL, err_msg, _("Error"), wxOK | wxICON_ERROR); + dlg.ShowModal(); + return; + } + + wxString field_name = m_textbox->GetValue(); + if (field_name.IsEmpty()) { + wxString err_msg = _("Please enter a field name for saving clustering results."); + wxMessageDialog dlg(NULL, err_msg, _("Error"), wxOK | wxICON_ERROR); + dlg.ShowModal(); + return; + } + + // Get Distance Selection + char dist = 'e'; // euclidean + int dist_sel = m_distance->GetSelection(); + char dist_choices[] = {'e','b'}; + dist = dist_choices[dist_sel]; + + // Weights selection + vector weights_ids; + WeightsManInterface* w_man_int = project->GetWManInt(); + w_man_int->GetIds(weights_ids); + + int sel = combo_weights->GetSelection(); + if (sel < 0) sel = 0; + if (sel >= weights_ids.size()) sel = weights_ids.size()-1; + + boost::uuids::uuid w_id = weights_ids[sel]; + GalWeight* gw = w_man_int->GetGal(w_id); + + if (gw == NULL) { + wxMessageDialog dlg (this, _("Invalid Weights Information:\n\n The selected weights file is not valid.\n Please choose another weights file, or use Tools > Weights > Weights Manager\n to define a valid weights file."), _("Warning"), wxOK | wxICON_WARNING); + dlg.ShowModal(); + return; + } + + // Check connectivity + if (!CheckConnectivity(gw)) { + wxString msg = _("The connectivity of selected spatial weights is incomplete, please adjust the spatial weights."); + wxMessageDialog dlg(this, msg, _("Warning"), wxOK | wxICON_WARNING ); + dlg.ShowModal(); + } + + // Get Bounds + double min_bound = GetMinBound(); + if (chk_floor->IsChecked()) { + wxString str_floor = txt_floor->GetValue(); + if (str_floor.IsEmpty() || combo_floor->GetSelection() < 0) { + wxString err_msg = _("Please enter minimum bound value"); + wxMessageDialog dlg(NULL, err_msg, _("Error"), wxOK | wxICON_ERROR); + dlg.ShowModal(); + return; + } + select_floor = combo_floor->GetString(combo_floor->GetSelection()); + } else { + wxString str_floor = txt_minregions->GetValue(); + if (str_floor.IsEmpty()) { + wxString err_msg = _("Please enter minimum number of observations per regions, or use minimum bound instead."); + wxMessageDialog dlg(NULL, err_msg, _("Error"), wxOK | wxICON_ERROR); + dlg.ShowModal(); + return; + } + } + double* bound_vals = GetBoundVals(); + if (bound_vals == NULL) { + wxString str_min_regions = txt_minregions->GetValue(); + long val_min_regions; + if (str_min_regions.ToLong(&val_min_regions)) { + min_bound = val_min_regions; + } + bound_vals = new double[rows]; + for (int i=0; i seeds; + bool use_lisa_seed = chk_lisa->GetValue(); + if (use_lisa_seed) { + int idx = combo_lisa->GetSelection(); + if (idx < 0) { + use_lisa_seed = false; + } else { + select_lisa = combo_lisa->GetString(idx); + wxString nm = name_to_nm[select_lisa]; + int col = table_int->FindColId(nm); + if (col == wxNOT_FOUND) { + wxString err_msg = wxString::Format(_("Variable %s is no longer in the Table. Please close and reopen this dialog to synchronize with Table data."), nm); + wxMessageDialog dlg(NULL, err_msg, _("Error"), wxOK | wxICON_ERROR); + dlg.ShowModal(); + return; + } + int tm = name_to_tm_id[combo_lisa->GetString(idx)]; + + table_int->GetColData(col, tm, seeds); + } + } + + // Get local search method + int local_search_method = m_localsearch->GetSelection(); + int tabu_length = 85; + double cool_rate = 0.85; + if ( local_search_method == 0) { + m_tabulength->Disable(); + m_coolrate->Disable(); + } else if ( local_search_method == 1) { + wxString str_tabulength= m_tabulength->GetValue(); + long n_tabulength; + if (str_tabulength.ToLong(&n_tabulength)) { + tabu_length = n_tabulength; + } + if (tabu_length < 1) { + wxString err_msg = _("Tabu length for Tabu Search algorithm has to be an integer number larger than 1 (e.g. 85)."); + wxMessageDialog dlg(NULL, err_msg, _("Error"), wxOK | wxICON_ERROR); + dlg.ShowModal(); + return; + } + } else if ( local_search_method == 2) { + wxString str_coolrate = m_coolrate->GetValue(); + str_coolrate.ToDouble(&cool_rate); + if ( cool_rate > 1 || cool_rate <= 0) { + wxString err_msg = _("Cooling rate for Simulated Annealing algorithm has to be a float number between 0 and 1 (e.g. 0.85)."); + wxMessageDialog dlg(NULL, err_msg, _("Error"), wxOK | wxICON_ERROR); + dlg.ShowModal(); + return; + } + } + + // Get random seed + int rnd_seed = -1; + if (chk_seed->GetValue()) rnd_seed = GdaConst::gda_user_seed; + + // Run MaxP + vector > z; + for (int i=0; i vals; + for (int j=0; jgal, z, min_bound, bound_vals, initial, seeds, local_search_method, tabu_length, cool_rate, rnd_seed, dist); + + delete[] bound_vals; + + vector > cluster_ids = maxp.GetRegions(); + int ncluster = cluster_ids.size(); + + vector clusters(rows, 0); + vector clusters_undef(rows, false); + + // sort result + std::sort(cluster_ids.begin(), cluster_ids.end(), GenUtils::less_vectors); + + for (int i=0; i < ncluster; i++) { + int c = i + 1; + for (int j=0; jFindColId(field_name); + if ( col == wxNOT_FOUND) { + int col_insert_pos = table_int->GetNumberCols(); + int time_steps = 1; + int m_length_val = GdaConst::default_dbf_long_len; + int m_decimals_val = 0; + + col = table_int->InsertCol(GdaConst::long64_type, field_name, col_insert_pos, time_steps, m_length_val, m_decimals_val); + } else { + // detect if column is integer field, if not raise a warning + if (table_int->GetColType(col) != GdaConst::long64_type ) { + wxString msg = _("This field name already exists (non-integer type). Please input a unique name."); + wxMessageDialog dlg(this, msg, _("Warning"), wxOK | wxICON_WARNING ); + dlg.ShowModal(); + return; + } + } + + if (col > 0) { + table_int->SetColData(col, time, clusters); + table_int->SetColUndefined(col, time, clusters_undef); + } + + // show a cluster map + if (project->IsTableOnlyProject()) { + return; + } + std::vector new_var_info; + std::vector new_col_ids; + new_col_ids.resize(1); + new_var_info.resize(1); + new_col_ids[0] = col; + new_var_info[0].time = 0; + // Set Primary GdaVarTools::VarInfo attributes + new_var_info[0].name = field_name; + new_var_info[0].is_time_variant = table_int->IsColTimeVariant(col); + table_int->GetMinMaxVals(new_col_ids[0], new_var_info[0].min, new_var_info[0].max); + new_var_info[0].sync_with_global_time = new_var_info[0].is_time_variant; + new_var_info[0].fixed_scale = true; + + + MapFrame* nf = new MapFrame(parent, project, + new_var_info, new_col_ids, + CatClassification::unique_values, + MapCanvas::no_smoothing, 4, + boost::uuids::nil_uuid(), + wxDefaultPosition, + GdaConst::map_default_size); + wxString ttl; + ttl << "Max-p " << _("Cluster Map ") << "("; + ttl << ncluster; + ttl << " clusters)"; + nf->SetTitle(ttl); +} diff --git a/DialogTools/MaxpDlg.h b/DialogTools/MaxpDlg.h new file mode 100644 index 000000000..e181548bd --- /dev/null +++ b/DialogTools/MaxpDlg.h @@ -0,0 +1,81 @@ +/** + * GeoDa TM, Copyright (C) 2011-2015 by Luc Anselin - all rights reserved + * + * This file is part of GeoDa. + * + * GeoDa is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * GeoDa is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#ifndef __GEODA_CENTER_MAXP_DLG_H___ +#define __GEODA_CENTER_MAXP_DLG_H___ + +#include +#include +#include +#include + + +#include "../FramesManager.h" +#include "../VarTools.h" +#include "AbstractClusterDlg.h" + +class Project; +class TableInterface; + +class MaxpDlg : public AbstractClusterDlg +{ +public: + MaxpDlg(wxFrame *parent, Project* project); + virtual ~MaxpDlg(); + + void CreateControls(); + + void OnOK( wxCommandEvent& event ); + void OnClickClose( wxCommandEvent& event ); + void OnClose(wxCloseEvent& ev); + void OnLocalSearch(wxCommandEvent& event); + void OnSeedCheck(wxCommandEvent& event); + void OnChangeSeed(wxCommandEvent& event); + void OnLISACheck(wxCommandEvent& event); + virtual void OnCheckMinBound(wxCommandEvent& event); + + virtual void InitLISACombobox(); + + virtual wxString _printConfiguration(); + +private: + wxCheckBox* chk_seed; + wxCheckBox* chk_lisa; + + wxChoice* combo_weights; + wxChoice* combo_lisa; + + wxChoice* m_localsearch; + wxChoice* m_distance; + wxTextCtrl* m_textbox; + wxTextCtrl* m_iterations; + + wxStaticText* st_minregions; + wxTextCtrl* txt_minregions; + wxTextCtrl* m_tabulength; + wxTextCtrl* m_coolrate; + wxButton* seedButton; + + wxString select_floor; + wxString select_lisa; + + DECLARE_EVENT_TABLE() +}; + +#endif diff --git a/DialogTools/NumCategoriesDlg.cpp b/DialogTools/NumCategoriesDlg.cpp index 8f46ca61e..68a810224 100644 --- a/DialogTools/NumCategoriesDlg.cpp +++ b/DialogTools/NumCategoriesDlg.cpp @@ -40,7 +40,7 @@ NumCategoriesDlg::NumCategoriesDlg(wxWindow* parent, : min_categories(min_categories_s), max_categories(max_categories_s), default_categories(default_categories_s) { - categories = GenUtils::min(default_categories, max_categories); + categories = std::min(default_categories, max_categories); wxXmlResource::Get()->LoadDialog(this, GetParent(),"ID_NUM_CATEGORIES_DLG"); m_categories = wxDynamicCast(FindWindow(XRCID("ID_NUM_CATEGORIES_SPIN")), wxSpinCtrl); diff --git a/DialogTools/NumCategoriesDlg.h b/DialogTools/NumCategoriesDlg.h index 3281c81c8..47daaea59 100644 --- a/DialogTools/NumCategoriesDlg.h +++ b/DialogTools/NumCategoriesDlg.h @@ -33,8 +33,8 @@ class NumCategoriesDlg: public wxDialog int min_categories_s, int max_categories_s, int default_categories_s, - const wxString& title = "Number of Categories", - const wxString& text = "Categories"); + const wxString& title = _("Number of Categories"), + const wxString& text = _("Categories")); void OnSpinCtrl( wxSpinEvent& event ); void OnOkClick( wxCommandEvent& event ); diff --git a/DialogTools/PCASettingsDlg.cpp b/DialogTools/PCASettingsDlg.cpp new file mode 100644 index 000000000..7c3feb0b8 --- /dev/null +++ b/DialogTools/PCASettingsDlg.cpp @@ -0,0 +1,408 @@ +/** + * GeoDa TM, Copyright (C) 2011-2015 by Luc Anselin - all rights reserved + * + * This file is part of GeoDa. + * + * GeoDa is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * GeoDa is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + + + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../logger.h" +#include "../FramesManager.h" +#include "../Project.h" +#include "../Algorithms/pca.h" + +#include "SaveToTableDlg.h" +#include "PCASettingsDlg.h" + +BEGIN_EVENT_TABLE( PCASettingsDlg, wxDialog ) +EVT_CLOSE( PCASettingsDlg::OnClose ) +END_EVENT_TABLE() + +PCASettingsDlg::PCASettingsDlg(wxFrame *parent_s, Project* project_s) +: AbstractClusterDlg(parent_s, project_s, _("PCA Settings")) +{ + wxLogMessage("Open PCASettingsDlg."); + + CreateControls(); +} + +PCASettingsDlg::~PCASettingsDlg() +{ +} + +void PCASettingsDlg::CreateControls() +{ + wxScrolledWindow* scrl = new wxScrolledWindow(this, wxID_ANY, wxDefaultPosition, wxSize(820,620), wxHSCROLL|wxVSCROLL ); + scrl->SetScrollRate( 5, 5 ); + + wxPanel *panel = new wxPanel(scrl); + + wxBoxSizer *vbox = new wxBoxSizer(wxVERTICAL); + + // input + AddSimpleInputCtrls(panel, vbox); + + // parameters + wxFlexGridSizer* gbox = new wxFlexGridSizer(5,2,10,0); + + wxStaticText* st12 = new wxStaticText(panel, wxID_ANY, _("Method:"), + wxDefaultPosition, wxSize(120,-1)); + const wxString _methods[2] = {"SVD", "Eigen"}; + combo_method = new wxChoice(panel, wxID_ANY, wxDefaultPosition, + wxSize(120,-1), 2, _methods); + gbox->Add(st12, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT | wxLEFT, 10); + gbox->Add(combo_method, 1, wxEXPAND); + + // Transformation + AddTransformation(panel, gbox); + + wxStaticBoxSizer *hbox = new wxStaticBoxSizer(wxHORIZONTAL, panel, _("Parameters:")); + hbox->Add(gbox, 1, wxEXPAND); + + // Output + wxStaticText* st1 = new wxStaticText(panel, wxID_ANY, _("Components:")); + combo_n = new wxChoice(panel, wxID_ANY, wxDefaultPosition, wxSize(120,-1), 0, NULL); + + wxStaticBoxSizer *hbox1 = new wxStaticBoxSizer(wxHORIZONTAL, panel, _("Output:")); + hbox1->Add(st1, 0, wxALIGN_CENTER_VERTICAL); + hbox1->Add(combo_n, 1, wxEXPAND); + + + // buttons + wxButton *okButton = new wxButton(panel, wxID_OK, _("Run"), wxDefaultPosition, + wxSize(70, 30)); + saveButton = new wxButton(panel, wxID_SAVE, _("Save"), wxDefaultPosition, + wxSize(70, 30)); + wxButton *closeButton = new wxButton(panel, wxID_EXIT, _("Close"), + wxDefaultPosition, wxSize(70, 30)); + wxBoxSizer *hbox2 = new wxBoxSizer(wxHORIZONTAL); + hbox2->Add(okButton, 1, wxALIGN_CENTER | wxALL, 5); + hbox2->Add(saveButton, 1, wxALIGN_CENTER | wxALL, 5); + hbox2->Add(closeButton, 1, wxALIGN_CENTER | wxALL, 5); + + // Container + vbox->Add(hbox, 0, wxALIGN_CENTER | wxALL, 10); + vbox->Add(hbox1, 0, wxEXPAND | wxALL, 10); + vbox->Add(hbox2, 0, wxALIGN_CENTER | wxALL, 10); + + wxBoxSizer *vbox1 = new wxBoxSizer(wxVERTICAL); + m_textbox = new SimpleReportTextCtrl(panel, XRCID("ID_TEXTCTRL"), ""); + vbox1->Add(m_textbox, 1, wxEXPAND|wxALL,20); + + wxBoxSizer *container = new wxBoxSizer(wxHORIZONTAL); + container->Add(vbox); + container->Add(vbox1,1, wxEXPAND | wxALL); + + panel->SetSizer(container); + + wxBoxSizer* panelSizer = new wxBoxSizer(wxVERTICAL); + panelSizer->Add(panel, 1, wxEXPAND|wxALL, 0); + + scrl->SetSizer(panelSizer); + + wxBoxSizer* sizerAll = new wxBoxSizer(wxVERTICAL); + sizerAll->Add(scrl, 1, wxEXPAND|wxALL, 0); + SetSizer(sizerAll); + SetAutoLayout(true); + sizerAll->Fit(this); + + Centre(); + + saveButton->Enable(false); + + combo_method->SetSelection(0); + combo_tranform->SetSelection(2); + + // Events + okButton->Bind(wxEVT_BUTTON, &PCASettingsDlg::OnOK, this); + saveButton->Bind(wxEVT_BUTTON, &PCASettingsDlg::OnSave, this); + closeButton->Bind(wxEVT_BUTTON, &PCASettingsDlg::OnCloseClick, this); +} + +void PCASettingsDlg::OnClose(wxCloseEvent& ev) +{ + wxLogMessage("Close PCASettingsDlg"); + // Note: it seems that if we don't explictly capture the close event + // and call Destory, then the destructor is not called. + Destroy(); +} + +void PCASettingsDlg::OnCloseClick(wxCommandEvent& event ) +{ + wxLogMessage("Close PCASettingsDlg."); + + event.Skip(); + EndDialog(wxID_CANCEL); + Destroy(); +} + +void PCASettingsDlg::OnSave(wxCommandEvent& event ) +{ + wxLogMessage("OnSave PCASettingsDlg."); + + if (scores.size()==0) + return; + + // save to table + int new_col = combo_n->GetSelection() + 1; + + std::vector new_data(new_col); + std::vector > vals(new_col); + std::vector > undefs(new_col); + + for (int j = 0; j < new_col; ++j) { + vals[j].resize(row_lim); + undefs[j].resize(row_lim); + for (unsigned int i = 0; i < row_lim; ++i) { + vals[j][i] = double(scores[j + col_lim*i]); + undefs[j][i] = false; + } + new_data[j].d_val = &vals[j]; + new_data[j].label = wxString::Format("PC%d", j+1); + new_data[j].field_default = wxString::Format("PC%d", j+1); + new_data[j].type = GdaConst::double_type; + new_data[j].undefined = &undefs[j]; + } + + SaveToTableDlg dlg(project, this, new_data, + "Save Results: PCA", + wxDefaultPosition, wxSize(400,400)); + dlg.ShowModal(); + + event.Skip(); + +} + +wxString PCASettingsDlg::_printConfiguration() +{ + return wxEmptyString; +} + +void PCASettingsDlg::OnOK(wxCommandEvent& event ) +{ + wxLogMessage("Click PCASettingsDlg::OnOK"); + + int transform = combo_tranform->GetSelection(); + + if (!GetInputData(transform,1)) + return; + + int max_sel_name_len = 0; + for (int i=0; i max_sel_name_len) { + max_sel_name_len = col_names[i].length(); + } + } + + + if (rows < columns) { + wxString msg = _("SVD will be automatically used for PCA since the number of rows is less than the number of columns."); + wxMessageDialog dlg(NULL, msg, "Information", wxOK | wxICON_INFORMATION); + dlg.ShowModal(); + combo_method->SetSelection(0); + } + + int pca_method = combo_method->GetSelection(); + + Pca pca(input_data, rows, columns); + int init_result = 0; + + if (pca_method == 0) + init_result = pca.CalculateSVD(); + else + init_result = pca.Calculate(); + + if (0 != init_result) { + wxString msg = _("There is an error during PCA calculation. Please check if the data is valid."); + wxMessageDialog dlg(NULL, msg, _("Error"), wxOK | wxICON_ERROR); + dlg.ShowModal(); + return; + } + vector sd = pca.sd(); + vector prop_of_var = pca.prop_of_var(); + vector cum_prop = pca.cum_prop(); + scores = pca.scores(); + + vector el_cols = pca.eliminated_columns(); + + float kaiser = pca.kaiser(); + thresh95 = pca.thresh95(); + + unsigned int ncols = pca.ncols(); + unsigned int nrows = pca.nrows(); + + wxString method = pca.method(); + + wxString pca_log; + pca_log << _("---\n\nPCA method: ") << method; + + pca_log << _("\n\nStandard deviation:\n"); + for (int i=0; i 0 && (token[pos] == ' ' || pos == n_len-1) ) { + // end of a number + pca_log << wxString::Format("%*s%d", sub_len-1, "PC", pc_idx++); + sub_len = 1; + start = false; + } else { + if (!start && token[pos] != ' ') { + start = true; + } + sub_len += 1; + } + pos += 1; + } + header = true; + pca_log << "\n"; + } + } + + for (int k=0; k > pc_data(num_pc); + for (int i=0; i col_size(num_pc, 0); + vector > corr_matrix(columns); + double corr, corr_sqr; + for (int i=0; i col_data; + for (int j=0; j col_size[j]) { + col_size[j] = tmp.length(); + } + corr_matrix[i][j] << corr_sqr; + } + } + + pca_log << wxString::Format("%-*s", max_sel_name_len+4, ""); + for (int j=0; jGetValue(); + m_textbox->SetValue(pca_log); + + combo_n->Clear(); + for (int i=0; iAppend(wxString::Format("%d", i+1)); + } + combo_n->SetSelection((int)thresh95 -1); + + saveButton->Enable(true); +} diff --git a/DialogTools/PCASettingsDlg.h b/DialogTools/PCASettingsDlg.h new file mode 100644 index 000000000..1549b5ddd --- /dev/null +++ b/DialogTools/PCASettingsDlg.h @@ -0,0 +1,68 @@ +/** + * GeoDa TM, Copyright (C) 2011-2015 by Luc Anselin - all rights reserved + * + * This file is part of GeoDa. + * + * GeoDa is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * GeoDa is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#ifndef __GEODA_CENTER_PCA_SET_DLG_H__ +#define __GEODA_CENTER_PCA_SET_DLG_H__ + + +#include +#include +#include + +#include "../DataViewer/TableStateObserver.h" +#include "../GeneralWxUtils.h" +#include "../FramesManager.h" +#include "../FramesManagerObserver.h" +#include "../Project.h" +#include "../VarTools.h" +#include "AbstractClusterDlg.h" + +class PCASettingsDlg : public AbstractClusterDlg +{ +public: + PCASettingsDlg(wxFrame* parent, Project* project); + virtual ~PCASettingsDlg(); + + void CreateControls(); + + void OnOK( wxCommandEvent& event ); + void OnSave( wxCommandEvent& event ); + void OnCloseClick( wxCommandEvent& event ); + void OnClose(wxCloseEvent& ev); + + virtual wxString _printConfiguration(); + + std::vector var_info; + std::vector col_ids; + +private: + wxChoice* combo_n; + wxChoice* combo_method; + wxButton* saveButton; + SimpleReportTextCtrl* m_textbox; + + unsigned int row_lim; + unsigned int col_lim; + std::vector scores; + float thresh95; + + DECLARE_EVENT_TABLE() +}; + +#endif diff --git a/DialogTools/PCPDlg.cpp b/DialogTools/PCPDlg.cpp index 04dd7000e..e06d1307d 100644 --- a/DialogTools/PCPDlg.cpp +++ b/DialogTools/PCPDlg.cpp @@ -69,7 +69,7 @@ void PCPDlg::Init() name_to_tm_id.clear(); // map to corresponding time id for (int i=0, iend=col_id_map.size(); iGetColName(id).Upper(); + wxString name = table_int->GetColName(id); if (table_int->IsColTimeVariant(id)) { for (int t=0; tGetColTimeSteps(id); t++) { wxString nm = name; diff --git a/DialogTools/PreferenceDlg.cpp b/DialogTools/PreferenceDlg.cpp new file mode 100644 index 000000000..10400afc3 --- /dev/null +++ b/DialogTools/PreferenceDlg.cpp @@ -0,0 +1,1079 @@ +/** + * GeoDa TM, Copyright (C) 2011-2015 by Luc Anselin - all rights reserved + * + * This file is part of GeoDa. + * + * GeoDa is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * GeoDa is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "curl/curl.h" +#include "ogrsf_frmts.h" +#include "cpl_conv.h" + +#include "../HLStateInt.h" +#include "../HighlightStateObserver.h" +#include "../ShapeOperations/OGRDataAdapter.h" +#include "../GeneralWxUtils.h" +#include "../GenUtils.h" +#include "../GdaConst.h" +#include "../GdaJson.h" +#include "../logger.h" +#include "PreferenceDlg.h" + +using namespace std; +using namespace GdaJson; + +//////////////////////////////////////////////////////////////////////////////// +// +// PreferenceDlg +// +//////////////////////////////////////////////////////////////////////////////// +PreferenceDlg::PreferenceDlg(wxWindow* parent, + wxWindowID id, + const wxString& title, + const wxPoint& pos, + const wxSize& size) + : wxDialog(parent, id, title, pos, size, wxDEFAULT_DIALOG_STYLE) +{ + highlight_state = NULL; + SetBackgroundColour(*wxWHITE); + Init(); + SetMinSize(wxSize(550, -1)); +} + +PreferenceDlg::PreferenceDlg(wxWindow* parent, + HLStateInt* _highlight_state, + wxWindowID id, + const wxString& title, + const wxPoint& pos, + const wxSize& size) + : wxDialog(parent, id, title, pos, size, wxDEFAULT_DIALOG_STYLE) +{ + highlight_state = _highlight_state; + SetBackgroundColour(*wxWHITE); + Init(); + SetMinSize(wxSize(550, -1)); +} + +void PreferenceDlg::Init() +{ + ReadFromCache(); + + wxNotebook* notebook = new wxNotebook(this, wxID_ANY, wxDefaultPosition, wxDefaultSize); + + // visualization tab + wxNotebookPage* vis_page = new wxNotebookPage(notebook, -1, wxDefaultPosition, wxSize(560, 680)); +#ifdef __WIN32__ + vis_page->SetBackgroundColour(*wxWHITE); +#endif + notebook->AddPage(vis_page, _("System")); + wxFlexGridSizer* grid_sizer1 = new wxFlexGridSizer(21, 2, 8, 10); + + grid_sizer1->Add(new wxStaticText(vis_page, wxID_ANY, _("Maps:")), 1); + grid_sizer1->AddSpacer(10); + + wxString lbl0 = _("Use classic yellow cross-hatching to highlight selection in maps:"); + wxStaticText* lbl_txt0 = new wxStaticText(vis_page, wxID_ANY, lbl0); + cbox0 = new wxCheckBox(vis_page, XRCID("PREF_USE_CROSSHATCH"), "", wxDefaultPosition); + grid_sizer1->Add(lbl_txt0, 1, wxEXPAND); + grid_sizer1->Add(cbox0, 0, wxALIGN_RIGHT); + cbox0->Bind(wxEVT_CHECKBOX, &PreferenceDlg::OnCrossHatch, this); + + wxSize sl_sz(200, -1); + wxSize txt_sz(35, -1); + + wxString lbl1 = _("Set transparency of highlighted objects in selection:"); + wxStaticText* lbl_txt1 = new wxStaticText(vis_page, wxID_ANY, lbl1); + wxBoxSizer* box1 = new wxBoxSizer(wxHORIZONTAL); + slider1 = new wxSlider(vis_page, wxID_ANY, + 0, 0, 255, + wxDefaultPosition, sl_sz, + wxSL_HORIZONTAL); + slider_txt1 = new wxTextCtrl(vis_page, XRCID("PREF_SLIDER1_TXT"), "", + wxDefaultPosition, txt_sz, wxTE_READONLY); + box1->Add(slider1); + box1->Add(slider_txt1); + grid_sizer1->Add(lbl_txt1, 1, wxEXPAND); + grid_sizer1->Add(box1, 0, wxALIGN_RIGHT); + slider1->Bind(wxEVT_SLIDER, &PreferenceDlg::OnSlider1, this); + + wxString lbl2 = _("Set transparency of unhighlighted objects in selection:"); + wxStaticText* lbl_txt2 = new wxStaticText(vis_page, wxID_ANY, lbl2); + wxBoxSizer* box2 = new wxBoxSizer(wxHORIZONTAL); + slider2 = new wxSlider(vis_page, wxID_ANY, + 0, 0, 255, + wxDefaultPosition, sl_sz, + wxSL_HORIZONTAL); + slider_txt2 = new wxTextCtrl(vis_page, XRCID("PREF_SLIDER2_TXT"), "", + wxDefaultPosition, txt_sz, wxTE_READONLY); + box2->Add(slider2); + box2->Add(slider_txt2); + grid_sizer1->Add(lbl_txt2, 1, wxEXPAND); + grid_sizer1->Add(box2, 0, wxALIGN_RIGHT); + slider2->Bind(wxEVT_SLIDER, &PreferenceDlg::OnSlider2, this); + + wxString lbl3 = _("Add basemap automatically:"); + wxStaticText* lbl_txt3 = new wxStaticText(vis_page, wxID_ANY, lbl3); + //wxStaticText* lbl_txt33 = new wxStaticText(vis_page, wxID_ANY, lbl3); + cmb33 = new wxComboBox(vis_page, wxID_ANY, "", wxDefaultPosition, wxDefaultSize, 0, NULL, wxCB_READONLY); + cmb33->Append("No basemap"); + wxString basemap_sources = GdaConst::gda_basemap_sources; + wxString encoded_str= wxString::FromUTF8((const char*)basemap_sources.mb_str()); + if (encoded_str.IsEmpty() == false) { + basemap_sources = encoded_str; + } + vector keys; + wxString newline = basemap_sources.Find('\r') == wxNOT_FOUND ? "\n" : "\r\n"; + wxStringTokenizer tokenizer(basemap_sources, newline); + while ( tokenizer.HasMoreTokens() ) { + wxString token = tokenizer.GetNextToken(); + keys.push_back(token.Trim()); + } + for (int i=0; iAppend(group_n_name); + } + } + cmb33->SetSelection(0); + cmb33->Bind(wxEVT_COMBOBOX, &PreferenceDlg::OnChoice3, this); + + grid_sizer1->Add(lbl_txt3, 1, wxEXPAND); + grid_sizer1->Add(cmb33, 0, wxALIGN_RIGHT); + + grid_sizer1->Add(new wxStaticText(vis_page, wxID_ANY, _("Plots:")), 1, wxTOP | wxBOTTOM, 10); + grid_sizer1->AddSpacer(10); + + wxString lbl6 = _("Set transparency of highlighted objects in selection:"); + wxStaticText* lbl_txt6 = new wxStaticText(vis_page, wxID_ANY, lbl6); + wxBoxSizer* box6 = new wxBoxSizer(wxHORIZONTAL); + slider6 = new wxSlider(vis_page, XRCID("PREF_SLIDER6"), + 255, 0, 255, + wxDefaultPosition, sl_sz, + wxSL_HORIZONTAL); + wxTextCtrl* slider_txt6 = new wxTextCtrl(vis_page, XRCID("PREF_SLIDER6_TXT"), "0.0", wxDefaultPosition, txt_sz, wxTE_READONLY); + lbl_txt6->Hide(); + slider6->Hide(); + slider_txt6->Hide(); + + box6->Add(slider6); + box6->Add(slider_txt6); + grid_sizer1->Add(lbl_txt6, 1, wxEXPAND); + grid_sizer1->Add(box6, 0, wxALIGN_RIGHT); + slider6->Bind(wxEVT_SLIDER, &PreferenceDlg::OnSlider6, this); + slider6->Enable(false); + + wxString lbl7 = _("Set transparency of unhighlighted objects in selection:"); + wxStaticText* lbl_txt7 = new wxStaticText(vis_page, wxID_ANY, lbl7); + wxBoxSizer* box7 = new wxBoxSizer(wxHORIZONTAL); + slider7 = new wxSlider(vis_page, wxID_ANY, + 0, 0, 255, + wxDefaultPosition, sl_sz, + wxSL_HORIZONTAL); + slider_txt7 = new wxTextCtrl(vis_page, XRCID("PREF_SLIDER7_TXT"), "", wxDefaultPosition, txt_sz, wxTE_READONLY); + box7->Add(slider7); + box7->Add(slider_txt7); + grid_sizer1->Add(lbl_txt7, 1, wxEXPAND); + grid_sizer1->Add(box7, 0, wxALIGN_RIGHT); + slider7->Bind(wxEVT_SLIDER, &PreferenceDlg::OnSlider7, this); + + + grid_sizer1->Add(new wxStaticText(vis_page, wxID_ANY, _("System:")), 1, + wxTOP | wxBOTTOM, 10); + grid_sizer1->AddSpacer(10); + + + wxString lbl113 = _("Language:"); + wxStaticText* lbl_txt113 = new wxStaticText(vis_page, wxID_ANY, lbl113); + cmb113 = new wxComboBox(vis_page, wxID_ANY, "", wxDefaultPosition, wxDefaultSize, 0, NULL, wxCB_READONLY); + cmb113->Append(""); + cmb113->Append("English"); + cmb113->Append("Chinese (Simplified)"); + cmb113->Append("Spanish"); + //cmb113->Append("German"); + cmb113->Bind(wxEVT_COMBOBOX, &PreferenceDlg::OnChooseLanguage, this); + //cmb113->Disable(); + + grid_sizer1->Add(lbl_txt113, 1, wxEXPAND); + grid_sizer1->Add(cmb113, 0, wxALIGN_RIGHT); + + wxString lbl8 = _("Show Recent/Sample Data panel in Connect Datasource Dialog:"); + wxStaticText* lbl_txt8 = new wxStaticText(vis_page, wxID_ANY, lbl8); + cbox8 = new wxCheckBox(vis_page, XRCID("PREF_SHOW_RECENT"), "", wxDefaultPosition); + grid_sizer1->Add(lbl_txt8, 1, wxEXPAND); + grid_sizer1->Add(cbox8, 0, wxALIGN_RIGHT); + cbox8->Bind(wxEVT_CHECKBOX, &PreferenceDlg::OnShowRecent, this); + + wxString lbl9 = _("Show CSV Configuration in Merge Data Dialog:"); + wxStaticText* lbl_txt9 = new wxStaticText(vis_page, wxID_ANY, lbl9); + cbox9 = new wxCheckBox(vis_page, XRCID("PREF_SHOW_CSV_IN_MERGE"), "", wxDefaultPosition); + grid_sizer1->Add(lbl_txt9, 1, wxEXPAND); + grid_sizer1->Add(cbox9, 0, wxALIGN_RIGHT); + cbox9->Bind(wxEVT_CHECKBOX, &PreferenceDlg::OnShowCsvInMerge, this); + + wxString lbl10 = _("Enable High DPI/Retina support (Mac only):"); + wxStaticText* lbl_txt10 = new wxStaticText(vis_page, wxID_ANY, lbl10); + cbox10 = new wxCheckBox(vis_page, XRCID("PREF_ENABLE_HDPI"), "", wxDefaultPosition); + grid_sizer1->Add(lbl_txt10, 1, wxEXPAND); + grid_sizer1->Add(cbox10, 0, wxALIGN_RIGHT); + cbox10->Bind(wxEVT_CHECKBOX, &PreferenceDlg::OnEnableHDPISupport, this); + + wxString lbl4 = _("Disable crash detection for bug report:"); + wxStaticText* lbl_txt4 = new wxStaticText(vis_page, wxID_ANY, lbl4); + cbox4 = new wxCheckBox(vis_page, XRCID("PREF_CRASH_DETECT"), "", wxDefaultPosition); + grid_sizer1->Add(lbl_txt4, 1, wxEXPAND); + grid_sizer1->Add(cbox4, 0, wxALIGN_RIGHT); + cbox4->Bind(wxEVT_CHECKBOX, &PreferenceDlg::OnDisableCrashDetect, this); + + wxString lbl5 = _("Disable auto upgrade:"); + wxStaticText* lbl_txt5 = new wxStaticText(vis_page, wxID_ANY, lbl5); + cbox5 = new wxCheckBox(vis_page, XRCID("PREF_AUTO_UPGRADE"), "", wxDefaultPosition); + grid_sizer1->Add(lbl_txt5, 1, wxEXPAND); + grid_sizer1->Add(cbox5, 0, wxALIGN_RIGHT); + cbox5->Bind(wxEVT_CHECKBOX, &PreferenceDlg::OnDisableAutoUpgrade, this); + + grid_sizer1->Add(new wxStaticText(vis_page, wxID_ANY, _("Method:")), 1, + wxTOP | wxBOTTOM, 10); + grid_sizer1->AddSpacer(10); + + wxString lbl16 = _("Use specified seed:"); + wxStaticText* lbl_txt16 = new wxStaticText(vis_page, wxID_ANY, lbl16); + cbox6 = new wxCheckBox(vis_page, XRCID("PREF_USE_SPEC_SEED"), "", wxDefaultPosition); + grid_sizer1->Add(lbl_txt16, 1, wxEXPAND); + grid_sizer1->Add(cbox6, 0, wxALIGN_RIGHT); + cbox6->Bind(wxEVT_CHECKBOX, &PreferenceDlg::OnUseSpecifiedSeed, this); + + wxString lbl17 = _("Set seed for randomization:"); + wxStaticText* lbl_txt17 = new wxStaticText(vis_page, wxID_ANY, lbl17); + txt_seed = new wxTextCtrl(vis_page, XRCID("PREF_SEED_VALUE"), "", wxDefaultPosition, wxSize(85, -1)); + grid_sizer1->Add(lbl_txt17, 1, wxEXPAND); + grid_sizer1->Add(txt_seed, 0, wxALIGN_RIGHT); + txt_seed->Bind(wxEVT_COMMAND_TEXT_UPDATED, &PreferenceDlg::OnSeedEnter, this); + + wxString lbl18 = _("Set number of CPU cores manually:"); + wxStaticText* lbl_txt18 = new wxStaticText(vis_page, wxID_ANY, lbl18); + wxBoxSizer* box18 = new wxBoxSizer(wxHORIZONTAL); + cbox18 = new wxCheckBox(vis_page, XRCID("PREF_SET_CPU_CORES"), "", wxDefaultPosition); + txt_cores = new wxTextCtrl(vis_page, XRCID("PREF_TXT_CPU_CORES"), "", wxDefaultPosition, wxSize(85, -1)); + box18->Add(cbox18); + box18->Add(txt_cores); + grid_sizer1->Add(lbl_txt18, 1, wxEXPAND); + grid_sizer1->Add(box18, 0, wxALIGN_RIGHT); + cbox18->Bind(wxEVT_CHECKBOX, &PreferenceDlg::OnSetCPUCores, this); + txt_cores->Bind(wxEVT_COMMAND_TEXT_UPDATED, &PreferenceDlg::OnCPUCoresEnter, this); + + wxString lbl19 = _("Stopping criterion for power iteration:"); + wxStaticText* lbl_txt19 = new wxStaticText(vis_page, wxID_ANY, lbl19); + txt_poweriter_eps = new wxTextCtrl(vis_page, XRCID("PREF_POWER_EPS"), "", wxDefaultPosition, wxSize(85, -1)); + grid_sizer1->Add(lbl_txt19, 1, wxEXPAND); + grid_sizer1->Add(txt_poweriter_eps, 0, wxALIGN_RIGHT); + txt_poweriter_eps->Bind(wxEVT_COMMAND_TEXT_UPDATED, &PreferenceDlg::OnPowerEpsEnter, this); + + wxString lbl20 = _("Use GPU to Accelerate computation:"); + wxStaticText* lbl_txt20 = new wxStaticText(vis_page, wxID_ANY, lbl20); + cbox_gpu = new wxCheckBox(vis_page, XRCID("PREF_USE_GPU"), "", wxDefaultPosition); + grid_sizer1->Add(lbl_txt20, 1, wxEXPAND); + grid_sizer1->Add(cbox_gpu, 0, wxALIGN_RIGHT); + cbox_gpu->Bind(wxEVT_CHECKBOX, &PreferenceDlg::OnUseGPU, this); + + //lbl_txt20->Hide(); + //cbox_gpu->Hide(); + + grid_sizer1->AddGrowableCol(0, 1); + + wxBoxSizer *nb_box1 = new wxBoxSizer(wxVERTICAL); + nb_box1->Add(grid_sizer1, 1, wxEXPAND | wxALL, 20); + nb_box1->Fit(vis_page); + + vis_page->SetSizer(nb_box1); + + //------------------------------------ + // datasource (gdal) tab + wxNotebookPage* gdal_page = new wxNotebookPage(notebook, -1); +#ifdef __WIN32__ + gdal_page->SetBackgroundColour(*wxWHITE); +#endif + notebook->AddPage(gdal_page, "Data Source"); + wxFlexGridSizer* grid_sizer2 = new wxFlexGridSizer(10, 2, 8, 10); + + wxString lbl21 = _("Hide system table in Postgresql connection:"); + wxStaticText* lbl_txt21 = new wxStaticText(gdal_page, wxID_ANY, lbl21); + cbox21 = new wxCheckBox(gdal_page, wxID_ANY, "", wxDefaultPosition); + grid_sizer2->Add(lbl_txt21, 1, wxEXPAND | wxTOP, 10); + grid_sizer2->Add(cbox21, 0, wxALIGN_RIGHT | wxTOP, 13); + cbox21->Bind(wxEVT_CHECKBOX, &PreferenceDlg::OnHideTablePostGIS, this); + + + wxString lbl22 = _("Hide system table in SQLITE connection:"); + wxStaticText* lbl_txt22 = new wxStaticText(gdal_page, wxID_ANY, lbl22); + cbox22 = new wxCheckBox(gdal_page, wxID_ANY, "", wxDefaultPosition); + grid_sizer2->Add(lbl_txt22, 1, wxEXPAND); + grid_sizer2->Add(cbox22, 0, wxALIGN_RIGHT); + cbox22->Bind(wxEVT_CHECKBOX, &PreferenceDlg::OnHideTableSQLITE, this); + + + wxString lbl23 = _("Http connection timeout (seconds) for e.g. WFS, Geojson etc.:"); + wxStaticText* lbl_txt23 = new wxStaticText(gdal_page, wxID_ANY, lbl23); + txt23 = new wxTextCtrl(gdal_page, XRCID("ID_HTTP_TIMEOUT"), "", wxDefaultPosition, txt_sz, wxTE_PROCESS_ENTER); + grid_sizer2->Add(lbl_txt23, 1, wxEXPAND); + grid_sizer2->Add(txt23, 0, wxALIGN_RIGHT); + txt23->Bind(wxEVT_TEXT, &PreferenceDlg::OnTimeoutInput, this); + + wxString lbl24 = _("Date/Time formats (using comma to separate formats):"); + wxStaticText* lbl_txt24 = new wxStaticText(gdal_page, wxID_ANY, lbl24); + txt24 = new wxTextCtrl(gdal_page, XRCID("ID_DATETIME_FORMATS"), "", wxDefaultPosition, wxSize(200, -1), wxTE_PROCESS_ENTER); + grid_sizer2->Add(lbl_txt24, 1, wxEXPAND); + grid_sizer2->Add(txt24, 0, wxALIGN_RIGHT); + txt24->Bind(wxEVT_TEXT, &PreferenceDlg::OnDateTimeInput, this); + + grid_sizer2->AddGrowableCol(0, 1); + + wxBoxSizer *nb_box2 = new wxBoxSizer(wxVERTICAL); + nb_box2->Add(grid_sizer2, 1, wxEXPAND | wxALL, 20); + nb_box2->Fit(gdal_page); + + gdal_page->SetSizer(nb_box2); + + SetupControls(); + + // overall + + wxBoxSizer *vbox = new wxBoxSizer(wxVERTICAL); + wxBoxSizer *hbox = new wxBoxSizer(wxHORIZONTAL); + + wxButton *resetButton = new wxButton(this, -1, _("Reset"), wxDefaultPosition, wxSize(70, 30)); + wxButton *closeButton = new wxButton(this, wxID_OK, _("Close"), wxDefaultPosition, wxSize(70, 30)); + resetButton->Bind(wxEVT_COMMAND_BUTTON_CLICKED, &PreferenceDlg::OnReset, this); + + hbox->Add(resetButton, 1); + hbox->Add(closeButton, 1, wxLEFT, 5); + + vbox->Add(notebook, 1, wxEXPAND | wxALL, 10); + vbox->Add(hbox, 0, wxALIGN_CENTER | wxTOP | wxBOTTOM, 10); + + SetSizer(vbox); + vbox->Fit(this); + + Centre(); + ShowModal(); + + Destroy(); +} + +void PreferenceDlg::OnReset(wxCommandEvent& ev) +{ + GdaConst::gda_use_gpu = false; + GdaConst::gda_ui_language = 0; + GdaConst::gda_eigen_tol = 1.0E-8; + GdaConst::gda_set_cpu_cores = true; + GdaConst::gda_cpu_cores = 8; + GdaConst::use_cross_hatching = false; + GdaConst::transparency_highlighted = 255; + GdaConst::transparency_unhighlighted = 100; + //GdaConst::transparency_map_on_basemap = 200; + GdaConst::use_basemap_by_default = false; + GdaConst::default_basemap_selection = 0; + GdaConst::hide_sys_table_postgres = false; + GdaConst::hide_sys_table_sqlite = false; + GdaConst::disable_crash_detect = false; + GdaConst::disable_auto_upgrade = false; + GdaConst::plot_transparency_highlighted = 255; + GdaConst::plot_transparency_unhighlighted = 50; + GdaConst::show_recent_sample_connect_ds_dialog = true; + GdaConst::show_csv_configure_in_merge = true; + GdaConst::enable_high_dpi_support = true; + GdaConst::gdal_http_timeout = 5; + GdaConst::use_gda_user_seed= true; + GdaConst::gda_user_seed = 123456789; + GdaConst::gda_datetime_formats_str = "%Y-%m-%d %H:%M:%S,%Y/%m/%d %H:%M:%S,%d.%m.%Y %H:%M:%S,%m/%d/%Y %H:%M:%S,%Y-%m-%d,%m/%d/%Y,%Y/%m/%d,%H:%M:%S,%H:%M,%Y/%m/%d %H:%M %p"; + if (!GdaConst::gda_datetime_formats_str.empty()) { + wxString patterns = GdaConst::gda_datetime_formats_str; + wxStringTokenizer tokenizer(patterns, ","); + while ( tokenizer.HasMoreTokens() ) + { + wxString token = tokenizer.GetNextToken(); + GdaConst::gda_datetime_formats.push_back(token); + } + GdaConst::gda_datetime_formats_str = patterns; + } + + SetupControls(); + + OGRDataAdapter& ogr_adapt = OGRDataAdapter::GetInstance(); + ogr_adapt.AddEntry("use_cross_hatching", "0"); + ogr_adapt.AddEntry("transparency_highlighted", "255"); + ogr_adapt.AddEntry("transparency_unhighlighted", "100"); + ogr_adapt.AddEntry("use_basemap_by_default", "0"); + ogr_adapt.AddEntry("default_basemap_selection", "0"); + ogr_adapt.AddEntry("hide_sys_table_postgres", "0"); + ogr_adapt.AddEntry("hide_sys_table_sqlite", "0"); + ogr_adapt.AddEntry("disable_crash_detect", "0"); + ogr_adapt.AddEntry("disable_auto_upgrade", "0"); + ogr_adapt.AddEntry("plot_transparency_highlighted", "255"); + ogr_adapt.AddEntry("plot_transparency_unhighlighted", "50"); + ogr_adapt.AddEntry("show_recent_sample_connect_ds_dialog", "1"); + ogr_adapt.AddEntry("show_csv_configure_in_merge", "1"); + ogr_adapt.AddEntry("enable_high_dpi_support", "1"); + ogr_adapt.AddEntry("gdal_http_timeout", "5"); + ogr_adapt.AddEntry("use_gda_user_seed", "1"); + ogr_adapt.AddEntry("gda_user_seed", "123456789"); + ogr_adapt.AddEntry("gda_datetime_formats_str", "%Y-%m-%d %H:%M:%S,%Y/%m/%d %H:%M:%S,%d.%m.%Y %H:%M:%S,%m/%d/%Y %H:%M:%S,%Y-%m-%d,%m/%d/%Y,%Y/%m/%d,%H:%M:%S,%H:%M,%Y/%m/%d %H:%M %p"); + ogr_adapt.AddEntry("gda_cpu_cores", "8"); + ogr_adapt.AddEntry("gda_set_cpu_cores", "1"); + ogr_adapt.AddEntry("gda_eigen_tol", "1.0E-8"); + ogr_adapt.AddEntry("gda_ui_language", "0"); + ogr_adapt.AddEntry("gda_use_gpu", "0"); +} + +void PreferenceDlg::SetupControls() +{ + cbox0->SetValue(GdaConst::use_cross_hatching); + slider1->SetValue(GdaConst::transparency_highlighted); + wxString t_hl = wxString::Format("%.2f", (255 - GdaConst::transparency_highlighted) / 255.0); + slider_txt1->SetValue(t_hl); + slider2->SetValue(GdaConst::transparency_unhighlighted); + wxString t_uhl = wxString::Format("%.2f", (255 - GdaConst::transparency_unhighlighted) / 255.0); + slider_txt2->SetValue(t_uhl); + if (GdaConst::use_basemap_by_default) { + cmb33->SetSelection(GdaConst::default_basemap_selection); + } + else { + cmb33->SetSelection(0); + } + + slider7->SetValue(GdaConst::plot_transparency_unhighlighted); + wxString t_p_hl = wxString::Format("%.2f", (255 - GdaConst::plot_transparency_unhighlighted) / 255.0); + slider_txt7->SetValue(t_p_hl); + + cbox4->SetValue(GdaConst::disable_crash_detect); + cbox5->SetValue(GdaConst::disable_auto_upgrade); + cbox21->SetValue(GdaConst::hide_sys_table_postgres); + cbox22->SetValue(GdaConst::hide_sys_table_sqlite); + cbox8->SetValue(GdaConst::show_recent_sample_connect_ds_dialog); + cbox9->SetValue(GdaConst::show_csv_configure_in_merge); + cbox10->SetValue(GdaConst::enable_high_dpi_support); + + txt23->SetValue(wxString::Format("%d", GdaConst::gdal_http_timeout)); + txt24->SetValue(GdaConst::gda_datetime_formats_str); + + cbox6->SetValue(GdaConst::use_gda_user_seed); + wxString t_seed; + t_seed << GdaConst::gda_user_seed; + txt_seed->SetValue(t_seed); + + cbox18->SetValue(GdaConst::gda_set_cpu_cores); + wxString t_cores; + t_cores << GdaConst::gda_cpu_cores; + txt_cores->SetValue(t_cores); + + wxString t_power_eps; + t_power_eps << GdaConst::gda_eigen_tol; + txt_poweriter_eps->SetValue(t_power_eps); + + cmb113->SetSelection(GdaConst::gda_ui_language); + + cbox_gpu->SetValue(GdaConst::gda_use_gpu); +} + +void PreferenceDlg::ReadFromCache() +{ + vector transp_h = OGRDataAdapter::GetInstance().GetHistory("transparency_highlighted"); + if (!transp_h.empty()) { + long transp_l = 0; + wxString transp = transp_h[0]; + if (transp.ToLong(&transp_l)) { + GdaConst::transparency_highlighted = transp_l; + } + } + vector transp_uh = OGRDataAdapter::GetInstance().GetHistory("transparency_unhighlighted"); + if (!transp_uh.empty()) { + long transp_l = 0; + wxString transp = transp_uh[0]; + if (transp.ToLong(&transp_l)) { + GdaConst::transparency_unhighlighted = transp_l; + } + } + vector plot_transparency_unhighlighted = OGRDataAdapter::GetInstance().GetHistory("plot_transparency_unhighlighted"); + if (!plot_transparency_unhighlighted.empty()) { + long transp_l = 0; + wxString transp = plot_transparency_unhighlighted[0]; + if (transp.ToLong(&transp_l)) { + GdaConst::plot_transparency_unhighlighted = transp_l; + } + } + vector basemap_sel = OGRDataAdapter::GetInstance().GetHistory("default_basemap_selection"); + if (!basemap_sel.empty()) { + long sel_l = 0; + wxString sel = basemap_sel[0]; + if (sel.ToLong(&sel_l)) { + GdaConst::default_basemap_selection = sel_l; + } + } + vector basemap_default = OGRDataAdapter::GetInstance().GetHistory("use_basemap_by_default"); + if (!basemap_default.empty()) { + long sel_l = 0; + wxString sel = basemap_default[0]; + if (sel.ToLong(&sel_l)) { + if (sel_l == 1) + GdaConst::use_basemap_by_default = true; + else if (sel_l == 0) + GdaConst::use_basemap_by_default = false; + } + } + vector crossht_sel = OGRDataAdapter::GetInstance().GetHistory("use_cross_hatching"); + if (!crossht_sel.empty()) { + long cross_l = 0; + wxString cross = crossht_sel[0]; + if (cross.ToLong(&cross_l)) { + if (cross_l == 1) + GdaConst::use_cross_hatching = true; + else if (cross_l == 0) + GdaConst::use_cross_hatching = false; + } + } + vector postgres_sys_sel = OGRDataAdapter::GetInstance().GetHistory("hide_sys_table_postgres"); + if (!postgres_sys_sel.empty()) { + long sel_l = 0; + wxString sel = postgres_sys_sel[0]; + if (sel.ToLong(&sel_l)) { + if (sel_l == 1) + GdaConst::hide_sys_table_postgres = true; + else if (sel_l == 0) + GdaConst::hide_sys_table_postgres = false; + } + } + vector hide_sys_table_sqlite = OGRDataAdapter::GetInstance().GetHistory("hide_sys_table_sqlite"); + if (!hide_sys_table_sqlite.empty()) { + long sel_l = 0; + wxString sel = hide_sys_table_sqlite[0]; + if (sel.ToLong(&sel_l)) { + if (sel_l == 1) + GdaConst::hide_sys_table_sqlite = true; + else if (sel_l == 0) + GdaConst::hide_sys_table_sqlite = false; + } + } + vector disable_crash_detect = OGRDataAdapter::GetInstance().GetHistory("disable_crash_detect"); + if (!disable_crash_detect.empty()) { + long sel_l = 0; + wxString sel = disable_crash_detect[0]; + if (sel.ToLong(&sel_l)) { + if (sel_l == 1) + GdaConst::disable_crash_detect = true; + else if (sel_l == 0) + GdaConst::disable_crash_detect = false; + } + } + vector disable_auto_upgrade = OGRDataAdapter::GetInstance().GetHistory("disable_auto_upgrade"); + if (!disable_auto_upgrade.empty()) { + long sel_l = 0; + wxString sel = disable_auto_upgrade[0]; + if (sel.ToLong(&sel_l)) { + if (sel_l == 1) + GdaConst::disable_auto_upgrade = true; + else if (sel_l == 0) + GdaConst::disable_auto_upgrade = false; + } + } + + vector show_recent_sample_connect_ds_dialog = OGRDataAdapter::GetInstance().GetHistory("show_recent_sample_connect_ds_dialog"); + if (!show_recent_sample_connect_ds_dialog.empty()) { + long sel_l = 0; + wxString sel = show_recent_sample_connect_ds_dialog[0]; + if (sel.ToLong(&sel_l)) { + if (sel_l == 1) + GdaConst::show_recent_sample_connect_ds_dialog = true; + else if (sel_l == 0) + GdaConst::show_recent_sample_connect_ds_dialog = false; + } + } + + vector show_csv_configure_in_merge = OGRDataAdapter::GetInstance().GetHistory("show_csv_configure_in_merge"); + if (!show_csv_configure_in_merge.empty()) { + long sel_l = 0; + wxString sel = show_csv_configure_in_merge[0]; + if (sel.ToLong(&sel_l)) { + if (sel_l == 1) + GdaConst::show_csv_configure_in_merge = true; + else if (sel_l == 0) + GdaConst::show_csv_configure_in_merge = false; + } + } + vector enable_high_dpi_support = OGRDataAdapter::GetInstance().GetHistory("enable_high_dpi_support"); + if (!enable_high_dpi_support.empty()) { + long sel_l = 0; + wxString sel = enable_high_dpi_support[0]; + if (sel.ToLong(&sel_l)) { + if (sel_l == 1) + GdaConst::enable_high_dpi_support = true; + else if (sel_l == 0) + GdaConst::enable_high_dpi_support = false; + } + } + vector gdal_http_timeout = OGRDataAdapter::GetInstance().GetHistory("gdal_http_timeout"); + if (!gdal_http_timeout.empty()) { + long sel_l = 0; + wxString sel = gdal_http_timeout[0]; + if (sel.ToLong(&sel_l)) { + GdaConst::gdal_http_timeout = sel_l; + } + } + + vector gda_datetime_formats_str = OGRDataAdapter::GetInstance().GetHistory("gda_datetime_formats_str"); + if (!gda_datetime_formats_str.empty()) { + wxString patterns = gda_datetime_formats_str[0]; + wxStringTokenizer tokenizer(patterns, ","); + while ( tokenizer.HasMoreTokens() ) + { + wxString token = tokenizer.GetNextToken(); + GdaConst::gda_datetime_formats.push_back(token); + } + GdaConst::gda_datetime_formats_str = patterns; + } + + vector gda_user_seed = OGRDataAdapter::GetInstance().GetHistory("gda_user_seed"); + if (!gda_user_seed.empty()) { + long sel_l = 0; + wxString sel = gda_user_seed[0]; + if (sel.ToLong(&sel_l)) { + GdaConst::gda_user_seed = sel_l; + } + } + vector use_gda_user_seed = OGRDataAdapter::GetInstance().GetHistory("use_gda_user_seed"); + if (!use_gda_user_seed.empty()) { + long sel_l = 0; + wxString sel = use_gda_user_seed[0]; + if (sel.ToLong(&sel_l)) { + if (sel_l == 1) { + GdaConst::use_gda_user_seed = true; + srand(GdaConst::gda_user_seed); + } else if (sel_l == 0) { + GdaConst::use_gda_user_seed = false; + } + } + } + + vector gda_set_cpu_cores = OGRDataAdapter::GetInstance().GetHistory("gda_set_cpu_cores"); + if (!gda_set_cpu_cores.empty()) { + long sel_l = 0; + wxString sel = gda_set_cpu_cores[0]; + if (sel.ToLong(&sel_l)) { + if (sel_l == 1) + GdaConst::gda_set_cpu_cores = true; + else if (sel_l == 0) + GdaConst::gda_set_cpu_cores = false; + } + } + vector gda_cpu_cores = OGRDataAdapter::GetInstance().GetHistory("gda_cpu_cores"); + if (!gda_cpu_cores.empty()) { + long sel_l = 0; + wxString sel = gda_cpu_cores[0]; + if (sel.ToLong(&sel_l)) { + GdaConst::gda_cpu_cores = sel_l; + } + } + + vector gda_eigen_tol = OGRDataAdapter::GetInstance().GetHistory("gda_eigen_tol"); + if (!gda_eigen_tol.empty()) { + double sel_l = 0; + wxString sel = gda_eigen_tol[0]; + if (sel.ToDouble(&sel_l)) { + GdaConst::gda_eigen_tol = sel_l; + } + } + + vector gda_ui_language = OGRDataAdapter::GetInstance().GetHistory("gda_ui_language"); + if (!gda_ui_language.empty()) { + long sel_l = 0; + wxString sel = gda_ui_language[0]; + if (sel.ToLong(&sel_l)) { + GdaConst::gda_ui_language = sel_l; + } + } + + vector gda_use_gpu = OGRDataAdapter::GetInstance().GetHistory("gda_use_gpu"); + if (!gda_use_gpu.empty()) { + long sel_l = 0; + wxString sel = gda_use_gpu[0]; + if (sel.ToLong(&sel_l)) { + if (sel_l == 1) + GdaConst::gda_use_gpu = true; + else if (sel_l == 0) + GdaConst::gda_use_gpu = false; + } + } + + // following are not in this UI, but still global variable + vector gda_user_email = OGRDataAdapter::GetInstance().GetHistory("gda_user_email"); + if (!gda_user_email.empty()) { + wxString email = gda_user_email[0]; + GdaConst::gda_user_email = email; + } + +} + +void PreferenceDlg::OnChooseLanguage(wxCommandEvent& ev) +{ + int lan_sel = ev.GetSelection(); + GdaConst::gda_ui_language = lan_sel; + wxString sel_str; + sel_str << GdaConst::gda_ui_language; + OGRDataAdapter::GetInstance().AddEntry("gda_ui_language", sel_str); + + // also update the lang/config.ini content + wxString exePath = wxStandardPaths::Get().GetExecutablePath(); + wxFileName exeFile(exePath); + wxString exeDir = exeFile.GetPathWithSep(); + wxString configPath = exeDir + "lang" + wxFileName::GetPathSeparator() + "config.ini"; + wxConfigBase * config = new wxFileConfig("GeoDa", wxEmptyString, configPath); + + if (lan_sel > 0) { + long language = wxLANGUAGE_UNKNOWN; + if (lan_sel == 1) { + language = wxLANGUAGE_ENGLISH + 1; + } else if (lan_sel == 2) { + language = 45;//wxLANGUAGE_CHINESE + 1; + } else if (lan_sel == 3) { + language = 179;//wxLANGUAGE_SPANISH; + } else if (lan_sel == 4) { + language = 88; // wxLANGUAGE_GERMAN + } + config->DeleteEntry("Translation"); + config->SetPath("Translation"); + config->Write("Language", language); + config->Flush(); + delete config; + } + + wxString msg = _("Please restart GeoDa to apply the language setup."); + wxMessageDialog dlg(NULL, msg, _("Info"), wxOK | wxICON_INFORMATION); + dlg.ShowModal(); +} +void PreferenceDlg::OnDateTimeInput(wxCommandEvent& ev) +{ + GdaConst::gda_datetime_formats.clear(); + wxString formats_str = txt24->GetValue(); + wxStringTokenizer tokenizer(formats_str, ","); + while ( tokenizer.HasMoreTokens() ) + { + wxString token = tokenizer.GetNextToken(); + GdaConst::gda_datetime_formats.push_back(token); + } + GdaConst::gda_datetime_formats_str = formats_str; + OGRDataAdapter::GetInstance().AddEntry("gda_datetime_formats_str", formats_str); +} + +void PreferenceDlg::OnTimeoutInput(wxCommandEvent& ev) +{ + wxString sec_str = txt23->GetValue(); + long sec; + if (sec_str.ToLong(&sec)) { + if (sec >= 0) { + GdaConst::gdal_http_timeout = sec; + OGRDataAdapter::GetInstance().AddEntry("gdal_http_timeout", sec_str); + CPLSetConfigOption("GDAL_HTTP_TIMEOUT", sec_str); + } + } +} + +void PreferenceDlg::OnSlider1(wxCommandEvent& ev) +{ + int val = slider1->GetValue(); + GdaConst::transparency_highlighted = val; + wxString transp_str; + transp_str << val; + OGRDataAdapter::GetInstance().AddEntry("transparency_highlighted", transp_str); + wxTextCtrl* txt_ctl = wxDynamicCast(FindWindow(XRCID("PREF_SLIDER1_TXT")), wxTextCtrl); + + wxString t_hl = wxString::Format("%.2f", (255 - val) / 255.0); + txt_ctl->SetValue(t_hl); + + if (highlight_state) { + highlight_state->SetEventType(HLStateInt::transparency); + highlight_state->notifyObservers(); + } +} +void PreferenceDlg::OnSlider2(wxCommandEvent& ev) +{ + int val = slider2->GetValue(); + GdaConst::transparency_unhighlighted = val; + wxString transp_str; + transp_str << val; + OGRDataAdapter::GetInstance().AddEntry("transparency_unhighlighted", transp_str); + wxTextCtrl* txt_ctl = wxDynamicCast(FindWindow(XRCID("PREF_SLIDER2_TXT")), wxTextCtrl); + + wxString t_hl = wxString::Format("%.2f", (255 - val) / 255.0); + txt_ctl->SetValue(t_hl); + + if (highlight_state) { + highlight_state->SetEventType(HLStateInt::transparency); + highlight_state->notifyObservers(); + } +} +void PreferenceDlg::OnSlider6(wxCommandEvent& ev) +{ + int val = slider6->GetValue(); + GdaConst::plot_transparency_highlighted = val; + wxString transp_str; + transp_str << val; + OGRDataAdapter::GetInstance().AddEntry("plot_transparency_highlighted", transp_str); + wxTextCtrl* txt_ctl = wxDynamicCast(FindWindow(XRCID("PREF_SLIDER6_TXT")), wxTextCtrl); + + wxString t_hl = wxString::Format("%.2f", (255 - val) / 255.0); + txt_ctl->SetValue(t_hl); + + if (highlight_state) { + highlight_state->SetEventType(HLStateInt::transparency); + highlight_state->notifyObservers(); + } +} +void PreferenceDlg::OnSlider7(wxCommandEvent& ev) +{ + int val = slider7->GetValue(); + GdaConst::plot_transparency_unhighlighted = val; + wxString transp_str; + transp_str << val; + OGRDataAdapter::GetInstance().AddEntry("plot_transparency_unhighlighted", transp_str); + wxTextCtrl* txt_ctl = wxDynamicCast(FindWindow(XRCID("PREF_SLIDER7_TXT")), wxTextCtrl); + + wxString t_hl = wxString::Format("%.2f", (255 - val) / 255.0); + txt_ctl->SetValue(t_hl); + + if (highlight_state) { + highlight_state->SetEventType(HLStateInt::transparency); + highlight_state->notifyObservers(); + } +} + +void PreferenceDlg::OnChoice3(wxCommandEvent& ev) +{ + int basemap_sel = ev.GetSelection(); + if (basemap_sel <= 0) { + GdaConst::use_basemap_by_default = false; + OGRDataAdapter::GetInstance().AddEntry("use_basemap_by_default", "0"); + } + else { + GdaConst::use_basemap_by_default = true; + GdaConst::default_basemap_selection = basemap_sel; + wxString sel_str; + sel_str << GdaConst::default_basemap_selection; + OGRDataAdapter::GetInstance().AddEntry("use_basemap_by_default", "1"); + OGRDataAdapter::GetInstance().AddEntry("default_basemap_selection", sel_str); + } +} + +void PreferenceDlg::OnCrossHatch(wxCommandEvent& ev) +{ + int crosshatch_sel = ev.GetSelection(); + if (crosshatch_sel == 0) { + GdaConst::use_cross_hatching = false; + OGRDataAdapter::GetInstance().AddEntry("use_cross_hatching", "0"); + } + else if (crosshatch_sel == 1) { + GdaConst::use_cross_hatching = true; + OGRDataAdapter::GetInstance().AddEntry("use_cross_hatching", "1"); + } + if (highlight_state) { + highlight_state->notifyObservers(); + } +} + +void PreferenceDlg::OnHideTablePostGIS(wxCommandEvent& ev) +{ + int sel = ev.GetSelection(); + if (sel == 0) { + GdaConst::hide_sys_table_postgres = false; + OGRDataAdapter::GetInstance().AddEntry("hide_sys_table_postgres", "0"); + } + else { + GdaConst::hide_sys_table_postgres = true; + OGRDataAdapter::GetInstance().AddEntry("hide_sys_table_postgres", "1"); + } +} + +void PreferenceDlg::OnHideTableSQLITE(wxCommandEvent& ev) +{ + int sel = ev.GetSelection(); + if (sel == 0) { + GdaConst::hide_sys_table_sqlite = false; + OGRDataAdapter::GetInstance().AddEntry("hide_sys_table_sqlite", "0"); + } + else { + GdaConst::hide_sys_table_sqlite = true; + OGRDataAdapter::GetInstance().AddEntry("hide_sys_table_sqlite", "1"); + + } +} +void PreferenceDlg::OnDisableCrashDetect(wxCommandEvent& ev) +{ + int sel = ev.GetSelection(); + if (sel == 0) { + GdaConst::disable_crash_detect = false; + OGRDataAdapter::GetInstance().AddEntry("disable_crash_detect", "0"); + } + else { + GdaConst::disable_crash_detect = true; + OGRDataAdapter::GetInstance().AddEntry("disable_crash_detect", "1"); + + } +} +void PreferenceDlg::OnDisableAutoUpgrade(wxCommandEvent& ev) +{ + int sel = ev.GetSelection(); + if (sel == 0) { + GdaConst::disable_auto_upgrade = false; + OGRDataAdapter::GetInstance().AddEntry("disable_auto_upgrade", "0"); + } + else { + GdaConst::disable_auto_upgrade = true; + OGRDataAdapter::GetInstance().AddEntry("disable_auto_upgrade", "1"); + + } +} +void PreferenceDlg::OnShowRecent(wxCommandEvent& ev) +{ + int sel = ev.GetSelection(); + if (sel == 0) { + GdaConst::show_recent_sample_connect_ds_dialog = false; + OGRDataAdapter::GetInstance().AddEntry("show_recent_sample_connect_ds_dialog", "0"); + } + else { + GdaConst::show_recent_sample_connect_ds_dialog = true; + OGRDataAdapter::GetInstance().AddEntry("show_recent_sample_connect_ds_dialog", "1"); + + } +} +void PreferenceDlg::OnShowCsvInMerge(wxCommandEvent& ev) +{ + int sel = ev.GetSelection(); + if (sel == 0) { + GdaConst::show_csv_configure_in_merge = false; + OGRDataAdapter::GetInstance().AddEntry("show_csv_configure_in_merge", "0"); + } + else { + GdaConst::show_csv_configure_in_merge = true; + OGRDataAdapter::GetInstance().AddEntry("show_csv_configure_in_merge", "1"); + } +} +void PreferenceDlg::OnEnableHDPISupport(wxCommandEvent& ev) +{ + int sel = ev.GetSelection(); + if (sel == 0) { + GdaConst::enable_high_dpi_support = false; + OGRDataAdapter::GetInstance().AddEntry("enable_high_dpi_support", "0"); + } + else { + GdaConst::enable_high_dpi_support = true; + OGRDataAdapter::GetInstance().AddEntry("enable_high_dpi_support", "1"); + } +} +void PreferenceDlg::OnUseSpecifiedSeed(wxCommandEvent& ev) +{ + int sel = ev.GetSelection(); + if (sel == 0) { + GdaConst::use_gda_user_seed = false; + OGRDataAdapter::GetInstance().AddEntry("use_gda_user_seed", "0"); + } + else { + GdaConst::use_gda_user_seed = true; + OGRDataAdapter::GetInstance().AddEntry("use_gda_user_seed", "1"); + } +} +void PreferenceDlg::OnSeedEnter(wxCommandEvent& ev) +{ + wxString val = txt_seed->GetValue(); + long _val; + if (val.ToLong(&_val)) { + GdaConst::gda_user_seed = _val; + OGRDataAdapter::GetInstance().AddEntry("gda_user_seed", val); + } +} +void PreferenceDlg::OnSetCPUCores(wxCommandEvent& ev) +{ + int sel = ev.GetSelection(); + if (sel == 0) { + GdaConst::gda_set_cpu_cores = false; + OGRDataAdapter::GetInstance().AddEntry("gda_set_cpu_cores", "0"); + txt_cores->Disable(); + } + else { + GdaConst::gda_set_cpu_cores = true; + OGRDataAdapter::GetInstance().AddEntry("gda_set_cpu_cores", "1"); + txt_cores->Enable(); + } +} +void PreferenceDlg::OnCPUCoresEnter(wxCommandEvent& ev) +{ + wxString val = txt_cores->GetValue(); + long _val; + if (val.ToLong(&_val)) { + GdaConst::gda_cpu_cores = _val; + OGRDataAdapter::GetInstance().AddEntry("gda_cpu_cores", val); + } +} + +void PreferenceDlg::OnPowerEpsEnter(wxCommandEvent& ev) +{ + wxString val = txt_poweriter_eps->GetValue(); + double _val; + if (val.ToDouble(&_val)) { + GdaConst::gda_eigen_tol = _val; + OGRDataAdapter::GetInstance().AddEntry("gda_eigen_tol", val); + } +} +void PreferenceDlg::OnUseGPU(wxCommandEvent& ev) +{ + int sel = ev.GetSelection(); + if (sel == 0) { + GdaConst::gda_use_gpu = false; + OGRDataAdapter::GetInstance().AddEntry("gda_use_gpu", "0"); + } + else { + GdaConst::gda_use_gpu = true; + OGRDataAdapter::GetInstance().AddEntry("gda_use_gpu", "1"); + } +} diff --git a/DialogTools/PreferenceDlg.h b/DialogTools/PreferenceDlg.h new file mode 100644 index 000000000..41f13aafa --- /dev/null +++ b/DialogTools/PreferenceDlg.h @@ -0,0 +1,146 @@ +/** + * GeoDa TM, Copyright (C) 2011-2015 by Luc Anselin - all rights reserved + * + * This file is part of GeoDa. + * + * GeoDa is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * GeoDa is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#ifndef __GEODA_CENTER_PREFERENCE_DLG_H__ +#define __GEODA_CENTER_PREFERENCE_DLG_H__ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../HLStateInt.h" +#include "../HighlightStateObserver.h" + +using namespace std; + +//////////////////////////////////////////////////////////////////////////////// +// +// PreferenceDlg +// +//////////////////////////////////////////////////////////////////////////////// +class PreferenceDlg : public wxDialog +{ +public: + PreferenceDlg(wxWindow* parent, + wxWindowID id = wxID_ANY, + const wxString& title = _("GeoDa Preference Setup"), + const wxPoint& pos = wxDefaultPosition, + const wxSize& size = wxSize(580,680)); + + PreferenceDlg(wxWindow* parent, + HLStateInt* highlight_state, + wxWindowID id = wxID_ANY, + const wxString& title = _("GeoDa Preference Setup"), + const wxPoint& pos = wxDefaultPosition, + const wxSize& size = wxSize(580,680)); + + static void ReadFromCache(); + +protected: + HLStateInt* highlight_state; + // PREF_USE_CROSSHATCH + wxCheckBox* cbox0; + // PREF_SLIDER1_TXT + wxSlider* slider1; + wxTextCtrl* slider_txt1; + // PREF_SLIDER2_TXT + wxSlider* slider2; + wxTextCtrl* slider_txt2; + // basemap auto + wxComboBox* cmb33; + // Transparency of highlighted object + wxSlider* slider6; + // plot unhighlighted transp + wxSlider* slider7; + wxTextCtrl* slider_txt7; + // crash detect + wxCheckBox* cbox4; + // auto upgrade + wxCheckBox* cbox5; + // use seed + wxCheckBox* cbox6; + // seed value + wxTextCtrl* txt_seed; + // show recent + wxCheckBox* cbox8; + // show cvs in merge + wxCheckBox* cbox9; + // enable High DPI + wxCheckBox* cbox10; + // postgresql + wxCheckBox* cbox21; + // sqlite + wxCheckBox* cbox22; + // timeout + wxTextCtrl* txt23; + // data/tome + wxTextCtrl* txt24; + // cpu cores + wxCheckBox* cbox18; + wxTextCtrl* txt_cores; + // eps of power iteration + wxTextCtrl* txt_poweriter_eps; + // lanuage + wxComboBox* cmb113; + // gpu + wxCheckBox* cbox_gpu; + + void Init(); + void SetupControls(); + + + void OnChooseLanguage(wxCommandEvent& ev); + void OnCrossHatch(wxCommandEvent& ev); + void OnSlider1(wxCommandEvent& ev); + void OnSlider2(wxCommandEvent& ev); + //void OnSlider3(wxCommandEvent& ev); + void OnChoice3(wxCommandEvent& ev); + void OnDisableCrashDetect(wxCommandEvent& ev); + void OnDisableAutoUpgrade(wxCommandEvent& ev); + void OnShowRecent(wxCommandEvent& ev); + void OnShowCsvInMerge(wxCommandEvent& ev); + void OnEnableHDPISupport(wxCommandEvent& ev); + + void OnSlider6(wxCommandEvent& ev); + void OnSlider7(wxCommandEvent& ev); + + void OnHideTablePostGIS(wxCommandEvent& ev); + void OnHideTableSQLITE(wxCommandEvent& ev); + void OnTimeoutInput(wxCommandEvent& ev); + void OnDateTimeInput(wxCommandEvent& ev); + + void OnUseSpecifiedSeed(wxCommandEvent& ev); + void OnSeedEnter(wxCommandEvent& ev); + + void OnSetCPUCores(wxCommandEvent& ev); + void OnCPUCoresEnter(wxCommandEvent& ev); + + void OnPowerEpsEnter(wxCommandEvent& ev); + void OnUseGPU(wxCommandEvent& ev); + + void OnReset(wxCommandEvent& ev); +}; + +#endif diff --git a/DialogTools/RandomizationDlg.cpp b/DialogTools/RandomizationDlg.cpp index 2f01cb157..e132e9312 100644 --- a/DialogTools/RandomizationDlg.cpp +++ b/DialogTools/RandomizationDlg.cpp @@ -33,6 +33,202 @@ #include "RandomizationDlg.h" +///////////////////////////////////////////////////////////////////////////// +// +// -------------------------------------- +// | Inference Settings | +// |-------------------------------------| +// | | +// | Bonferroni Bounds: __0.43__ | +// | | +// | False Discovery Rate: __0.____ | +// | | +// | Use specified p-value: _______ | +// | | +// | | +// | | +// | [ O K ] [ Cancel ] | +// -------------------------------------- +///////////////////////////////////////////////////////////////////////////// + +BEGIN_EVENT_TABLE( InferenceSettingsDlg, wxDialog ) +EVT_BUTTON( wxID_OK, InferenceSettingsDlg::OnOkClick ) +END_EVENT_TABLE() + +InferenceSettingsDlg::InferenceSettingsDlg(wxWindow* parent, + double _p_cutoff, + double* _p_vals, + int _n, + const wxString& title, + wxWindowID id, + const wxPoint& pos, + const wxSize& size ) +: wxDialog(parent, id, title, pos, size), p_cutoff(_p_cutoff), p_vals(_p_vals), n(_n), fdr(0), bo(0), user_input(0) +{ + wxLogMessage("Open InferenceSettingsDlg."); + + wxString p_str = wxString::Format("%g", p_cutoff); + wxPanel *panel = new wxPanel(this); + wxBoxSizer *vbox = new wxBoxSizer(wxVERTICAL); + + // Parameters + wxFlexGridSizer* gbox = new wxFlexGridSizer(9,2,10,0); + + m_rdo_1 = new wxRadioButton(panel, -1, _("Bonferroni bound:"), wxDefaultPosition, wxDefaultSize, wxRB_GROUP); + m_txt_bo = new wxStaticText(panel, wxID_ANY, _(""), wxDefaultPosition, wxSize(150,-1)); + gbox->Add(m_rdo_1, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT | wxLEFT, 10); + gbox->Add(m_txt_bo, 1, wxEXPAND); + + m_rdo_2 = new wxRadioButton(panel, -1, _("False Discovery Rate:"), wxDefaultPosition, wxDefaultSize); + m_txt_fdr = new wxStaticText(panel, wxID_ANY, _(""), wxDefaultPosition, wxSize(150,-1)); + gbox->Add(m_rdo_2, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT | wxLEFT, 10); + gbox->Add(m_txt_fdr, 1, wxEXPAND); + + m_rdo_3 = new wxRadioButton(panel, -1, _("Input significance:"), wxDefaultPosition, wxDefaultSize); + m_txt_pval = new wxTextCtrl(panel, XRCID("ID_INFERENCE_TCTRL"), p_str, wxDefaultPosition, wxSize(100,-1),wxTE_PROCESS_ENTER); + m_txt_pval->SetValidator(wxTextValidator(wxFILTER_NUMERIC)); + Connect(XRCID("ID_INFERENCE_TCTRL"), wxEVT_TEXT, + wxCommandEventHandler(InferenceSettingsDlg::OnAlphaTextCtrl)); + gbox->Add(m_rdo_3, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT | wxLEFT, 10); + gbox->Add(m_txt_pval, 1, wxEXPAND); + m_rdo_3->SetValue(true); + + // Buttons + wxButton *okButton = new wxButton(panel, wxID_OK, _("OK"), + wxDefaultPosition, wxSize(70, 30)); + wxButton *closeButton = new wxButton(panel, wxID_CANCEL, _("Close"), + wxDefaultPosition, wxSize(70, 30)); + wxBoxSizer *hbox2 = new wxBoxSizer(wxHORIZONTAL); + hbox2->Add(okButton, 1, wxALIGN_CENTER | wxALL, 5); + hbox2->Add(closeButton, 1, wxALIGN_CENTER | wxALL, 5); + + // Container + chk_pval = new wxCheckBox(panel, wxID_ANY, _("Use selected as specified alpha level")); + chk_pval->SetValue(true); + chk_pval->Hide(); + //vbox->Add(m_txt_title, 0, wxALIGN_CENTER, 10); + vbox->Add(gbox, 1, wxEXPAND | wxALL, 10); + //vbox->Add(chk_pval, 0, wxALIGN_CENTER | wxALL, 10); + vbox->Add(hbox2, 0, wxALIGN_CENTER | wxALL, 10); + + wxBoxSizer *container = new wxBoxSizer(wxHORIZONTAL); + container->Add(vbox); + + panel->SetSizer(container); + + wxBoxSizer* sizerAll = new wxBoxSizer(wxVERTICAL); + sizerAll->Add(panel, 1, wxEXPAND|wxALL, 0); + SetSizer(sizerAll); + SetAutoLayout(true); + sizerAll->Fit(this); + + Centre(); + + Init(p_vals, n, p_cutoff); +} + +int compare (const void * a, const void * b) +{ + if (*(double*)a > *(double*)b) return 1; + else if (*(double*)a < *(double*)b) return -1; + else return 0; +} + +void InferenceSettingsDlg::Init(double* p_vals, int n, double current_p) +{ + double bonferroni_bound = current_p / (double)n; + wxString bo_str = wxString::Format("%g", bonferroni_bound);; + m_txt_bo->SetLabel(bo_str); + + std::vector pvals; + for (int i=0; i= p_start) { + if (i_0 == i) { + stop = true; + } + i_0 = i; + break; + } + } + if (i_0 < 0) + stop = true; + + // compute p* = i_0 x alpha / N + p_start = i_0 * current_p / (double)n ; + } + + wxString fdr_str; + + if (i_0 >= 0) + fdr_str = wxString::Format("%g", p_start); + else { + fdr_str = "nan"; + p_start = 0.0; + } + + m_txt_fdr->SetLabel(fdr_str); + + bo = bonferroni_bound; + fdr = p_start; +} + +void InferenceSettingsDlg::OnAlphaTextCtrl(wxCommandEvent& ev) +{ + wxString val = m_txt_pval->GetValue(); + val.Trim(false); + val.Trim(true); + double pval; + bool is_valid = val.ToDouble(&pval); + if (is_valid) { + if (pval > 1 ) { + m_txt_pval->SetValue("1.0"); + pval = 1; + } else if (pval < 0) { + m_txt_pval->SetValue("0"); + pval = 0; + } + user_input = pval; + Init(p_vals, n, pval); + } + ev.Skip(); +} + +void InferenceSettingsDlg::OnOkClick( wxCommandEvent& event ) +{ + wxLogMessage("In InferenceSettingsDlg::OnOkClick()"); + + if (chk_pval->GetValue()) { + wxString p_val = m_txt_pval->GetValue(); + p_val.ToDouble(&user_input); + + if (m_rdo_3->GetValue()) { + p_cutoff = user_input; + } else if (m_rdo_1->GetValue()) { + p_cutoff = bo; + } else if (m_rdo_2->GetValue()) { + p_cutoff = fdr; + } + + EndDialog(wxID_OK); + } else { + EndDialog(wxID_CANCEL); + } +} + +///////////////////////////////////////////////////////////////////////////// + RandomizationPanel::RandomizationPanel(const std::vector& raw_data1_s, const std::vector& undefs_s, const GalElement* W_s, int NumPermutations, @@ -129,6 +325,10 @@ void RandomizationPanel::CalcMoran() for (int i=0; iPerm(num_obs, perm, theRands); + rng->Perm(undefs, num_obs, perm, theRands); double newMoran = 0; if (is_bivariate) { for (int i=0; i 0) { + valid_num_obs++; + } + } + newMoran /= (double) valid_num_obs - 1.0; // find its place in the distribution MoranI[ totFrequency++ ] = newMoran; int newBin = (int)floor( (newMoran - start)/range ); - if (newBin < 0) newBin = 0; - else if (newBin >= bins) newBin = bins-1; + if (newBin < 0) { + newBin = 0; + } else if (newBin >= bins) { + newBin = bins-1; + } freq[newBin] = freq[newBin] + 1; if (newBin < minBin) minBin = newBin; @@ -238,6 +453,13 @@ void RandomizationPanel::RunRandomTrials() void RandomizationPanel::UpdateStatistics() { + int valid_num_obs = 0; + for (int i=0; i 0) { + valid_num_obs++; + } + } + double sMoran = 0; for (int i=0; i < totFrequency; i++) { sMoran += MoranI[i]; @@ -260,7 +482,7 @@ void RandomizationPanel::UpdateStatistics() } pseudo_p_val = (((double) signFrequency)+1.0)/(((double) totFrequency)+1.0); - expected_val = (double) -1/(num_obs - 1); + expected_val = (double) -1/(valid_num_obs - 1); } void RandomizationPanel::DrawRectangle(wxDC* dc, int left, int top, int right, @@ -289,15 +511,18 @@ void RandomizationPanel::Draw(wxDC* dc) DrawRectangle(dc, 0, 0, sz.x, sz.y, GdaConst::canvas_background_color); int fMax = freq_back[0]; - for (int i=1; i 0) { @@ -321,7 +546,7 @@ void RandomizationPanel::Draw(wxDC* dc) DrawRectangle(dc, Left + thresholdBin*binX, Top, Left + (thresholdBin+1)*binX, Top+ Height, //GdaConst::highlight_color ); - wxColour(49, 163, 84)); + wxColour(49, 163, 84)); // green for origial Moran's I wxPen drawPen(*wxBLACK_PEN); drawPen.SetColour(GdaConst::textColor); @@ -330,7 +555,7 @@ void RandomizationPanel::Draw(wxDC* dc) //dc->DrawLine(Left, Top, Left, Top+Height); // Vertical axis dc->DrawLine(Left, Top+Height, Left+Width, Top+Height); // Horizontal axis - drawPen.SetColour(wxColour(20, 20, 20)); + drawPen.SetColour(wxColour(20, 20, 20)); // black dc->SetPen(drawPen); dc->SetBrush(*wxWHITE_BRUSH); const int hZero= (int)(Left+(0-start)/(stop-start)*Width); @@ -346,7 +571,9 @@ void RandomizationPanel::Draw(wxDC* dc) drawPen.SetColour(GdaConst::textColor); dc->SetPen(drawPen); double zval = 0; - if (MSdev != 0) zval = (Moran-MMean)/MSdev; + if (MSdev != 0) { + zval = (Moran-MMean)/MSdev; + } wxString text; dc->SetTextForeground(wxColour(0,0,0)); text = wxString::Format("I: %-7.4f E[I]: %-7.4f mean: %-7.4f" @@ -430,6 +657,7 @@ RandomizationDlg::RandomizationDlg(const std::vector& raw_data1_s, const GalWeight* W_s, const std::vector& _undef, const std::vector& hl, + bool _is_regime, int NumPermutations, bool reuse_user_seed, uint64_t user_specified_seed, @@ -438,7 +666,7 @@ RandomizationDlg::RandomizationDlg(const std::vector& raw_data1_s, const wxPoint& pos, const wxSize& size, long style ) : wxFrame(parent, id, "", wxDefaultPosition, wxSize(550,300)), -copy_w(NULL), copy_w_sel(NULL), copy_w_unsel(NULL) +copy_w(NULL), copy_w_sel(NULL), copy_w_unsel(NULL), is_regime(_is_regime) { wxLogMessage("Open RandomizationDlg (bivariate)."); @@ -471,7 +699,7 @@ copy_w(NULL), copy_w_sel(NULL), copy_w_unsel(NULL) panel = new RandomizationPanel(raw_data1_s, raw_data2_s, _undef, W, NumPermutations, reuse_user_seed, user_specified_seed, this, sz); - if ( has_hl) { + if ( has_hl && is_regime) { std::vector sel_undefs(num_obs, false); for (int i=0; i& raw_data1_s, const GalWeight* W_s, const std::vector& _undef, const std::vector& hl, + bool _is_regime, int NumPermutations, bool reuse_user_seed, uint64_t user_specified_seed, @@ -507,7 +736,7 @@ RandomizationDlg::RandomizationDlg( const std::vector& raw_data1_s, const wxPoint& pos, const wxSize& size, long style ) : wxFrame(parent, id, "", wxDefaultPosition, wxSize(550,300)), -copy_w(NULL), copy_w_sel(NULL), copy_w_unsel(NULL) +copy_w(NULL), copy_w_sel(NULL), copy_w_unsel(NULL), is_regime(_is_regime) { wxLogMessage("Open RandomizationDlg (univariate)."); @@ -537,7 +766,7 @@ copy_w(NULL), copy_w_sel(NULL), copy_w_unsel(NULL) panel = new RandomizationPanel(raw_data1_s, _undef, W, NumPermutations, reuse_user_seed, user_specified_seed, this, sz); - if ( has_hl) { + if ( has_hl && is_regime ) { std::vector sel_undefs(num_obs, false); for (int i=0; iAdd(button, 0, wxALIGN_CENTER | wxALIGN_TOP | wxALL, 10); @@ -598,7 +827,7 @@ void RandomizationDlg::CreateControls() void RandomizationDlg::CreateControls_regime() { - wxButton *button = new wxButton(this, ID_BUTTON, wxT("Run")); + wxButton *button = new wxButton(this, ID_BUTTON, _("Run")); wxBoxSizer* panel_box = new wxBoxSizer(wxVERTICAL); panel_box->Add(button, 0, wxALIGN_CENTER | wxALIGN_TOP | wxALL, 10); diff --git a/DialogTools/RandomizationDlg.h b/DialogTools/RandomizationDlg.h index e434f5b50..91ecdcd9b 100644 --- a/DialogTools/RandomizationDlg.h +++ b/DialogTools/RandomizationDlg.h @@ -21,6 +21,10 @@ #define __GEODA_CENTER_RANDOMIZATION_DLG_H__ #include +#include +#include +#include + #include "../ShapeOperations/GalWeight.h" #include "../ShapeOperations/Randik.h" @@ -28,6 +32,47 @@ class GalElement; +class InferenceSettingsDlg : public wxDialog +{ +public: + InferenceSettingsDlg(wxWindow* parent, + double p_cutoff, + double* p_vals, + int n, + const wxString& title = _("Inference Settings"), + wxWindowID id = wxID_ANY, + const wxPoint& pos = wxDefaultPosition, + const wxSize& size = wxDefaultSize ); + + void OnAlphaTextCtrl(wxCommandEvent& ev); + double GetAlphaLevel() { return p_cutoff;} + double GetBO() {return bo;} + double GetFDR() { return fdr; } + double GetUserInput() { return user_input;} + +protected: + double bo; + double fdr; + double p_cutoff; + double user_input; + double* p_vals; + int n; + + wxRadioButton* m_rdo_1; + wxRadioButton* m_rdo_2; + wxRadioButton* m_rdo_3; + wxStaticText* m_txt_bo; + wxStaticText* m_txt_fdr; + wxTextCtrl* m_txt_pval; + wxCheckBox* chk_pval; + + void Init(double* p_vals, int n, double current_p); + + void OnOkClick( wxCommandEvent& event ); + + DECLARE_EVENT_TABLE() +}; + class RandomizationPanel: public wxPanel { public: @@ -110,6 +155,7 @@ class RandomizationDlg: public wxFrame const GalWeight* W, const std::vector& undef, const std::vector& hl, + bool is_regime, int NumPermutations, bool reuse_user_seed, uint64_t user_specified_seed, @@ -123,6 +169,7 @@ class RandomizationDlg: public wxFrame const GalWeight* W, const std::vector& undef, const std::vector& hl, + bool is_regime, int NumPermutations, bool reuse_user_seed, uint64_t user_specified_seed, @@ -145,6 +192,7 @@ class RandomizationDlg: public wxFrame RandomizationPanel* panel_sel; RandomizationPanel* panel_unsel; + bool is_regime; GalWeight* copy_w; GalWeight* copy_w_sel; GalWeight* copy_w_unsel; diff --git a/DialogTools/RangeSelectionDlg.cpp b/DialogTools/RangeSelectionDlg.cpp index f60be567c..37168b897 100644 --- a/DialogTools/RangeSelectionDlg.cpp +++ b/DialogTools/RangeSelectionDlg.cpp @@ -295,7 +295,7 @@ void RangeSelectionDlg::OnSelRangeClick( wxCommandEvent& event ) } } else { wxString msg("Selected field is should be numeric."); - wxMessageDialog dlg (this, msg, "Error", wxOK | wxICON_ERROR); + wxMessageDialog dlg (this, msg, _("Error"), wxOK | wxICON_ERROR); dlg.ShowModal(); return; } @@ -536,14 +536,14 @@ void RangeSelectionDlg::OnApplySaveClick( wxCommandEvent& event ) table_int->SetColData(write_col, sf_tm, t); table_int->SetColUndefined(write_col, sf_tm, undefined); } else { - wxString msg = "Chosen field is not a numeric type. Please select a numeric type field."; + wxString msg = _("Chosen field is not a numeric type. Please select a numeric type field."); - wxMessageDialog dlg(this, msg, "Error", wxOK | wxICON_ERROR ); + wxMessageDialog dlg(this, msg, _("Error"), wxOK | wxICON_ERROR ); dlg.ShowModal(); return; } - wxString msg = "Values assigned to target field successfully."; + wxString msg = _("Values assigned to target field successfully."); wxMessageDialog dlg(this, msg, "Success", wxOK | wxICON_INFORMATION ); dlg.ShowModal(); } @@ -614,9 +614,6 @@ boost::uuids::uuid RangeSelectionDlg::GetWeightsId() if (!m_weights_choice) return boost::uuids::nil_uuid(); int sel = m_weights_choice->GetSelection(); if (sel < 0 || sel >= weights_ids.size()) return boost::uuids::nil_uuid(); - wxString s; - s << "RangeSelectionDlg::GetWeightsId() weight: "; - s << w_man_int->GetShortDispName(weights_ids[sel]); return weights_ids[sel]; } diff --git a/DialogTools/RedcapDlg.cpp b/DialogTools/RedcapDlg.cpp new file mode 100644 index 000000000..e8b506cf7 --- /dev/null +++ b/DialogTools/RedcapDlg.cpp @@ -0,0 +1,643 @@ +/** + * GeoDa TM, Copyright (C) 2011-2015 by Luc Anselin - all rights reserved + * + * This file is part of GeoDa. + * + * GeoDa is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * GeoDa is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include +#include +#include +#include + + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../VarCalc/WeightsManInterface.h" +#include "../ShapeOperations/OGRDataAdapter.h" +#include "../ShapeOperations/WeightUtils.h" +#include "../Explore/MapNewView.h" +#include "../Project.h" +#include "../Algorithms/DataUtils.h" +#include "../Algorithms/cluster.h" + + + +#include "../GeneralWxUtils.h" +#include "../GenUtils.h" +#include "SaveToTableDlg.h" +#include "RedcapDlg.h" + +using namespace SpanningTreeClustering; + +BEGIN_EVENT_TABLE( RedcapDlg, wxDialog ) +EVT_CLOSE( RedcapDlg::OnClose ) +END_EVENT_TABLE() + +RedcapDlg::RedcapDlg(wxFrame* parent_s, Project* project_s) +: redcap(NULL), AbstractClusterDlg(parent_s, project_s, _("REDCAP Settings")) +{ + wxLogMessage("Open REDCAP dialog."); + + parent = parent_s; + project = project_s; + weights = NULL; + + bool init_success = Init(); + + if (init_success == false) { + EndDialog(wxID_CANCEL); + } else { + CreateControls(); + } + frames_manager->registerObserver(this); +} + +RedcapDlg::~RedcapDlg() +{ + wxLogMessage("On RedcapDlg::~RedcapDlg"); + frames_manager->removeObserver(this); + if (redcap) { + delete redcap; + redcap = NULL; + } +} + +bool RedcapDlg::Init() +{ + wxLogMessage("On RedcapDlg::Init"); + if (project == NULL) + return false; + + table_int = project->GetTableInt(); + if (table_int == NULL) + return false; + + + table_int->GetTimeStrings(tm_strs); + + return true; +} + +void RedcapDlg::CreateControls() +{ + wxLogMessage("On RedcapDlg::CreateControls"); + wxScrolledWindow* scrl = new wxScrolledWindow(this, wxID_ANY, wxDefaultPosition, wxSize(820,780), wxHSCROLL|wxVSCROLL ); + scrl->SetScrollRate( 5, 5 ); + + wxPanel *panel = new wxPanel(scrl); + wxBoxSizer *vbox = new wxBoxSizer(wxVERTICAL); + + // Input + AddSimpleInputCtrls(panel, vbox); + + // Parameters + wxFlexGridSizer* gbox = new wxFlexGridSizer(11,2,5,0); + + wxStaticText* st16 = new wxStaticText(panel, wxID_ANY, _("Weights:"), + wxDefaultPosition, wxSize(128,-1)); + combo_weights = new wxChoice(panel, wxID_ANY, wxDefaultPosition, + wxSize(200,-1)); + gbox->Add(st16, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT | wxLEFT, 10); + gbox->Add(combo_weights, 1, wxEXPAND); + + wxStaticText* st20 = new wxStaticText(panel, wxID_ANY, _("Method:"), + wxDefaultPosition, wxSize(128,-1)); + wxString choices20[] = {"FirstOrder-SingleLinkage", "FullOrder-CompleteLinkage", "FullOrder-AverageLinkage", "FullOrder-SingleLinkage"}; + combo_method = new wxChoice(panel, wxID_ANY, wxDefaultPosition, wxSize(200,-1), 4, choices20); + combo_method->SetSelection(2); + + gbox->Add(st20, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT | wxLEFT, 10); + gbox->Add(combo_method, 1, wxEXPAND); + + // Minimum Bound Control + AddMinBound(panel, gbox); + + wxStaticText* st11 = new wxStaticText(panel, wxID_ANY, _("Maximum # of regions:"), + wxDefaultPosition, wxSize(128,-1)); + m_max_region = new wxTextCtrl(panel, wxID_ANY, "5", wxDefaultPosition, wxSize(200,-1)); + gbox->Add(st11, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT | wxLEFT, 10); + gbox->Add(m_max_region, 1, wxEXPAND); + + wxStaticText* st13 = new wxStaticText(panel, wxID_ANY, _("Distance Function:"), + wxDefaultPosition, wxSize(128,-1)); + wxString choices13[] = {"Euclidean", "Manhattan"}; + m_distance = new wxChoice(panel, wxID_ANY, wxDefaultPosition, wxSize(200,-1), 2, choices13); + m_distance->SetSelection(0); + gbox->Add(st13, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT | wxLEFT, 10); + gbox->Add(m_distance, 1, wxEXPAND); + + // Transformation + AddTransformation(panel, gbox); + + wxStaticText* st17 = new wxStaticText(panel, wxID_ANY, _("Use specified seed:"), + wxDefaultPosition, wxSize(128,-1)); + wxBoxSizer *hbox17 = new wxBoxSizer(wxHORIZONTAL); + chk_seed = new wxCheckBox(panel, wxID_ANY, ""); + seedButton = new wxButton(panel, wxID_OK, _("Change Seed")); + + hbox17->Add(chk_seed,0, wxALIGN_CENTER_VERTICAL); + hbox17->Add(seedButton,0,wxALIGN_CENTER_VERTICAL); + seedButton->Disable(); + gbox->Add(st17, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT | wxLEFT, 10); + gbox->Add(hbox17, 1, wxEXPAND); + + if (GdaConst::use_gda_user_seed) { + chk_seed->SetValue(true); + seedButton->Enable(); + } + + wxStaticBoxSizer *hbox = new wxStaticBoxSizer(wxHORIZONTAL, panel, _("Parameters:")); + hbox->Add(gbox, 1, wxEXPAND); + + + // Output + wxStaticText* st3 = new wxStaticText (panel, wxID_ANY, _("Save Cluster in Field:"), + wxDefaultPosition, wxDefaultSize); + m_textbox = new wxTextCtrl(panel, wxID_ANY, "CL", wxDefaultPosition, wxSize(158,-1)); + wxStaticBoxSizer *hbox1 = new wxStaticBoxSizer(wxHORIZONTAL, panel, _("Output:")); + hbox1->Add(st3, 0, wxALIGN_CENTER_VERTICAL); + hbox1->Add(m_textbox, 1, wxALIGN_CENTER_VERTICAL |wxLEFT, 10); + + + // Buttons + wxButton *okButton = new wxButton(panel, wxID_OK, _("Run"), wxDefaultPosition, + wxSize(70, 30)); + saveButton = new wxButton(panel, wxID_OK, _("Save Spanning Tree"), wxDefaultPosition, + wxSize(140, 30)); + wxButton *closeButton = new wxButton(panel, wxID_EXIT, _("Close"), + wxDefaultPosition, wxSize(70, 30)); + wxBoxSizer *hbox2 = new wxBoxSizer(wxHORIZONTAL); + hbox2->Add(okButton, 0, wxALIGN_CENTER | wxALL, 5); + hbox2->Add(saveButton, 0, wxALIGN_CENTER | wxALL, 5); + hbox2->Add(closeButton, 0, wxALIGN_CENTER | wxALL, 5); + saveButton->Disable(); + + // Container + vbox->Add(hbox, 0, wxALIGN_CENTER | wxALL, 10); + vbox->Add(hbox1, 0, wxEXPAND | wxTOP | wxLEFT | wxRIGHT, 10); + vbox->Add(hbox2, 0, wxALIGN_CENTER | wxALL, 10); + + // Summary control + wxBoxSizer *vbox1 = new wxBoxSizer(wxVERTICAL); + wxNotebook* notebook = AddSimpleReportCtrls(panel); + vbox1->Add(notebook, 1, wxEXPAND|wxALL,20); + + wxBoxSizer *container = new wxBoxSizer(wxHORIZONTAL); + container->Add(vbox); + container->Add(vbox1,1, wxEXPAND | wxALL); + + panel->SetSizer(container); + + wxBoxSizer* panelSizer = new wxBoxSizer(wxVERTICAL); + panelSizer->Add(panel, 1, wxEXPAND|wxALL, 0); + + scrl->SetSizer(panelSizer); + + + wxBoxSizer* sizerAll = new wxBoxSizer(wxVERTICAL); + sizerAll->Add(scrl, 1, wxEXPAND|wxALL, 0); + SetSizer(sizerAll); + SetAutoLayout(true); + sizerAll->Fit(this); + + + Centre(); + + // Content + //InitVariableCombobox(combo_var); + + // init weights + vector weights_ids; + WeightsManInterface* w_man_int = project->GetWManInt(); + w_man_int->GetIds(weights_ids); + + size_t sel_pos=0; + for (size_t i=0; iAppend(w_man_int->GetShortDispName(weights_ids[i])); + if (w_man_int->GetDefault() == weights_ids[i]) + sel_pos = i; + } + if (weights_ids.size() > 0) combo_weights->SetSelection(sel_pos); + + // Events + okButton->Bind(wxEVT_BUTTON, &RedcapDlg::OnOK, this); + saveButton->Bind(wxEVT_BUTTON, &RedcapDlg::OnSaveTree, this); + closeButton->Bind(wxEVT_BUTTON, &RedcapDlg::OnClickClose, this); + chk_seed->Bind(wxEVT_CHECKBOX, &RedcapDlg::OnSeedCheck, this); + seedButton->Bind(wxEVT_BUTTON, &RedcapDlg::OnChangeSeed, this); +} + +void RedcapDlg::OnSeedCheck(wxCommandEvent& event) +{ + wxLogMessage("On RedcapDlg::OnSeedCheck"); + bool use_user_seed = chk_seed->GetValue(); + + if (use_user_seed) { + seedButton->Enable(); + if (GdaConst::use_gda_user_seed == false && GdaConst::gda_user_seed == 0) { + OnChangeSeed(event); + return; + } + GdaConst::use_gda_user_seed = true; + + OGRDataAdapter& ogr_adapt = OGRDataAdapter::GetInstance(); + ogr_adapt.AddEntry("use_gda_user_seed", "1"); + } else { + seedButton->Disable(); + } +} + +void RedcapDlg::OnChangeSeed(wxCommandEvent& event) +{ + wxLogMessage("On RedcapDlg::OnChangeSeed"); + // prompt user to enter user seed (used globally) + wxString m; + m << _("Enter a seed value for random number generator:"); + + long long unsigned int val; + wxString dlg_val; + wxString cur_val; + cur_val << GdaConst::gda_user_seed; + + wxTextEntryDialog dlg(NULL, m, _("Enter a seed value"), cur_val); + if (dlg.ShowModal() != wxID_OK) return; + dlg_val = dlg.GetValue(); + dlg_val.Trim(true); + dlg_val.Trim(false); + if (dlg_val.IsEmpty()) return; + if (dlg_val.ToULongLong(&val)) { + uint64_t new_seed_val = val; + GdaConst::gda_user_seed = new_seed_val; + GdaConst::use_gda_user_seed = true; + + OGRDataAdapter& ogr_adapt = OGRDataAdapter::GetInstance(); + wxString str_gda_user_seed; + str_gda_user_seed << GdaConst::gda_user_seed; + ogr_adapt.AddEntry("gda_user_seed", str_gda_user_seed.ToStdString()); + ogr_adapt.AddEntry("use_gda_user_seed", "1"); + } else { + wxString m = _("\"%s\" is not a valid seed. Seed unchanged."); + m = wxString::Format(m, dlg_val); + wxMessageDialog dlg(NULL, m, _("Error"), wxOK | wxICON_ERROR); + dlg.ShowModal(); + GdaConst::use_gda_user_seed = false; + OGRDataAdapter& ogr_adapt = OGRDataAdapter::GetInstance(); + ogr_adapt.AddEntry("use_gda_user_seed", "0"); + } +} + +void RedcapDlg::InitVariableCombobox(wxListBox* var_box) +{ + wxLogMessage("On RedcapDlg::InitVariableCombobox"); + wxArrayString items; + + int cnt_floor = 0; + std::vector col_id_map; + table_int->FillNumericColIdMap(col_id_map); + for (int i=0, iend=col_id_map.size(); iGetColName(id); + if (table_int->IsColTimeVariant(id)) { + for (int t=0; tGetColTimeSteps(id); t++) { + wxString nm = name; + nm << " (" << table_int->GetTimeString(t) << ")"; + name_to_nm[nm] = name; + name_to_tm_id[nm] = t; + items.Add(nm); + combo_floor->Insert(nm, cnt_floor++); + } + } else { + name_to_nm[name] = name; + name_to_tm_id[name] = 0; + items.Add(name); + combo_floor->Insert(name, cnt_floor++); + } + } + if (!items.IsEmpty()) + var_box->InsertItems(items,0); + + combo_floor->SetSelection(-1); +} + +void RedcapDlg::OnClickClose(wxCommandEvent& event ) +{ + wxLogMessage("OnClickClose RedcapDlg."); + + event.Skip(); + EndDialog(wxID_CANCEL); + Destroy(); +} + +void RedcapDlg::OnClose(wxCloseEvent& ev) +{ + wxLogMessage("Close RedcapDlg"); + // Note: it seems that if we don't explictly capture the close event + // and call Destory, then the destructor is not called. + Destroy(); +} + +wxString RedcapDlg::_printConfiguration() +{ + wxString txt; + txt << _("Weights:") << "\t" << combo_weights->GetString(combo_weights->GetSelection()) << "\n"; + + txt << _("Method:\t") << combo_method->GetString(combo_method->GetSelection()) << "\n"; + + if (chk_floor && chk_floor->IsChecked()) { + int idx = combo_floor->GetSelection(); + wxString nm = name_to_nm[combo_floor->GetString(idx)]; + txt << _("Minimum bound:\t") << txt_floor->GetValue() << "(" << nm << ")" << "\n"; + } + + txt << _("Minimum region size:\t") << m_textbox->GetValue() << "\n"; + + txt << _("Transformation:") << "\t" << combo_tranform->GetString(combo_tranform->GetSelection()) << "\n"; + + txt << _("Distance function:\t") << m_distance->GetString(m_distance->GetSelection()) << "\n"; + return txt; +} + +void RedcapDlg::OnSaveTree(wxCommandEvent& event ) +{ + if (weights && redcap) { + wxString filter = "GWT|*.gwt"; + wxFileDialog dialog(NULL, _("Save Spanning Tree to a Weights File"), wxEmptyString, + wxEmptyString, filter, + wxFD_SAVE | wxFD_OVERWRITE_PROMPT); + if (dialog.ShowModal() != wxID_OK) + return; + wxFileName fname = wxFileName(dialog.GetPath()); + wxString new_main_dir = fname.GetPathWithSep(); + wxString new_main_name = fname.GetName(); + wxString new_txt = new_main_dir + new_main_name+".gwt"; + wxTextFile file(new_txt); + file.Create(new_txt); + file.Open(new_txt); + file.Clear(); + + wxString header; + header << "0 " << project->GetNumRecords() << " " << project->GetProjectTitle(); + file.AddLine(header); + + for (int i=0; iordered_edges.size(); i++) { + wxString line; + line << redcap->ordered_edges[i]->orig->id+1<< " " << redcap->ordered_edges[i]->dest->id +1<< " " << redcap->ordered_edges[i]->length ; + file.AddLine(line); + } + file.Write(); + file.Close(); + + // Load the weights file into Weights Manager + WeightsManInterface* w_man_int = project->GetWManInt(); + WeightUtils::LoadGwtInMan(w_man_int, new_txt, table_int); + } +} + +void RedcapDlg::OnOK(wxCommandEvent& event ) +{ + wxLogMessage("Click RedcapDlg::OnOK"); + + if (GdaConst::use_gda_user_seed) { + setrandomstate(GdaConst::gda_user_seed); + resetrandom(); + } + + // Get input data + int transform = combo_tranform->GetSelection(); + bool success = GetInputData(transform, 1); + if (!success) { + return; + } + + wxString str_max_region = m_max_region->GetValue(); + if (str_max_region.IsEmpty()) { + wxString err_msg = _("Please enter maximum number of regions."); + wxMessageDialog dlg(NULL, err_msg, _("Error"), wxOK | wxICON_ERROR); + dlg.ShowModal(); + return; + } + if (chk_floor->IsChecked()) { + wxString str_floor = txt_floor->GetValue(); + if (str_floor.IsEmpty() || combo_floor->GetSelection() < 0) { + wxString err_msg = _("Please enter minimum bound value"); + wxMessageDialog dlg(NULL, err_msg, _("Error"), wxOK | wxICON_ERROR); + dlg.ShowModal(); + return; + } + } + + wxString field_name = m_textbox->GetValue(); + if (field_name.IsEmpty()) { + wxString err_msg = _("Please enter a field name for saving clustering results."); + wxMessageDialog dlg(NULL, err_msg, _("Error"), wxOK | wxICON_ERROR); + dlg.ShowModal(); + return; + } + + // Get Weights Selection + vector weights_ids; + WeightsManInterface* w_man_int = project->GetWManInt(); + w_man_int->GetIds(weights_ids); + + int sel = combo_weights->GetSelection(); + if (sel < 0) sel = 0; + if (sel >= weights_ids.size()) sel = weights_ids.size()-1; + + boost::uuids::uuid w_id = weights_ids[sel]; + GalWeight* gw = w_man_int->GetGal(w_id); + + if (gw == NULL) { + wxMessageDialog dlg (this, _("Invalid Weights Information:\n\n The selected weights file is not valid.\n Please choose another weights file, or use Tools > Weights > Weights Manager\n to define a valid weights file."), _("Warning"), wxOK | wxICON_WARNING); + dlg.ShowModal(); + return; + } + weights = w_man_int->GetGal(w_id); + // Check connectivity + if (!CheckConnectivity(gw)) { + wxString msg = _("The connectivity of selected spatial weights is incomplete, please adjust the spatial weights."); + wxMessageDialog dlg(this, msg, _("Warning"), wxOK | wxICON_WARNING ); + dlg.ShowModal(); + return; + } + + // Get Bounds + double min_bound = GetMinBound(); + double* bound_vals = GetBoundVals(); + + // Get Distance Selection + char dist = 'e'; // euclidean + int dist_sel = m_distance->GetSelection(); + char dist_choices[] = {'e','b'}; + dist = dist_choices[dist_sel]; + + // Get number of regions + int n_regions = 0; + long value_n_region; + if(str_max_region.ToLong(&value_n_region)) { + n_regions = value_n_region; + } + + // Get user specified seed + int rnd_seed = -1; + if (chk_seed->GetValue()) rnd_seed = GdaConst::gda_user_seed; + + int transpose = 0; // row wise + double** ragged_distances = distancematrix(rows, columns, input_data, mask, weight, dist, transpose); + double** distances = DataUtils::fullRaggedMatrix(ragged_distances, rows, rows); + for (int i = 1; i < rows; i++) free(ragged_distances[i]); + free(ragged_distances); + + // run RedCap + std::vector undefs(rows, false); + + if (redcap != NULL) { + delete redcap; + redcap = NULL; + } + + int method_idx = combo_method->GetSelection(); + if (method_idx == 0) { + redcap = new FirstOrderSLKRedCap(rows, columns, distances, input_data, undefs, gw->gal, bound_vals, min_bound); + } else if (method_idx == 1) { + redcap = new FullOrderCLKRedCap(rows, columns, distances, input_data, undefs, gw->gal, bound_vals, min_bound); + } else if (method_idx == 2) { + redcap = new FullOrderALKRedCap(rows, columns, distances, input_data, undefs, gw->gal, bound_vals, min_bound); + } else if (method_idx == 3) { + redcap = new FullOrderSLKRedCap(rows, columns, distances, input_data, undefs, gw->gal, bound_vals, min_bound); + } + + + if (redcap==NULL) { + delete[] bound_vals; + bound_vals = NULL; + return; + } + + redcap->Partitioning(n_regions); + + vector > cluster_ids = redcap->GetRegions(); + + int ncluster = cluster_ids.size(); + + if (ncluster < n_regions) { + // show message dialog to user + wxString warn_str = _("The number of identified clusters is less than "); + warn_str << n_regions; + wxMessageDialog dlg(NULL, warn_str, _("Warning"), wxOK | wxICON_WARNING); + dlg.ShowModal(); + } + vector clusters(rows, 0); + vector clusters_undef(rows, false); + + // sort result + std::sort(cluster_ids.begin(), cluster_ids.end(), GenUtils::less_vectors); + + for (int i=0; i < ncluster; i++) { + int c = i + 1; + for (int j=0; jFindColId(field_name); + if ( col == wxNOT_FOUND) { + int col_insert_pos = table_int->GetNumberCols(); + int time_steps = 1; + int m_length_val = GdaConst::default_dbf_long_len; + int m_decimals_val = 0; + + col = table_int->InsertCol(GdaConst::long64_type, field_name, col_insert_pos, time_steps, m_length_val, m_decimals_val); + } else { + // detect if column is integer field, if not raise a warning + if (table_int->GetColType(col) != GdaConst::long64_type ) { + wxString msg = _("This field name already exists (non-integer type). Please input a unique name."); + wxMessageDialog dlg(this, msg, _("Warning"), wxOK | wxICON_WARNING ); + dlg.ShowModal(); + return; + } + } + + if (col > 0) { + table_int->SetColData(col, time, clusters); + table_int->SetColUndefined(col, time, clusters_undef); + } + + // free memory + for (int i = 1; i < rows; i++) free(distances[i]); + free(distances); + + delete[] bound_vals; + bound_vals = NULL; + + // show a cluster map + if (project->IsTableOnlyProject()) { + return; + } + std::vector new_var_info; + std::vector new_col_ids; + new_col_ids.resize(1); + new_var_info.resize(1); + new_col_ids[0] = col; + new_var_info[0].time = 0; + // Set Primary GdaVarTools::VarInfo attributes + new_var_info[0].name = field_name; + new_var_info[0].is_time_variant = table_int->IsColTimeVariant(col); + table_int->GetMinMaxVals(new_col_ids[0], new_var_info[0].min, new_var_info[0].max); + new_var_info[0].sync_with_global_time = new_var_info[0].is_time_variant; + new_var_info[0].fixed_scale = true; + + + MapFrame* nf = new MapFrame(parent, project, + new_var_info, new_col_ids, + CatClassification::unique_values, + MapCanvas::no_smoothing, 4, + boost::uuids::nil_uuid(), + wxDefaultPosition, + GdaConst::map_default_size); + wxString ttl; + ttl << "REDCAP " << _("Cluster Map ") << "("; + ttl << n_regions; + ttl << " clusters)"; + nf->SetTitle(ttl); + + saveButton->Enable(); +} diff --git a/DialogTools/RedcapDlg.h b/DialogTools/RedcapDlg.h new file mode 100644 index 000000000..e8241be55 --- /dev/null +++ b/DialogTools/RedcapDlg.h @@ -0,0 +1,83 @@ +/** + * GeoDa TM, Copyright (C) 2011-2015 by Luc Anselin - all rights reserved + * + * This file is part of GeoDa. + * + * GeoDa is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * GeoDa is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#ifndef __GEODA_CENTER_REDCAP_DLG_H___ +#define __GEODA_CENTER_REDCAP_DLG_H___ + +#include +#include +#include +#include + + +#include "../FramesManager.h" +#include "../VarTools.h" +#include "AbstractClusterDlg.h" +#include "../Algorithms/redcap.h" + +using namespace std; + +class Project; +class TableInterface; + +class RedcapDlg : public AbstractClusterDlg +{ +public: + RedcapDlg(wxFrame *parent, Project* project); + virtual ~RedcapDlg(); + + void CreateControls(); + bool Init(); + + void OnOK( wxCommandEvent& event ); + void OnSaveTree( wxCommandEvent& event ); + void OnClickClose( wxCommandEvent& event ); + void OnClose(wxCloseEvent& ev); + + void OnSeedCheck(wxCommandEvent& event); + void OnChangeSeed(wxCommandEvent& event); + + void InitVariableCombobox(wxListBox* var_box); + + virtual wxString _printConfiguration(); + +protected: + wxChoice* combo_method; + wxChoice* combo_weights; + + wxTextCtrl* m_max_region; + + wxCheckBox* chk_seed; + + wxTextCtrl* m_textbox; + + wxChoice* m_method; + + wxChoice* m_distance; + + wxButton* seedButton; + wxButton* saveButton; + + SpanningTreeClustering::AbstractClusterFactory* redcap; + GeoDaWeight* weights; + + DECLARE_EVENT_TABLE() +}; + +#endif diff --git a/DialogTools/RegressionDlg.cpp b/DialogTools/RegressionDlg.cpp index f58a3f73a..d90bdab72 100644 --- a/DialogTools/RegressionDlg.cpp +++ b/DialogTools/RegressionDlg.cpp @@ -37,7 +37,6 @@ #include "SaveToTableDlg.h" #include "../DataViewer/TableInterface.h" #include "../DataViewer/TableState.h" -#include "../DbfFile.h" #include "../ShapeOperations/WeightsManager.h" #include "../ShapeOperations/WeightsManState.h" #include "../ShapeOperations/GeodaWeight.h" @@ -135,6 +134,13 @@ regReportDlg(0) { wxLogMessage("Open RegressionDlg."); + if (project_s->GetTableInt()->GetNumberCols() == 0) { + wxString err_msg = _("No numeric variables found in table."); + wxMessageDialog dlg(NULL, err_msg, _("Warning"), wxOK | wxICON_ERROR); + dlg.ShowModal(); + EndDialog(wxID_CANCEL); + } + Create(parent, id, caption, pos, size, style); RegressModel = 1; @@ -236,15 +242,13 @@ void RegressionDlg::CreateControls() void RegressionDlg::OnSetupAutoModel(wxCommandEvent& event ) { - wxString m; - m << "Please specify the p-value to be used in tests; \n"; - m << "default: p-value = 0.01"; + wxString m = _("Please specify the p-value to be used in tests; \ndefault: p-value = 0.01"); double val; wxString dlg_val; wxString cur_val; - wxTextEntryDialog dlg(NULL, m, "Enter a seed value", cur_val); + wxTextEntryDialog dlg(NULL, m, _("Enter a seed value"), cur_val); if (dlg.ShowModal() != wxID_OK) return; @@ -257,10 +261,9 @@ void RegressionDlg::OnSetupAutoModel(wxCommandEvent& event ) if (dlg_val.ToDouble(&val)) { autoPVal = val; } else { - wxString m; - m << "\"" << dlg_val << - "\" is not a valid p-value. Default p-value (0.01) is used"; - wxMessageDialog dlg(NULL, m, "Error", wxOK | wxICON_ERROR); + wxString m = _("\"%s\" is not a valid p-value. Default p-value (0.01) is used"); + m = wxString::Format(m, dlg_val); + wxMessageDialog dlg(NULL, m, _("Error"), wxOK | wxICON_ERROR); dlg.ShowModal(); } @@ -271,7 +274,7 @@ void RegressionDlg::OnRunClick( wxCommandEvent& event ) wxLogMessage("Click RegressionDlg::OnRunClick"); m_gauge->Show(); - UpdateMessageBox("calculating..."); + UpdateMessageBox(_("calculating...")); wxString m_Yname = m_dependent->GetValue(); @@ -287,9 +290,8 @@ void RegressionDlg::OnRunClick( wxCommandEvent& event ) m_Yname.Trim(true); double** dt = new double* [sz + 1]; - for (int i = 0; i < sz + 1; i++) { + for (int i = 0; i < sz + 1; i++) dt[i] = new double[m_obs]; - } // WS1447 // fill in each field from m_independentlist and tack on @@ -308,8 +310,11 @@ void RegressionDlg::OnRunClick( wxCommandEvent& event ) int col = table_int->FindColId(nm); if (col == wxNOT_FOUND) { wxString err_msg = wxString::Format(_("Variable %s is no longer in the Table. Please close and reopen the Regression Dialog to synchronize with Table data."), nm); - wxMessageDialog dlg(NULL, err_msg, "Error", wxOK | wxICON_ERROR); + wxMessageDialog dlg(NULL, err_msg, _("Error"), wxOK | wxICON_ERROR); dlg.ShowModal(); + // free memory of dt[][] + for (int i = 0; i < sz + 1; i++) delete[] dt[i]; + delete[] dt; return; } int tm = name_to_tm_id[m_independentlist->GetString(i)]; @@ -326,15 +331,17 @@ void RegressionDlg::OnRunClick( wxCommandEvent& event ) int y_col_id = table_int->FindColId(name_to_nm[m_Yname]); if (y_col_id == wxNOT_FOUND) { wxString err_msg = wxString::Format("Variable %s is no longer in the Table. Please close and reopen the Regression Dialog to synchronize with Table data.", name_to_nm[m_Yname]); - wxMessageDialog dlg(NULL, err_msg, "Error", wxOK | wxICON_ERROR); + wxMessageDialog dlg(NULL, err_msg, _("Error"), wxOK | wxICON_ERROR); dlg.ShowModal(); + // free memory of dt[][] + for (int i = 0; i < sz + 1; i++) delete[] dt[i]; + delete[] dt; return; } table_int->GetColData(y_col_id, name_to_tm_id[m_Yname], vec); - for (int j=0; j vec_undef(m_obs); table_int->GetColUndefined(y_col_id, name_to_tm_id[m_Yname], vec_undef); @@ -363,6 +370,16 @@ void RegressionDlg::OnRunClick( wxCommandEvent& event ) } } + if (valid_obs == 0) { + wxString err_msg = _("Please check the selected variables are all valid."); + wxMessageDialog dlg(NULL, err_msg, _("Error"), wxOK | wxICON_ERROR); + dlg.ShowModal(); + // free memory of dt[][] + for (int i = 0; i < sz + 1; i++) delete[] dt[i]; + delete[] dt; + return; + } + if (m_constant_term) { nX = nX + 1; ix = 1; @@ -502,13 +519,19 @@ void RegressionDlg::OnRunClick( wxCommandEvent& event ) bool HetFlag = false; DiagnosticReport m_DR(n, nX, m_constant_term, true, 1); + if ( false == m_DR.GetDiagStatus()) { + UpdateMessageBox(""); + return; + } if (gal_weight && !classicalRegression(gal_weight, valid_obs, y, n, x, nX, &m_DR, m_constant_term, true, m_gauge, do_white_test)) { - wxMessageBox(_("Error: the inverse matrix is ill-conditioned")); + wxString s = _("Error: the inverse matrix is ill-conditioned."); + wxMessageDialog dlg(NULL, s, _("Error"), wxOK | wxICON_ERROR); + dlg.ShowModal(); m_OpenDump = false; OnCResetClick(event); UpdateMessageBox(""); @@ -570,6 +593,11 @@ void RegressionDlg::OnRunClick( wxCommandEvent& event ) if (RegressModel == 1) { wxLogMessage("OLS model"); DiagnosticReport m_DR(n, nX, m_constant_term, true, RegressModel); + if ( false == m_DR.GetDiagStatus()) { + UpdateMessageBox(""); + return; + } + SetXVariableNames(&m_DR); m_DR.SetMeanY(ComputeMean(y, n)); m_DR.SetSDevY(ComputeSdev(y, n)); @@ -577,8 +605,12 @@ void RegressionDlg::OnRunClick( wxCommandEvent& event ) if (gal_weight && !classicalRegression(gal_weight, valid_obs, y, n, x, nX, &m_DR, m_constant_term, true, m_gauge, - do_white_test)) { - wxMessageBox(_("Error: the inverse matrix is ill-conditioned")); + do_white_test)) + { + wxString s = _("Error: the inverse matrix is ill-conditioned."); + wxMessageDialog dlg(NULL, s, _("Error"), wxOK | wxICON_ERROR); + dlg.ShowModal(); + m_OpenDump = false; OnCResetClick(event); UpdateMessageBox(""); @@ -608,18 +640,25 @@ void RegressionDlg::OnRunClick( wxCommandEvent& event ) p_dlg->Show(); p_dlg->StatusUpdate(0, _("Checking Symmetry...")); sym = w_man_int->CheckSym(id, p_dlg); - p_dlg->StatusUpdate(1, "Finished"); + p_dlg->StatusUpdate(1, _("Finished")); p_dlg->Destroy(); } if (sym != WeightsMetaInfo::SYM_symmetric) { - wxMessageBox(_("Spatial lag and error regressions require symmetric weights (not KNN). You can still use KNN weights to obtain spatial diagnostics for classic regressions.")); + wxString s = _("Spatial lag and error regressions require symmetric weights (not KNN). You can still use KNN weights to obtain spatial diagnostics for classic regressions."); + wxMessageDialog dlg(NULL, s, _("Error"), wxOK | wxICON_ERROR); + dlg.ShowModal(); + UpdateMessageBox(""); return; } DiagnosticReport m_DR(n, nX + 1, m_constant_term, true, RegressModel); - + if ( false == m_DR.GetDiagStatus()) { + UpdateMessageBox(""); + return; + } + SetXVariableNames(&m_DR); m_DR.SetMeanY(ComputeMean(y, n)); m_DR.SetSDevY(ComputeSdev(y, n)); @@ -657,11 +696,13 @@ void RegressionDlg::OnRunClick( wxCommandEvent& event ) p_dlg->Show(); p_dlg->StatusUpdate(0, _("Checking Symmetry...")); sym = w_man_int->CheckSym(id, p_dlg); - p_dlg->StatusUpdate(1, "Finished"); + p_dlg->StatusUpdate(1, _("Finished")); p_dlg->Destroy(); } if (sym != WeightsMetaInfo::SYM_symmetric) { - wxMessageBox(_("Spatial lag and error regressions require symmetric weights (not KNN). You can still use KNN weights to obtain spatial diagnostics for classic regressions.")); + wxString s = _("Spatial lag and error regressions require symmetric weights (not KNN). You can still use KNN weights to obtain spatial diagnostics for classic regressions."); + wxMessageDialog dlg(NULL, s, _("Error"), wxOK | wxICON_ERROR); + dlg.ShowModal(); UpdateMessageBox(""); return; } @@ -669,6 +710,11 @@ void RegressionDlg::OnRunClick( wxCommandEvent& event ) // Error Model DiagnosticReport m_DR(n, nX + 1, m_constant_term, true, RegressModel); + if ( false == m_DR.GetDiagStatus()) { + UpdateMessageBox(""); + return; + } + SetXVariableNames(&m_DR); m_DR.SetMeanY(ComputeMean(y, n)); m_DR.SetSDevY(ComputeSdev(y, n)); @@ -676,7 +722,10 @@ void RegressionDlg::OnRunClick( wxCommandEvent& event ) if (gal_weight && !spatialErrorRegression(gal_weight, valid_obs, y, n, x, nX, &m_DR, true, m_gauge)) { - wxMessageBox(_("Error: the inverse matrix is ill-conditioned.")); + wxString s = _("Error: the inverse matrix is ill-conditioned."); + wxMessageDialog dlg(NULL, s, _("Error"), wxOK | wxICON_ERROR); + dlg.ShowModal(); + m_OpenDump = false; OnCResetClick(event); UpdateMessageBox(""); @@ -714,6 +763,10 @@ void RegressionDlg::OnRunClick( wxCommandEvent& event ) } else { DiagnosticReport m_DR(n, nX, m_constant_term, false, RegressModel); + if ( false == m_DR.GetDiagStatus()) { + UpdateMessageBox(""); + return; + } SetXVariableNames(&m_DR); m_DR.SetMeanY(ComputeMean(y, n)); m_DR.SetSDevY(ComputeSdev(y, n)); @@ -721,7 +774,10 @@ void RegressionDlg::OnRunClick( wxCommandEvent& event ) if (!classicalRegression((GalElement*)NULL, m_obs, y, n, x, nX, &m_DR, m_constant_term, false, m_gauge, do_white_test)) { - wxMessageBox(_("Error: the inverse matrix is ill-conditioned.")); + wxString s = _("Error: the inverse matrix is ill-conditioned."); + wxMessageDialog dlg(NULL, s, _("Error"), wxOK | wxICON_ERROR); + dlg.ShowModal(); + m_OpenDump = false; OnCResetClick(event); UpdateMessageBox(""); @@ -754,7 +810,7 @@ void RegressionDlg::OnRunClick( wxCommandEvent& event ) EnablingItems(); //FindWindow(XRCID("ID_RUN"))->Enable(false); - UpdateMessageBox("done"); + UpdateMessageBox(_("done")); } void RegressionDlg::DisplayRegression(wxString dump) @@ -837,7 +893,7 @@ void RegressionDlg::OnSaveToTxtFileClick( wxCommandEvent& event ) if (failed) { wxString msg; msg << _("Unable to overwrite ") << new_txt; - wxMessageDialog dlg (this, msg, "Error", wxOK | wxICON_ERROR); + wxMessageDialog dlg (this, msg, _("Error"), wxOK | wxICON_ERROR); dlg.ShowModal(); } } @@ -1032,7 +1088,7 @@ void RegressionDlg::OnCSaveRegressionClick( wxCommandEvent& event ) } SaveToTableDlg dlg(project, this, data, - "Save Regression Results", + _("Save Regression Results"), wxDefaultPosition, wxSize(400,400)); dlg.ShowModal(); @@ -1090,7 +1146,9 @@ void RegressionDlg::InitVariableList() m_obs = project->GetNumRecords(); if (m_obs <= 0) { - wxMessageBox("Error: no records found in DBF file"); + wxString s = _("Error: no records found in data source."); + wxMessageDialog dlg(NULL, s, _("Error"), wxOK | wxICON_ERROR); + dlg.ShowModal(); return; } @@ -1204,7 +1262,11 @@ void RegressionDlg::OnCWeightCheckClick( wxCommandEvent& event ) b_done1 = b_done2 = b_done3 = false; EnablingItems(); - if (!m_CheckWeight->IsChecked()) m_radio1->SetValue(true); + if (!m_CheckWeight->IsChecked()) { + m_radio1->SetValue(true); + wxCommandEvent(ev); + OnCRadio1Selected(ev); + } } void RegressionDlg::UpdateMessageBox(wxString msg) @@ -1234,8 +1296,10 @@ void RegressionDlg::printAndShowClassicalResults(const wxString& datasetname, logReport = wxEmptyString; // reset log report int cnt = 0; - slog << "SUMMARY OF OUTPUT: ORDINARY LEAST SQUARES ESTIMATION\n"; cnt++; - slog << "Data set : " << datasetname << "\n"; cnt++; + slog << "SUMMARY OF OUTPUT: ORDINARY LEAST SQUARES ESTIMATION\n"; + cnt++; + slog << "Data set : " << datasetname << "\n"; + cnt++; slog << "Dependent Variable :"; if (m_dependent->GetValue().length() > 12 ) @@ -1243,56 +1307,79 @@ void RegressionDlg::printAndShowClassicalResults(const wxString& datasetname, else slog << GenUtils::Pad(m_dependent->GetValue(), 12) << " "; - slog << "Number of Observations:" << wxString::Format("%5d\n",Obs); cnt++; + slog << "Number of Observations:" << wxString::Format("%5d\n",Obs); + cnt++; f = "Mean dependent var :%12.6g Number of Variables :%5d\n"; - slog << wxString::Format(f, r->GetMeanY(), nX); cnt++; + slog << wxString::Format(f, r->GetMeanY(), nX); + cnt++; f = "S.D. dependent var :%12.6g Degrees of Freedom :%5d \n"; - slog << wxString::Format(f, r->GetSDevY(), Obs-nX); cnt++; - slog << "\n"; cnt++; + slog << wxString::Format(f, r->GetSDevY(), Obs-nX); + cnt++; + slog << "\n"; + cnt++; - f = "R-squared :%12.6f F-statistic :%12.6g\n"; cnt++; + f = "R-squared :%12.6f F-statistic :%12.6g\n"; + cnt++; slog << wxString::Format(f, r->GetR2(), r->GetFtest()); - f = "Adjusted R-squared :%12.6f Prob(F-statistic) :%12.6g\n"; cnt++; + f = "Adjusted R-squared :%12.6f Prob(F-statistic) :%12.6g\n"; + cnt++; slog << wxString::Format(f, r->GetR2_adjust(), r->GetFtestProb()); - f = "Sum squared residual:%12.6g Log likelihood :%12.6g\n"; cnt++; + f = "Sum squared residual:%12.6g Log likelihood :%12.6g\n"; + cnt++; slog << wxString::Format(f, r->GetRSS() ,r->GetLIK()); - f = "Sigma-square :%12.6g Akaike info criterion :%12.6g\n"; cnt++; + f = "Sigma-square :%12.6g Akaike info criterion :%12.6g\n"; + cnt++; slog << wxString::Format(f, r->GetSIQ_SQ(), r->GetAIC()); - f = "S.E. of regression :%12.6g Schwarz criterion :%12.6g\n"; cnt++; + f = "S.E. of regression :%12.6g Schwarz criterion :%12.6g\n"; + cnt++; slog << wxString::Format(f, sqrt(r->GetSIQ_SQ()), r->GetOLS_SC()); - f = "Sigma-square ML :%12.6g\n"; cnt++; + f = "Sigma-square ML :%12.6g\n"; + cnt++; slog << wxString::Format(f, r->GetSIQ_SQLM()); - f = "S.E of regression ML:%12.6g\n\n"; cnt++; cnt++; + f = "S.E of regression ML:%12.6g\n\n"; + cnt++; + cnt++; slog << wxString::Format(f, sqrt(r->GetSIQ_SQLM())); slog << "--------------------------------------"; - slog << "---------------------------------------\n"; cnt++; + slog << "---------------------------------------\n"; + cnt++; slog << " Variable Coefficient "; - slog << "Std.Error t-Statistic Probability\n"; cnt++; + slog << "Std.Error t-Statistic Probability\n"; + cnt++; slog << "--------------------------------------"; - slog << "---------------------------------------\n"; cnt++; + slog << "---------------------------------------\n"; + cnt++; for (int i=0; iGetXVarName(i), 18); slog << wxString::Format(" %12.6g %12.6g %12.6g %9.5f\n", r->GetCoefficient(i), r->GetStdError(i), - r->GetZValue(i), r->GetProbability(i)); cnt++; + r->GetZValue(i), r->GetProbability(i)); + cnt++; } slog << "----------------------------------------"; - slog << "-------------------------------------\n\n"; cnt++; cnt++; + slog << "-------------------------------------\n\n"; + cnt++; + cnt++; - slog << "REGRESSION DIAGNOSTICS \n"; cnt++; + slog << "REGRESSION DIAGNOSTICS \n"; + cnt++; double *rr = r->GetBPtest(); if (rr[1] > 1) { slog << wxString::Format("MULTICOLLINEARITY CONDITION NUMBER %7f\n", - r->GetConditionNumber()); cnt++; + r->GetConditionNumber()); + cnt++; } else { slog << wxString::Format("MULTICOLLINEARITY CONDITION NUMBER %7f\n", - r->GetConditionNumber()); cnt++; + r->GetConditionNumber()); + cnt++; slog << " "; - slog << " (Extreme Multicollinearity)\n"; cnt++; + slog << " (Extreme Multicollinearity)\n"; + cnt++; } - slog << "TEST ON NORMALITY OF ERRORS\n"; cnt++; + slog << "TEST ON NORMALITY OF ERRORS\n"; + cnt++; slog << "TEST DF VALUE PROB\n"; cnt++; rr = r->GetJBtest(); f = "Jarque-Bera %2.0f %11.4f %9.5f\n"; cnt++; diff --git a/DialogTools/RegressionReportDlg.cpp b/DialogTools/RegressionReportDlg.cpp index 53353ebcb..d5817f482 100644 --- a/DialogTools/RegressionReportDlg.cpp +++ b/DialogTools/RegressionReportDlg.cpp @@ -80,7 +80,7 @@ void RegressionReportDlg::CreateControls() //m_textbox = XRCCTRL(*this, "ID_TEXTCTRL1", wxTextCtrl); wxPanel *panel = new wxPanel(this, -1); wxBoxSizer *vbox = new wxBoxSizer(wxVERTICAL); - m_textbox = new wxTextCtrl(panel, XRCID("ID_TEXTCTRL"), "", wxDefaultPosition, wxSize(620,560), wxTE_MULTILINE | wxTE_READONLY); + m_textbox = new wxTextCtrl(panel, XRCID("ID_TEXTCTRL"), "", wxDefaultPosition, wxSize(620,560), wxTE_MULTILINE | wxTE_READONLY | wxTE_RICH | wxTE_RICH2); if (GeneralWxUtils::isWindows()) { wxFont font(8,wxFONTFAMILY_TELETYPE,wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL); @@ -167,7 +167,7 @@ void RegressionReportDlg::OnSaveToFile(wxCommandEvent& event) if (failed) { wxString msg; msg << "Unable to overwrite " << new_txt; - wxMessageDialog dlg (this, msg, "Error", wxOK | wxICON_ERROR); + wxMessageDialog dlg (this, msg, _("Error"), wxOK | wxICON_ERROR); dlg.ShowModal(); } } diff --git a/DialogTools/ReportBugDlg.cpp b/DialogTools/ReportBugDlg.cpp index 7b6ce0f12..d6c1fcc17 100644 --- a/DialogTools/ReportBugDlg.cpp +++ b/DialogTools/ReportBugDlg.cpp @@ -104,712 +104,11 @@ void WelcomeSelectionStyleDlg::OnStyle2(wxMouseEvent& ev) EndDialog(wxID_OK); } + //////////////////////////////////////////////////////////////////////////////// // -// PreferenceDlg // //////////////////////////////////////////////////////////////////////////////// -PreferenceDlg::PreferenceDlg(wxWindow* parent, - wxWindowID id, - const wxString& title, - const wxPoint& pos, - const wxSize& size) - : wxDialog(parent, id, title, pos, size, wxDEFAULT_DIALOG_STYLE) -{ - highlight_state = NULL; - SetBackgroundColour(*wxWHITE); - Init(); - SetMinSize(wxSize(550, -1)); -} - -PreferenceDlg::PreferenceDlg(wxWindow* parent, - HLStateInt* _highlight_state, - wxWindowID id, - const wxString& title, - const wxPoint& pos, - const wxSize& size) - : wxDialog(parent, id, title, pos, size, wxDEFAULT_DIALOG_STYLE) -{ - highlight_state = _highlight_state; - SetBackgroundColour(*wxWHITE); - Init(); - SetMinSize(wxSize(550, -1)); -} - -void PreferenceDlg::Init() -{ - ReadFromCache(); - - wxNotebook* notebook = new wxNotebook(this, wxID_ANY, wxDefaultPosition, wxDefaultSize); - - // visualization tab - wxNotebookPage* vis_page = new wxNotebookPage(notebook, -1, wxDefaultPosition, wxSize(560, 580)); -#ifdef __WIN32__ - vis_page->SetBackgroundColour(*wxWHITE); -#endif - notebook->AddPage(vis_page, "System"); - wxFlexGridSizer* grid_sizer1 = new wxFlexGridSizer(16, 2, 12, 15); - - grid_sizer1->Add(new wxStaticText(vis_page, wxID_ANY, _("Maps:")), 1); - grid_sizer1->AddSpacer(10); - - wxString lbl0 = _("Use classic yellow cross-hatching to highlight selection in maps:"); - wxStaticText* lbl_txt0 = new wxStaticText(vis_page, wxID_ANY, lbl0); - cbox0 = new wxCheckBox(vis_page, XRCID("PREF_USE_CROSSHATCH"), "", wxDefaultPosition); - grid_sizer1->Add(lbl_txt0, 1, wxEXPAND); - grid_sizer1->Add(cbox0, 0, wxALIGN_RIGHT); - cbox0->Bind(wxEVT_CHECKBOX, &PreferenceDlg::OnCrossHatch, this); - - wxSize sl_sz(200, -1); - wxSize txt_sz(35, -1); - - wxString lbl1 = _("Set transparency of highlighted objects in selection:"); - wxStaticText* lbl_txt1 = new wxStaticText(vis_page, wxID_ANY, lbl1); - wxBoxSizer* box1 = new wxBoxSizer(wxHORIZONTAL); - slider1 = new wxSlider(vis_page, wxID_ANY, - 0, 0, 255, - wxDefaultPosition, sl_sz, - wxSL_HORIZONTAL); - slider_txt1 = new wxTextCtrl(vis_page, XRCID("PREF_SLIDER1_TXT"), "", - wxDefaultPosition, txt_sz, wxTE_READONLY); - box1->Add(slider1); - box1->Add(slider_txt1); - grid_sizer1->Add(lbl_txt1, 1, wxEXPAND); - grid_sizer1->Add(box1, 0, wxALIGN_RIGHT); - slider1->Bind(wxEVT_SLIDER, &PreferenceDlg::OnSlider1, this); - - wxString lbl2 = _("Set transparency of unhighlighted objects in selection:"); - wxStaticText* lbl_txt2 = new wxStaticText(vis_page, wxID_ANY, lbl2); - wxBoxSizer* box2 = new wxBoxSizer(wxHORIZONTAL); - slider2 = new wxSlider(vis_page, wxID_ANY, - 0, 0, 255, - wxDefaultPosition, sl_sz, - wxSL_HORIZONTAL); - slider_txt2 = new wxTextCtrl(vis_page, XRCID("PREF_SLIDER2_TXT"), "", - wxDefaultPosition, txt_sz, wxTE_READONLY); - box2->Add(slider2); - box2->Add(slider_txt2); - grid_sizer1->Add(lbl_txt2, 1, wxEXPAND); - grid_sizer1->Add(box2, 0, wxALIGN_RIGHT); - slider2->Bind(wxEVT_SLIDER, &PreferenceDlg::OnSlider2, this); - - - wxString lbl3 = _("Add basemap automatically:"); - wxStaticText* lbl_txt3 = new wxStaticText(vis_page, wxID_ANY, lbl3); - //wxStaticText* lbl_txt33 = new wxStaticText(vis_page, wxID_ANY, lbl3); - cmb33 = new wxComboBox(vis_page, wxID_ANY, _(""), wxDefaultPosition, wxDefaultSize, 0, NULL, wxCB_READONLY); - cmb33->Append("No basemap"); - cmb33->Append("Carto Light"); - cmb33->Append("Carto Dark"); - cmb33->Append("Carto Light (No Labels)"); - cmb33->Append("Carto Dark (No Labels)"); - cmb33->Append("Nokia Day"); - cmb33->Append("Nokia Night"); - cmb33->Append("Nokia Hybrid"); - cmb33->Append("Nokia Satellite"); - cmb33->SetSelection(0); - cmb33->Bind(wxEVT_COMBOBOX, &PreferenceDlg::OnChoice3, this); - - grid_sizer1->Add(lbl_txt3, 1, wxEXPAND); - grid_sizer1->Add(cmb33, 0, wxALIGN_RIGHT); - - - grid_sizer1->Add(new wxStaticText(vis_page, wxID_ANY, _("Plots:")), 1, - wxTOP | wxBOTTOM, 20); - grid_sizer1->AddSpacer(10); - - - wxString lbl6 = _("Set transparency of highlighted objects in selection:"); - wxStaticText* lbl_txt6 = new wxStaticText(vis_page, wxID_ANY, lbl6); - wxBoxSizer* box6 = new wxBoxSizer(wxHORIZONTAL); - slider6 = new wxSlider(vis_page, XRCID("PREF_SLIDER6"), - 255, 0, 255, - wxDefaultPosition, sl_sz, - wxSL_HORIZONTAL); - wxTextCtrl* slider_txt6 = new wxTextCtrl(vis_page, XRCID("PREF_SLIDER6_TXT"), "0.0", wxDefaultPosition, txt_sz, wxTE_READONLY); - lbl_txt6->Hide(); - slider6->Hide(); - slider_txt6->Hide(); - - box6->Add(slider6); - box6->Add(slider_txt6); - grid_sizer1->Add(lbl_txt6, 1, wxEXPAND); - grid_sizer1->Add(box6, 0, wxALIGN_RIGHT); - slider6->Bind(wxEVT_SLIDER, &PreferenceDlg::OnSlider6, this); - slider6->Enable(false); - - wxString lbl7 = _("Set transparency of unhighlighted objects in selection:"); - wxStaticText* lbl_txt7 = new wxStaticText(vis_page, wxID_ANY, lbl7); - wxBoxSizer* box7 = new wxBoxSizer(wxHORIZONTAL); - slider7 = new wxSlider(vis_page, wxID_ANY, - 0, 0, 255, - wxDefaultPosition, sl_sz, - wxSL_HORIZONTAL); - slider_txt7 = new wxTextCtrl(vis_page, XRCID("PREF_SLIDER7_TXT"), "", wxDefaultPosition, txt_sz, wxTE_READONLY); - box7->Add(slider7); - box7->Add(slider_txt7); - grid_sizer1->Add(lbl_txt7, 1, wxEXPAND); - grid_sizer1->Add(box7, 0, wxALIGN_RIGHT); - slider7->Bind(wxEVT_SLIDER, &PreferenceDlg::OnSlider7, this); - - - grid_sizer1->Add(new wxStaticText(vis_page, wxID_ANY, _("System:")), 1, - wxTOP | wxBOTTOM, 20); - grid_sizer1->AddSpacer(10); - - - wxString lbl8 = _("Show Recent/Sample Data panel in Connect Datasource Dialog:"); - wxStaticText* lbl_txt8 = new wxStaticText(vis_page, wxID_ANY, lbl8); - cbox8 = new wxCheckBox(vis_page, XRCID("PREF_SHOW_RECENT"), "", wxDefaultPosition); - grid_sizer1->Add(lbl_txt8, 1, wxEXPAND); - grid_sizer1->Add(cbox8, 0, wxALIGN_RIGHT); - cbox8->Bind(wxEVT_CHECKBOX, &PreferenceDlg::OnShowRecent, this); - - wxString lbl9 = _("Show CSV Configuration in Merge Data Dialog:"); - wxStaticText* lbl_txt9 = new wxStaticText(vis_page, wxID_ANY, lbl9); - cbox9 = new wxCheckBox(vis_page, XRCID("PREF_SHOW_CSV_IN_MERGE"), "", wxDefaultPosition); - grid_sizer1->Add(lbl_txt9, 1, wxEXPAND); - grid_sizer1->Add(cbox9, 0, wxALIGN_RIGHT); - cbox9->Bind(wxEVT_CHECKBOX, &PreferenceDlg::OnShowCsvInMerge, this); - - wxString lbl10 = _("Enable High DPI/Retina support (Mac only):"); - wxStaticText* lbl_txt10 = new wxStaticText(vis_page, wxID_ANY, lbl10); - cbox10 = new wxCheckBox(vis_page, XRCID("PREF_ENABLE_HDPI"), "", wxDefaultPosition); - grid_sizer1->Add(lbl_txt10, 1, wxEXPAND); - grid_sizer1->Add(cbox10, 0, wxALIGN_RIGHT); - cbox10->Bind(wxEVT_CHECKBOX, &PreferenceDlg::OnEnableHDPISupport, this); - - wxString lbl4 = _("Disable crash detection for bug report:"); - wxStaticText* lbl_txt4 = new wxStaticText(vis_page, wxID_ANY, lbl4); - cbox4 = new wxCheckBox(vis_page, XRCID("PREF_CRASH_DETECT"), "", wxDefaultPosition); - grid_sizer1->Add(lbl_txt4, 1, wxEXPAND); - grid_sizer1->Add(cbox4, 0, wxALIGN_RIGHT); - cbox4->Bind(wxEVT_CHECKBOX, &PreferenceDlg::OnDisableCrashDetect, this); - - wxString lbl5 = _("Disable auto upgrade:"); - wxStaticText* lbl_txt5 = new wxStaticText(vis_page, wxID_ANY, lbl5); - cbox5 = new wxCheckBox(vis_page, XRCID("PREF_AUTO_UPGRADE"), "", wxDefaultPosition); - grid_sizer1->Add(lbl_txt5, 1, wxEXPAND); - grid_sizer1->Add(cbox5, 0, wxALIGN_RIGHT); - cbox5->Bind(wxEVT_CHECKBOX, &PreferenceDlg::OnDisableAutoUpgrade, this); - - grid_sizer1->AddGrowableCol(0, 1); - - wxBoxSizer *nb_box1 = new wxBoxSizer(wxVERTICAL); - nb_box1->Add(grid_sizer1, 1, wxEXPAND | wxALL, 20); - nb_box1->Fit(vis_page); - - vis_page->SetSizer(nb_box1); - - //------------------------------------ - // datasource (gdal) tab - wxNotebookPage* gdal_page = new wxNotebookPage(notebook, -1); -#ifdef __WIN32__ - gdal_page->SetBackgroundColour(*wxWHITE); -#endif - notebook->AddPage(gdal_page, "Data Source"); - wxFlexGridSizer* grid_sizer2 = new wxFlexGridSizer(10, 2, 15, 20); - - wxString lbl21 = _("Hide system table in Postgresql connection:"); - wxStaticText* lbl_txt21 = new wxStaticText(gdal_page, wxID_ANY, lbl21); - cbox21 = new wxCheckBox(gdal_page, wxID_ANY, "", wxDefaultPosition); - grid_sizer2->Add(lbl_txt21, 1, wxEXPAND | wxTOP, 10); - grid_sizer2->Add(cbox21, 0, wxALIGN_RIGHT | wxTOP, 13); - cbox21->Bind(wxEVT_CHECKBOX, &PreferenceDlg::OnHideTablePostGIS, this); - - - wxString lbl22 = _("Hide system table in SQLITE connection:"); - wxStaticText* lbl_txt22 = new wxStaticText(gdal_page, wxID_ANY, lbl22); - cbox22 = new wxCheckBox(gdal_page, wxID_ANY, "", wxDefaultPosition); - grid_sizer2->Add(lbl_txt22, 1, wxEXPAND); - grid_sizer2->Add(cbox22, 0, wxALIGN_RIGHT); - cbox22->Bind(wxEVT_CHECKBOX, &PreferenceDlg::OnHideTableSQLITE, this); - - - wxString lbl23 = _("Http connection timeout (seconds) for e.g. WFS, Geojson etc.:"); - wxStaticText* lbl_txt23 = new wxStaticText(gdal_page, wxID_ANY, lbl23); - txt23 = new wxTextCtrl(gdal_page, XRCID("ID_HTTP_TIMEOUT"), "", wxDefaultPosition, txt_sz, wxTE_PROCESS_ENTER); - grid_sizer2->Add(lbl_txt23, 1, wxEXPAND); - grid_sizer2->Add(txt23, 0, wxALIGN_RIGHT); - txt23->Bind(wxEVT_TEXT, &PreferenceDlg::OnTimeoutInput, this); - - grid_sizer2->AddGrowableCol(0, 1); - - wxBoxSizer *nb_box2 = new wxBoxSizer(wxVERTICAL); - nb_box2->Add(grid_sizer2, 1, wxEXPAND | wxALL, 20); - nb_box2->Fit(gdal_page); - - gdal_page->SetSizer(nb_box2); - - SetupControls(); - - // overall - - wxBoxSizer *vbox = new wxBoxSizer(wxVERTICAL); - wxBoxSizer *hbox = new wxBoxSizer(wxHORIZONTAL); - - wxButton *resetButton = new wxButton(this, -1, _("Reset"), wxDefaultPosition, wxSize(70, 30)); - wxButton *closeButton = new wxButton(this, wxID_OK, _("Close"), wxDefaultPosition, wxSize(70, 30)); - resetButton->Bind(wxEVT_COMMAND_BUTTON_CLICKED, &PreferenceDlg::OnReset, this); - - hbox->Add(resetButton, 1); - hbox->Add(closeButton, 1, wxLEFT, 5); - - vbox->Add(notebook, 1, wxEXPAND | wxALL, 10); - vbox->Add(hbox, 0, wxALIGN_CENTER | wxTOP | wxBOTTOM, 10); - - SetSizer(vbox); - vbox->Fit(this); - - Centre(); - ShowModal(); - - Destroy(); -} - -void PreferenceDlg::OnReset(wxCommandEvent& ev) -{ - GdaConst::use_cross_hatching = false; - GdaConst::transparency_highlighted = 255; - GdaConst::transparency_unhighlighted = 100; - //GdaConst::transparency_map_on_basemap = 200; - GdaConst::use_basemap_by_default = false; - GdaConst::default_basemap_selection = 0; - GdaConst::hide_sys_table_postgres = false; - GdaConst::hide_sys_table_sqlite = false; - GdaConst::disable_crash_detect = false; - GdaConst::disable_auto_upgrade = false; - GdaConst::plot_transparency_highlighted = 255; - GdaConst::plot_transparency_unhighlighted = 50; - GdaConst::show_recent_sample_connect_ds_dialog = true; - GdaConst::show_csv_configure_in_merge = false; - GdaConst::enable_high_dpi_support = true; - GdaConst::gdal_http_timeout = 5; - - - SetupControls(); - - OGRDataAdapter& ogr_adapt = OGRDataAdapter::GetInstance(); - ogr_adapt.AddEntry("use_cross_hatching", "0"); - ogr_adapt.AddEntry("transparency_highlighted", "255"); - ogr_adapt.AddEntry("transparency_unhighlighted", "100"); - ogr_adapt.AddEntry("use_basemap_by_default", "0"); - ogr_adapt.AddEntry("default_basemap_selection", "0"); - ogr_adapt.AddEntry("hide_sys_table_postgres", "0"); - ogr_adapt.AddEntry("hide_sys_table_sqlite", "0"); - ogr_adapt.AddEntry("disable_crash_detect", "0"); - ogr_adapt.AddEntry("disable_auto_upgrade", "0"); - ogr_adapt.AddEntry("plot_transparency_highlighted", "255"); - ogr_adapt.AddEntry("plot_transparency_unhighlighted", "50"); - ogr_adapt.AddEntry("show_recent_sample_connect_ds_dialog", "1"); - ogr_adapt.AddEntry("show_csv_configure_in_merge", "0"); - ogr_adapt.AddEntry("enable_high_dpi_support", "1"); - ogr_adapt.AddEntry("gdal_http_timeout", "5"); -} - -void PreferenceDlg::SetupControls() -{ - cbox0->SetValue(GdaConst::use_cross_hatching); - slider1->SetValue(GdaConst::transparency_highlighted); - wxString t_hl = wxString::Format("%.2f", (255 - GdaConst::transparency_highlighted) / 255.0); - slider_txt1->SetValue(t_hl); - slider2->SetValue(GdaConst::transparency_unhighlighted); - wxString t_uhl = wxString::Format("%.2f", (255 - GdaConst::transparency_unhighlighted) / 255.0); - slider_txt2->SetValue(t_uhl); - if (GdaConst::use_basemap_by_default) { - cmb33->SetSelection(GdaConst::default_basemap_selection); - } - else { - cmb33->SetSelection(0); - } - - slider7->SetValue(GdaConst::plot_transparency_unhighlighted); - wxString t_p_hl = wxString::Format("%.2f", (255 - GdaConst::plot_transparency_unhighlighted) / 255.0); - slider_txt7->SetValue(t_p_hl); - - cbox4->SetValue(GdaConst::disable_crash_detect); - cbox5->SetValue(GdaConst::disable_auto_upgrade); - cbox21->SetValue(GdaConst::hide_sys_table_postgres); - cbox22->SetValue(GdaConst::hide_sys_table_sqlite); - cbox8->SetValue(GdaConst::show_recent_sample_connect_ds_dialog); - cbox9->SetValue(GdaConst::show_csv_configure_in_merge); - cbox10->SetValue(GdaConst::enable_high_dpi_support); - - txt23->SetValue(wxString::Format("%d", GdaConst::gdal_http_timeout)); -} - -void PreferenceDlg::ReadFromCache() -{ - vector transp_h = OGRDataAdapter::GetInstance().GetHistory("transparency_highlighted"); - if (!transp_h.empty()) { - long transp_l = 0; - wxString transp = transp_h[0]; - if (transp.ToLong(&transp_l)) { - GdaConst::transparency_highlighted = transp_l; - } - } - vector transp_uh = OGRDataAdapter::GetInstance().GetHistory("transparency_unhighlighted"); - if (!transp_uh.empty()) { - long transp_l = 0; - wxString transp = transp_uh[0]; - if (transp.ToLong(&transp_l)) { - GdaConst::transparency_unhighlighted = transp_l; - } - } - vector plot_transparency_unhighlighted = OGRDataAdapter::GetInstance().GetHistory("plot_transparency_unhighlighted"); - if (!plot_transparency_unhighlighted.empty()) { - long transp_l = 0; - wxString transp = plot_transparency_unhighlighted[0]; - if (transp.ToLong(&transp_l)) { - GdaConst::plot_transparency_unhighlighted = transp_l; - } - } - vector basemap_sel = OGRDataAdapter::GetInstance().GetHistory("default_basemap_selection"); - if (!basemap_sel.empty()) { - long sel_l = 0; - wxString sel = basemap_sel[0]; - if (sel.ToLong(&sel_l)) { - GdaConst::default_basemap_selection = sel_l; - } - } - vector basemap_default = OGRDataAdapter::GetInstance().GetHistory("use_basemap_by_default"); - if (!basemap_default.empty()) { - long sel_l = 0; - wxString sel = basemap_default[0]; - if (sel.ToLong(&sel_l)) { - if (sel_l == 1) - GdaConst::use_basemap_by_default = true; - else if (sel_l == 0) - GdaConst::use_basemap_by_default = false; - } - } - vector crossht_sel = OGRDataAdapter::GetInstance().GetHistory("use_cross_hatching"); - if (!crossht_sel.empty()) { - long cross_l = 0; - wxString cross = crossht_sel[0]; - if (cross.ToLong(&cross_l)) { - if (cross_l == 1) - GdaConst::use_cross_hatching = true; - else if (cross_l == 0) - GdaConst::use_cross_hatching = false; - } - } - vector postgres_sys_sel = OGRDataAdapter::GetInstance().GetHistory("hide_sys_table_postgres"); - if (!postgres_sys_sel.empty()) { - long sel_l = 0; - wxString sel = postgres_sys_sel[0]; - if (sel.ToLong(&sel_l)) { - if (sel_l == 1) - GdaConst::hide_sys_table_postgres = true; - else if (sel_l == 0) - GdaConst::hide_sys_table_postgres = false; - } - } - vector hide_sys_table_sqlite = OGRDataAdapter::GetInstance().GetHistory("hide_sys_table_sqlite"); - if (!hide_sys_table_sqlite.empty()) { - long sel_l = 0; - wxString sel = hide_sys_table_sqlite[0]; - if (sel.ToLong(&sel_l)) { - if (sel_l == 1) - GdaConst::hide_sys_table_sqlite = true; - else if (sel_l == 0) - GdaConst::hide_sys_table_sqlite = false; - } - } - vector disable_crash_detect = OGRDataAdapter::GetInstance().GetHistory("disable_crash_detect"); - if (!disable_crash_detect.empty()) { - long sel_l = 0; - wxString sel = disable_crash_detect[0]; - if (sel.ToLong(&sel_l)) { - if (sel_l == 1) - GdaConst::disable_crash_detect = true; - else if (sel_l == 0) - GdaConst::disable_crash_detect = false; - } - } - vector disable_auto_upgrade = OGRDataAdapter::GetInstance().GetHistory("disable_auto_upgrade"); - if (!disable_auto_upgrade.empty()) { - long sel_l = 0; - wxString sel = disable_auto_upgrade[0]; - if (sel.ToLong(&sel_l)) { - if (sel_l == 1) - GdaConst::disable_auto_upgrade = true; - else if (sel_l == 0) - GdaConst::disable_auto_upgrade = false; - } - } - - vector show_recent_sample_connect_ds_dialog = OGRDataAdapter::GetInstance().GetHistory("show_recent_sample_connect_ds_dialog"); - if (!show_recent_sample_connect_ds_dialog.empty()) { - long sel_l = 0; - wxString sel = show_recent_sample_connect_ds_dialog[0]; - if (sel.ToLong(&sel_l)) { - if (sel_l == 1) - GdaConst::show_recent_sample_connect_ds_dialog = true; - else if (sel_l == 0) - GdaConst::show_recent_sample_connect_ds_dialog = false; - } - } - - vector show_csv_configure_in_merge = OGRDataAdapter::GetInstance().GetHistory("show_csv_configure_in_merge"); - if (!show_csv_configure_in_merge.empty()) { - long sel_l = 0; - wxString sel = show_csv_configure_in_merge[0]; - if (sel.ToLong(&sel_l)) { - if (sel_l == 1) - GdaConst::show_csv_configure_in_merge = true; - else if (sel_l == 0) - GdaConst::show_csv_configure_in_merge = false; - } - } - vector enable_high_dpi_support = OGRDataAdapter::GetInstance().GetHistory("enable_high_dpi_support"); - if (!enable_high_dpi_support.empty()) { - long sel_l = 0; - wxString sel = enable_high_dpi_support[0]; - if (sel.ToLong(&sel_l)) { - if (sel_l == 1) - GdaConst::enable_high_dpi_support = true; - else if (sel_l == 0) - GdaConst::enable_high_dpi_support = false; - } - } - vector gdal_http_timeout = OGRDataAdapter::GetInstance().GetHistory("gdal_http_timeout"); - if (!gdal_http_timeout.empty()) { - long sel_l = 0; - wxString sel = gdal_http_timeout[0]; - if (sel.ToLong(&sel_l)) { - GdaConst::gdal_http_timeout = sel_l; - } - } - - // following are not in this UI, but still global variable - vector gda_user_seed = OGRDataAdapter::GetInstance().GetHistory("gda_user_seed"); - if (!gda_user_seed.empty()) { - long sel_l = 0; - wxString sel = gda_user_seed[0]; - if (sel.ToLong(&sel_l)) { - GdaConst::gda_user_seed = sel_l; - } - } - vector use_gda_user_seed = OGRDataAdapter::GetInstance().GetHistory("use_gda_user_seed"); - if (!use_gda_user_seed.empty()) { - long sel_l = 0; - wxString sel = use_gda_user_seed[0]; - if (sel.ToLong(&sel_l)) { - if (sel_l == 1) - GdaConst::use_gda_user_seed = true; - else if (sel_l == 0) - GdaConst::use_gda_user_seed = false; - } - } -} - -void PreferenceDlg::OnTimeoutInput(wxCommandEvent& ev) -{ - wxString sec_str = txt23->GetValue(); - long sec; - if (sec_str.ToLong(&sec)) { - if (sec >= 0) { - GdaConst::gdal_http_timeout = sec; - OGRDataAdapter::GetInstance().AddEntry("gdal_http_timeout", sec_str.ToStdString()); - CPLSetConfigOption("GDAL_HTTP_TIMEOUT", sec_str); - } - } -} - -void PreferenceDlg::OnSlider1(wxCommandEvent& ev) -{ - int val = slider1->GetValue(); - GdaConst::transparency_highlighted = val; - wxString transp_str; - transp_str << val; - OGRDataAdapter::GetInstance().AddEntry("transparency_highlighted", transp_str.ToStdString()); - wxTextCtrl* txt_ctl = wxDynamicCast(FindWindow(XRCID("PREF_SLIDER1_TXT")), wxTextCtrl); - - wxString t_hl = wxString::Format("%.2f", (255 - val) / 255.0); - txt_ctl->SetValue(t_hl); - - if (highlight_state) { - highlight_state->SetEventType(HLStateInt::transparency); - highlight_state->notifyObservers(); - } -} -void PreferenceDlg::OnSlider2(wxCommandEvent& ev) -{ - int val = slider2->GetValue(); - GdaConst::transparency_unhighlighted = val; - wxString transp_str; - transp_str << val; - OGRDataAdapter::GetInstance().AddEntry("transparency_unhighlighted", transp_str.ToStdString()); - wxTextCtrl* txt_ctl = wxDynamicCast(FindWindow(XRCID("PREF_SLIDER2_TXT")), wxTextCtrl); - - wxString t_hl = wxString::Format("%.2f", (255 - val) / 255.0); - txt_ctl->SetValue(t_hl); - - if (highlight_state) { - highlight_state->SetEventType(HLStateInt::transparency); - highlight_state->notifyObservers(); - } -} -void PreferenceDlg::OnSlider6(wxCommandEvent& ev) -{ - int val = slider6->GetValue(); - GdaConst::plot_transparency_highlighted = val; - wxString transp_str; - transp_str << val; - OGRDataAdapter::GetInstance().AddEntry("plot_transparency_highlighted", transp_str.ToStdString()); - wxTextCtrl* txt_ctl = wxDynamicCast(FindWindow(XRCID("PREF_SLIDER6_TXT")), wxTextCtrl); - - wxString t_hl = wxString::Format("%.2f", (255 - val) / 255.0); - txt_ctl->SetValue(t_hl); - - if (highlight_state) { - highlight_state->SetEventType(HLStateInt::transparency); - highlight_state->notifyObservers(); - } -} -void PreferenceDlg::OnSlider7(wxCommandEvent& ev) -{ - int val = slider7->GetValue(); - GdaConst::plot_transparency_unhighlighted = val; - wxString transp_str; - transp_str << val; - OGRDataAdapter::GetInstance().AddEntry("plot_transparency_unhighlighted", transp_str.ToStdString()); - wxTextCtrl* txt_ctl = wxDynamicCast(FindWindow(XRCID("PREF_SLIDER7_TXT")), wxTextCtrl); - - wxString t_hl = wxString::Format("%.2f", (255 - val) / 255.0); - txt_ctl->SetValue(t_hl); - - if (highlight_state) { - highlight_state->SetEventType(HLStateInt::transparency); - highlight_state->notifyObservers(); - } -} - -void PreferenceDlg::OnChoice3(wxCommandEvent& ev) -{ - int basemap_sel = ev.GetSelection(); - if (basemap_sel <= 0) { - GdaConst::use_basemap_by_default = false; - OGRDataAdapter::GetInstance().AddEntry("use_basemap_by_default", "0"); - } - else { - GdaConst::use_basemap_by_default = true; - GdaConst::default_basemap_selection = basemap_sel; - wxString sel_str; - sel_str << GdaConst::default_basemap_selection; - OGRDataAdapter::GetInstance().AddEntry("use_basemap_by_default", "1"); - OGRDataAdapter::GetInstance().AddEntry("default_basemap_selection", sel_str.ToStdString()); - } -} - -void PreferenceDlg::OnCrossHatch(wxCommandEvent& ev) -{ - int crosshatch_sel = ev.GetSelection(); - if (crosshatch_sel == 0) { - GdaConst::use_cross_hatching = false; - OGRDataAdapter::GetInstance().AddEntry("use_cross_hatching", "0"); - } - else if (crosshatch_sel == 1) { - GdaConst::use_cross_hatching = true; - OGRDataAdapter::GetInstance().AddEntry("use_cross_hatching", "1"); - } - if (highlight_state) { - highlight_state->notifyObservers(); - } -} - -void PreferenceDlg::OnHideTablePostGIS(wxCommandEvent& ev) -{ - int sel = ev.GetSelection(); - if (sel == 0) { - GdaConst::hide_sys_table_postgres = false; - OGRDataAdapter::GetInstance().AddEntry("hide_sys_table_postgres", "0"); - } - else { - GdaConst::hide_sys_table_postgres = true; - OGRDataAdapter::GetInstance().AddEntry("hide_sys_table_postgres", "1"); - } -} - -void PreferenceDlg::OnHideTableSQLITE(wxCommandEvent& ev) -{ - int sel = ev.GetSelection(); - if (sel == 0) { - GdaConst::hide_sys_table_sqlite = false; - OGRDataAdapter::GetInstance().AddEntry("hide_sys_table_sqlite", "0"); - } - else { - GdaConst::hide_sys_table_sqlite = true; - OGRDataAdapter::GetInstance().AddEntry("hide_sys_table_sqlite", "1"); - - } -} -void PreferenceDlg::OnDisableCrashDetect(wxCommandEvent& ev) -{ - int sel = ev.GetSelection(); - if (sel == 0) { - GdaConst::disable_crash_detect = false; - OGRDataAdapter::GetInstance().AddEntry("disable_crash_detect", "0"); - } - else { - GdaConst::disable_crash_detect = true; - OGRDataAdapter::GetInstance().AddEntry("disable_crash_detect", "1"); - - } -} -void PreferenceDlg::OnDisableAutoUpgrade(wxCommandEvent& ev) -{ - int sel = ev.GetSelection(); - if (sel == 0) { - GdaConst::disable_auto_upgrade = false; - OGRDataAdapter::GetInstance().AddEntry("disable_auto_upgrade", "0"); - } - else { - GdaConst::disable_auto_upgrade = true; - OGRDataAdapter::GetInstance().AddEntry("disable_auto_upgrade", "1"); - - } -} -void PreferenceDlg::OnShowRecent(wxCommandEvent& ev) -{ - int sel = ev.GetSelection(); - if (sel == 0) { - GdaConst::show_recent_sample_connect_ds_dialog = false; - OGRDataAdapter::GetInstance().AddEntry("show_recent_sample_connect_ds_dialog", "0"); - } - else { - GdaConst::show_recent_sample_connect_ds_dialog = true; - OGRDataAdapter::GetInstance().AddEntry("show_recent_sample_connect_ds_dialog", "1"); - - } -} -void PreferenceDlg::OnShowCsvInMerge(wxCommandEvent& ev) -{ - int sel = ev.GetSelection(); - if (sel == 0) { - GdaConst::show_csv_configure_in_merge = false; - OGRDataAdapter::GetInstance().AddEntry("show_csv_configure_in_merge", "0"); - } - else { - GdaConst::show_csv_configure_in_merge = true; - OGRDataAdapter::GetInstance().AddEntry("show_csv_configure_in_merge", "1"); - } -} -void PreferenceDlg::OnEnableHDPISupport(wxCommandEvent& ev) -{ - int sel = ev.GetSelection(); - if (sel == 0) { - GdaConst::enable_high_dpi_support = false; - OGRDataAdapter::GetInstance().AddEntry("enable_high_dpi_support", "0"); - } - else { - GdaConst::enable_high_dpi_support = true; - OGRDataAdapter::GetInstance().AddEntry("enable_high_dpi_support", "1"); - } -} -//////////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// ReportResultDlg::ReportResultDlg(wxWindow* parent, wxString issue_url, wxWindowID id, const wxString& title, @@ -851,7 +150,7 @@ size_t write_to_string_(void *ptr, size_t size, size_t count, void *stream) { string CreateIssueOnGithub(string& post_data) { - std::vector tester_ids = OGRDataAdapter::GetInstance().GetHistory("tester_id"); + std::vector tester_ids = OGRDataAdapter::GetInstance().GetHistory("tester_id"); if (tester_ids.empty()) { return ""; } diff --git a/DialogTools/ReportBugDlg.h b/DialogTools/ReportBugDlg.h index abd3f886a..f1a500654 100644 --- a/DialogTools/ReportBugDlg.h +++ b/DialogTools/ReportBugDlg.h @@ -56,87 +56,6 @@ class WelcomeSelectionStyleDlg : public wxDialog void OnStyle2(wxMouseEvent& ev); }; -//////////////////////////////////////////////////////////////////////////////// -// -// PreferenceDlg -// -//////////////////////////////////////////////////////////////////////////////// -class PreferenceDlg : public wxDialog -{ -public: - PreferenceDlg(wxWindow* parent, - wxWindowID id = wxID_ANY, - const wxString& title = _("GeoDa Preference Setup"), - const wxPoint& pos = wxDefaultPosition, - const wxSize& size = wxSize(580,640)); - - PreferenceDlg(wxWindow* parent, - HLStateInt* highlight_state, - wxWindowID id = wxID_ANY, - const wxString& title = _("GeoDa Preference Setup"), - const wxPoint& pos = wxDefaultPosition, - const wxSize& size = wxSize(580,640)); - - static void ReadFromCache(); - -protected: - HLStateInt* highlight_state; - // PREF_USE_CROSSHATCH - wxCheckBox* cbox0; - // PREF_SLIDER1_TXT - wxSlider* slider1; - wxTextCtrl* slider_txt1; - // PREF_SLIDER2_TXT - wxSlider* slider2; - wxTextCtrl* slider_txt2; - // basemap auto - wxComboBox* cmb33; - // Transparency of highlighted object - wxSlider* slider6; - // plot unhighlighted transp - wxSlider* slider7; - wxTextCtrl* slider_txt7; - // crash detect - wxCheckBox* cbox4; - // auto upgrade - wxCheckBox* cbox5; - // show recent - wxCheckBox* cbox8; - // show cvs in merge - wxCheckBox* cbox9; - // enable High DPI - wxCheckBox* cbox10; - // postgresql - wxCheckBox* cbox21; - // sqlite - wxCheckBox* cbox22; - // timeout - wxTextCtrl* txt23; - - void Init(); - void SetupControls(); - - void OnCrossHatch(wxCommandEvent& ev); - void OnSlider1(wxCommandEvent& ev); - void OnSlider2(wxCommandEvent& ev); - //void OnSlider3(wxCommandEvent& ev); - void OnChoice3(wxCommandEvent& ev); - void OnDisableCrashDetect(wxCommandEvent& ev); - void OnDisableAutoUpgrade(wxCommandEvent& ev); - void OnShowRecent(wxCommandEvent& ev); - void OnShowCsvInMerge(wxCommandEvent& ev); - void OnEnableHDPISupport(wxCommandEvent& ev); - - void OnSlider6(wxCommandEvent& ev); - void OnSlider7(wxCommandEvent& ev); - - void OnHideTablePostGIS(wxCommandEvent& ev); - void OnHideTableSQLITE(wxCommandEvent& ev); - void OnTimeoutInput(wxCommandEvent& ev); - - void OnReset(wxCommandEvent& ev); -}; - //////////////////////////////////////////////////////////////////////////////// // // ReportResultDlg @@ -153,7 +72,7 @@ class ReportResultDlg: public wxDialog wxWindowID id = wxID_ANY, const wxString& title = _("Check Bug Report on Github"), const wxPoint& pos = wxDefaultPosition, - const wxSize& size = wxDefaultSize); + const wxSize& size = wxSize(680,200)); ~ReportResultDlg(); }; diff --git a/DialogTools/SHP2ASCDlg.cpp b/DialogTools/SHP2ASCDlg.cpp deleted file mode 100644 index f5a38b2b7..000000000 --- a/DialogTools/SHP2ASCDlg.cpp +++ /dev/null @@ -1,449 +0,0 @@ -/** - * GeoDa TM, Copyright (C) 2011-2015 by Luc Anselin - all rights reserved - * - * This file is part of GeoDa. - * - * GeoDa is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * GeoDa is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -#include - -#ifndef WX_PRECOMP - #include -#endif - -#include -#include -#include -#include // XRC XML resouces - -#include "../ShapeOperations/ShapeFileTypes.h" -#include "../ShapeOperations/ShapeFileHdr.h" - -#include "../ShapeOperations/OGRDatasourceProxy.h" -#include "../ShapeOperations/OGRLayerProxy.h" -#include "SHP2ASCDlg.h" -#include "ConnectDatasourceDlg.h" - -using namespace ShapeFileTypes; - -BEGIN_EVENT_TABLE( SHP2ASCDlg, wxDialog ) - EVT_BUTTON( XRCID("IDOK_ADD"), SHP2ASCDlg::OnOkAddClick ) - EVT_BUTTON( XRCID("IDC_OPEN_OASC"), SHP2ASCDlg::OnCOpenOascClick ) - EVT_BUTTON( XRCID("IDOKDONE"), SHP2ASCDlg::OnOkdoneClick ) - EVT_RADIOBUTTON( XRCID("IDC_RADIO1"), SHP2ASCDlg::OnCRadio1Selected ) - EVT_RADIOBUTTON( XRCID("IDC_RADIO2"), SHP2ASCDlg::OnCRadio2Selected ) - EVT_RADIOBUTTON( XRCID("IDC_RADIO3"), SHP2ASCDlg::OnCRadio3Selected ) - EVT_RADIOBUTTON( XRCID("IDC_RADIO4"), SHP2ASCDlg::OnCRadio4Selected ) - EVT_BUTTON( XRCID("IDC_OPEN_ISHP"), SHP2ASCDlg::OnCOpenIshpClick ) -END_EVENT_TABLE() - -bool SHP2ASCDlg::CreateASCBoundary(wxString oasc, wxString orasc, int field, - int type, bool isR) -{ - if(isR && !orasc) - return false; - - ofstream ascr; - if (isR) { - //ascr.open(orasc); // produce bounding box file. - ascr.open(GET_ENCODED_FILENAME(orasc)); - } - - if(isR) { - if(!ascr.is_open()) - return false; - } - - ofstream asc; - asc.open(GET_ENCODED_FILENAME(oasc)); - - if(!asc.is_open()) - return false; - - int n = ogr_layer->GetNumRecords(); - string field_name = ogr_layer->GetFieldName(field).ToStdString(); - - switch(type) { - case 1: - case 3: - break; - case 2: - case 4: - asc << n << "," << field_name << endl; - if(isR) ascr << n << "," << field_name << endl; - break; - default: - asc.close(); - if(isR) - ascr.close(); - return false; - } - - double* polyid = NULL; - string* temp_y = NULL; - int col_type; - - if (ogr_layer->GetFieldType(field) == GdaConst::long64_type || - ogr_layer->GetFieldType(field) == GdaConst::double_type ) { - polyid = new double[n]; - col_type = 1; - for (int i=0; idata[i]->GetFieldAsInteger64(field); - } - - } else if (ogr_layer->GetFieldType(field) == GdaConst::string_type) { - temp_y = new string[n + 1]; - col_type = 0; - for (int i=0; idata[i]->GetFieldAsString(field); - } - - } else { - wxMessageBox(_("This file type is not supported.")); - return false; - } - - if (ogr_layer->GetShapeType() == wkbPolygon || - ogr_layer->GetShapeType() == wkbMultiPolygon ) { - - for (long rec= 0; rec < n; ++rec) - { - if(col_type == 0) - asc << temp_y[rec]; - else - asc << polyid[rec]; - - int n_po = 0; - OGRGeometry* geom = ogr_layer->data[rec]->GetGeometryRef(); - OGRPolygon* poly = dynamic_cast(geom); - OGRMultiPolygon* multi_poly = NULL; - - // if a OGRPolygon, build a OGRMultiPolygon - if ( poly != NULL ) { - multi_poly = new OGRMultiPolygon(); - multi_poly->addGeometry(poly); - } else { - multi_poly = dynamic_cast(geom); - } - - int num_sub_polys = multi_poly->getNumGeometries(); - - for ( int i=0; i < num_sub_polys; i++) { - OGRPolygon* sub_poly = - (OGRPolygon*)multi_poly->getGeometryRef(i); - OGRLinearRing* ext_ring = sub_poly->getExteriorRing(); - n_po += ext_ring->getNumPoints(); - int num_inner_rings = sub_poly->getNumInteriorRings(); - for (int j=0; j < num_inner_rings; j++) { - OGRLinearRing* inn_ring = sub_poly->getInteriorRing(j); - n_po += inn_ring->getNumPoints(); - } - } - - switch(type) - { - case 1: - case 2: - asc << "," << n_po << endl; - break; - case 3: - case 4: - asc << endl; - break; - default: - - return false; - } - - if(isR) { - if(col_type == 0) - ascr << temp_y[rec]; - else - ascr << polyid[rec]; - - OGREnvelope pEnvelope; - multi_poly->getEnvelope(&pEnvelope); - - ascr << "," << wxString::Format("%.10f", pEnvelope.MinX); - ascr << "," << wxString::Format("%.10f", pEnvelope.MinY); - ascr << "," << wxString::Format("%.10f", pEnvelope.MaxX); - ascr << "," << wxString::Format("%.10f", pEnvelope.MaxY); - ascr << endl; - } - - OGRLinearRing* ext_ring = NULL; - - for ( int i=0; i < num_sub_polys; i++) { - OGRPolygon* sub_poly = - (OGRPolygon*)multi_poly->getGeometryRef(i); - ext_ring = sub_poly->getExteriorRing(); - for (int i=0; i < ext_ring->getNumPoints(); i++) { - asc << wxString::Format("%.10f", ext_ring->getX(i)); - asc << ","; - asc << wxString::Format("%.10f", ext_ring->getY(i)); - asc << endl; - } - int num_inner_rings = sub_poly->getNumInteriorRings(); - for (int i=0; i < num_inner_rings; i++) { - OGRLinearRing* inn_ring = sub_poly->getInteriorRing(i); - for (int j=0; j < inn_ring->getNumPoints(); j++) { - asc << wxString::Format("%.10f", inn_ring->getX(j)); - asc << ","; - asc << wxString::Format("%.10f", inn_ring->getY(j)); - asc << endl; - } - } - } - - } - } - - if(polyid) - delete [] polyid; - polyid = NULL; - if(temp_y) - delete [] temp_y; - temp_y = NULL; - - asc.close(); - if(isR) - ascr.close(); - - return true; -} - -SHP2ASCDlg::SHP2ASCDlg( ) -: ogr_ds(NULL), ogr_layer(NULL) -{ -} - -SHP2ASCDlg::SHP2ASCDlg( wxWindow* parent, wxWindowID id, - const wxString& caption, const wxPoint& pos, - const wxSize& size, long style ) -: ogr_ds(NULL), ogr_layer(NULL) -{ - type = -1; - Create(parent, id, caption, pos, size, style); - - FindWindow(XRCID("IDC_OPEN_OASC"))->Enable(false); - FindWindow(XRCID("IDC_FIELD_ASC"))->Enable(false); - FindWindow(XRCID("IDC_KEYVAR"))->Enable(false); - FindWindow(XRCID("IDOK_ADD"))->Enable(false); -} - -SHP2ASCDlg::~SHP2ASCDlg() -{ - if ( ogr_ds ) { - delete ogr_ds; - ogr_ds = NULL; - } -} - -bool SHP2ASCDlg::Create( wxWindow* parent, wxWindowID id, - const wxString& caption, const wxPoint& pos, - const wxSize& size, long style ) -{ - SetParent(parent); - CreateControls(); - Centre(); - - m_ra1->SetValue(true); - type = 1; - - return true; -} - - -void SHP2ASCDlg::CreateControls() -{ - wxXmlResource::Get()->LoadDialog(this, GetParent(), "IDD_CONVERT_SHP2ASC"); - m_inputfile = XRCCTRL(*this, "IDC_FIELD_SHP", wxTextCtrl); - m_inputfile->SetMaxLength(0); - m_outputfile = XRCCTRL(*this, "IDC_FIELD_ASC", wxTextCtrl); - m_outputfile->SetMaxLength(0); - m_X = XRCCTRL(*this, "IDC_KEYVAR", wxChoice); - m_check = XRCCTRL(*this, "IDC_CHECK1", wxCheckBox); - m_ra1 = XRCCTRL(*this, "IDC_RADIO1", wxRadioButton); - m_ra1a = XRCCTRL(*this, "IDC_RADIO2", wxRadioButton); - m_ra2 = XRCCTRL(*this, "IDC_RADIO3", wxRadioButton); - m_ra2a = XRCCTRL(*this, "IDC_RADIO4", wxRadioButton); - - if (m_ra1->GetValue()) type = 1; - if (m_ra1a->GetValue()) type = 2; - if (m_ra2->GetValue()) type = 3; - if (m_ra2a->GetValue()) type = 4; -} - -void SHP2ASCDlg::OnOkAddClick( wxCommandEvent& event ) -{ - wxLogMessage("In SHP2ASCDlg::OnOkAddClick()"); - if(type == -1) { - wxMessageBox(_("Please select an option.")); - return; - } - - wxString m_ishp = m_inputfile->GetValue(); - wxString m_oasc = m_outputfile->GetValue(); - wxString DirName; - wxString RName; - wxString RNameExt; - - int pos = m_ishp.Find('.',true); - if (pos > 0) - DirName = m_ishp.Left(pos); - else - DirName = m_ishp; - - wxString ifl = DirName; - wxString ofl = m_oasc; - - pos = m_oasc.Find('.',true); - if (pos > 0) { - RName = m_oasc.Left(pos); - RNameExt = m_oasc.Right(m_oasc.Length()-pos); - } else { - RName = m_oasc; - RNameExt = wxEmptyString; - } - - bool m_isR = m_check->GetValue(); - - if(m_isR) { - wxString orf = RName+ "_r" +RNameExt; - - if(!CreateASCBoundary(ofl, orf, m_X->GetSelection(), type, m_isR)) { - wxMessageBox(_("Can't write output file!")); - return; - } - - } else { - if(!CreateASCBoundary(ofl, wxEmptyString, m_X->GetSelection(), - type, m_isR)) { - wxMessageBox(_("Can't write output file!")); - return; - } - } - - wxMessageDialog dlg (this, _("Export shape to boundary successfully."), - _("Info"), wxOK | wxICON_INFORMATION); - dlg.ShowModal(); - - event.Skip(); -} - -void SHP2ASCDlg::OnCOpenOascClick( wxCommandEvent& event ) -{ - wxLogMessage("In SHP2ASCDlg::OnCOpenOascClick()"); - - wxFileDialog dlg(this, - _("Output ASCII file"), - wxEmptyString, - fn + ".txt", - "ASCII files (*.txt)|*.txt", - wxFD_SAVE | wxFD_OVERWRITE_PROMPT); - - wxString m_path = wxEmptyString; - - if (dlg.ShowModal() == wxID_OK) { - m_path = dlg.GetPath(); - wxString OutFile = m_path; - m_outputfile->SetValue(OutFile); - FindWindow(XRCID("IDOK_ADD"))->Enable(true); - } -} - -void SHP2ASCDlg::OnOkdoneClick( wxCommandEvent& event ) -{ - wxLogMessage("In SHP2ASCDlg::OnOkdoneClick()"); - - event.Skip(); - EndDialog(wxID_CANCEL); -} - -void SHP2ASCDlg::OnCRadio1Selected( wxCommandEvent& event ) -{ - wxLogMessage("In SHP2ASCDlg::OnCRadio1Selected()"); - - type = 1; -} - -void SHP2ASCDlg::OnCRadio2Selected( wxCommandEvent& event ) -{ - wxLogMessage("In SHP2ASCDlg::OnCRadio2Selected()"); - type = 2; -} - -void SHP2ASCDlg::OnCRadio3Selected( wxCommandEvent& event ) -{ - wxLogMessage("In SHP2ASCDlg::OnCRadio3Selected()"); - type = 3; -} - -void SHP2ASCDlg::OnCRadio4Selected( wxCommandEvent& event ) -{ - wxLogMessage("In SHP2ASCDlg::OnCRadio4Selected()"); - type = 4; -} - - -void SHP2ASCDlg::OnCOpenIshpClick( wxCommandEvent& event ) -{ - wxLogMessage("In SHP2ASCDlg::OnCOpenIshpClick()"); - try{ - ConnectDatasourceDlg dlg(this); - if (dlg.ShowModal() != wxID_OK) return; - - wxString proj_title = dlg.GetProjectTitle(); - wxString layer_name = dlg.GetLayerName(); - IDataSource* datasource = dlg.GetDataSource(); - wxString ds_name = datasource->GetOGRConnectStr(); - GdaConst::DataSourceType ds_type = datasource->GetType(); - - ogr_ds = new OGRDatasourceProxy(ds_name, ds_type, true); - ogr_layer = ogr_ds->GetLayerProxy(layer_name.ToStdString()); - ogr_layer->ReadData(); - - bool is_valid_layer = true; - - if (ogr_layer->IsTableOnly()) { - wxMessageBox(_("This is not a shape datasource. Please open a valid shape datasource, e.g. ESRI Shapefile, PostGIS layer...")); - is_valid_layer = false; - } - if (ogr_layer->GetNumFields() == 0){ - wxMessageBox(_("No fields found!")); - is_valid_layer = false; - } - if ( !is_valid_layer) { - delete ogr_ds; - ogr_ds = NULL; - return; - } - - m_X->Clear(); - for (int i=0; iGetNumFields(); i++){ - m_X->Append(wxString::Format("%s",ogr_layer->GetFieldName(i))); - } - m_X->SetSelection(0); - m_inputfile->SetValue(layer_name); - - FindWindow(XRCID("IDC_OPEN_OASC"))->Enable(true); - FindWindow(XRCID("IDC_FIELD_ASC"))->Enable(true); - FindWindow(XRCID("IDC_KEYVAR"))->Enable(true); - } catch (GdaException& e) { - wxMessageDialog dlg (this, e.what(), "Error", wxOK | wxICON_ERROR); - dlg.ShowModal(); - return; - } -} diff --git a/DialogTools/SHP2ASCDlg.h b/DialogTools/SHP2ASCDlg.h deleted file mode 100644 index 2cf44f51b..000000000 --- a/DialogTools/SHP2ASCDlg.h +++ /dev/null @@ -1,75 +0,0 @@ -/** - * GeoDa TM, Copyright (C) 2011-2015 by Luc Anselin - all rights reserved - * - * This file is part of GeoDa. - * - * GeoDa is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * GeoDa is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -#ifndef __GEODA_CENTER_SHP_2_ASC_DLG_H__ -#define __GEODA_CENTER_SHP_2_ASC_DLG_H__ - -#include "../ShapeOperations/OGRDatasourceProxy.h" -#include "../ShapeOperations/OGRLayerProxy.h" - -class SHP2ASCDlg: public wxDialog -{ - DECLARE_EVENT_TABLE() - -public: - SHP2ASCDlg( ); - SHP2ASCDlg( wxWindow* parent, wxWindowID id = -1, - const wxString& caption = _("Exporting Shape to Boundary"), - const wxPoint& pos = wxDefaultPosition, - const wxSize& size = wxDefaultSize, - long style = wxCAPTION|wxDEFAULT_DIALOG_STYLE ); - ~SHP2ASCDlg(); - - bool Create( wxWindow* parent, wxWindowID id = -1, - const wxString& caption = _("Exporting Shape to Boundary"), - const wxPoint& pos = wxDefaultPosition, - const wxSize& size = wxDefaultSize, - long style = wxCAPTION|wxDEFAULT_DIALOG_STYLE ); - - bool CreateASCBoundary(wxString oasc, wxString orasc, int field, - int type, bool isR); - void CreateControls(); - - void OnOkAddClick( wxCommandEvent& event ); - void OnCOpenOascClick( wxCommandEvent& event ); - void OnOkdoneClick( wxCommandEvent& event ); - void OnCRadio1Selected( wxCommandEvent& event ); - void OnCRadio2Selected( wxCommandEvent& event ); - void OnCRadio3Selected( wxCommandEvent& event ); - void OnCRadio4Selected( wxCommandEvent& event ); - void OnCOpenIshpClick( wxCommandEvent& event ); - -private: - wxTextCtrl* m_inputfile; - wxTextCtrl* m_outputfile; - wxChoice* m_X; - wxCheckBox* m_check; - wxRadioButton* m_ra1; - wxRadioButton* m_ra1a; - wxRadioButton* m_ra2; - wxRadioButton* m_ra2a; - - int type; - wxString fn; - - OGRDatasourceProxy* ogr_ds; - OGRLayerProxy* ogr_layer; -}; - -#endif diff --git a/DialogTools/SaveAsDlg.cpp b/DialogTools/SaveAsDlg.cpp index a0f1c651f..8f561f2f0 100644 --- a/DialogTools/SaveAsDlg.cpp +++ b/DialogTools/SaveAsDlg.cpp @@ -111,8 +111,8 @@ void SaveAsDlg::OnBrowseDatasourceBtn ( wxCommandEvent& event ) wxString msg; IDataSource* datasource = project_p->GetDataSource(); if ( datasource == NULL ) { - msg = "Datasource in project is not valid."; - wxMessageDialog dlg(this, msg , "Error", wxOK | wxICON_INFORMATION); + msg = _("Datasource in project is not valid."); + wxMessageDialog dlg(this, msg , _("Error"), wxOK | wxICON_INFORMATION); dlg.ShowModal(); return; } @@ -129,10 +129,9 @@ void SaveAsDlg::OnBrowseDatasourceBtn ( wxCommandEvent& event ) ds_type != GdaConst::ds_gpkg && ds_type != GdaConst::ds_csv) { - msg << "Save is not supported on current data source type: " - << ds_format << ". Please try to use \"File->Save As\" other data source. " - << "However, the project file can still be saved as other project file."; - wxMessageDialog dlg (this, msg, "Warning", wxOK | wxICON_INFORMATION); + msg = _("Save is not supported on current data source type: %s. Please try to use \"File->Save As\" other data source. However, the project file can still be saved as other project file."); + msg = wxString::Format(msg, ds_format); + wxMessageDialog dlg (this, msg, _("Warning"), wxOK | wxICON_INFORMATION); dlg.ShowModal(); m_datasource_path_txt->SetValue(""); m_chk_create_datasource->SetValue(false); @@ -141,15 +140,15 @@ void SaveAsDlg::OnBrowseDatasourceBtn ( wxCommandEvent& event ) wxString ds_path = project_p->GetDataSource()->GetOGRConnectStr(); wxString suffix = ds_path.AfterLast('.'); if ( suffix.empty() ) { - msg << "The original datasource " << ds_path << " is not a valid file." - "GeoDa \"Save\" only works on file datasource."; - wxMessageDialog dlg(this, msg , "Warning", wxOK | wxICON_INFORMATION); + msg = _("The original datasource %s is not a valid file. GeoDa \"Save\" only works on file datasource."); + msg = wxString::Format(msg, ds_path); + wxMessageDialog dlg(this, msg , _("Warning"), wxOK | wxICON_INFORMATION); dlg.ShowModal(); return; } wxString wildcard; wildcard << ds_format << " (*." << suffix << ")|*." << suffix; - wxFileDialog dlg(this, "Save As Datasource", "", "", wildcard, + wxFileDialog dlg(this, _("Save As Datasource"), "", "", wildcard, wxFD_SAVE|wxFD_OVERWRITE_PROMPT); if (dlg.ShowModal() != wxID_OK) return; ds_file_path = dlg.GetPath(); @@ -188,7 +187,7 @@ void SaveAsDlg::OnOkClick( wxCommandEvent& event ) project_p->SpecifyProjectConfFile(project_fname); project_p->SaveProjectConf(); } else { - msg = "Project file path is empty."; + msg = _("Project file path is empty."); } } else if ( !bSaveProject && bSaveDatasource ) { // SaveAs datasource only @@ -196,13 +195,12 @@ void SaveAsDlg::OnOkClick( wxCommandEvent& event ) bool is_update = false; project_p->SaveDataSourceAs(datasource_fname, is_update); } else { - msg = "Datasource path is empty."; + msg = _("Datasource path is empty."); } } else if ( bSaveProject && bSaveDatasource ) { // SaveAs project + datasource if ( project_fname.empty() || datasource_fname.empty() ) { - msg = "Please provide paths for both Project file and " - "Datasource."; + msg = _("Please provide paths for both Project file and Datasource."); } else { project_p->SpecifyProjectConfFile(project_fname); bool is_update = false; @@ -239,17 +237,17 @@ void SaveAsDlg::OnOkClick( wxCommandEvent& event ) } if ( !msg.empty() ) { - wxMessageDialog dlg(this, msg , "Info", wxOK | wxICON_INFORMATION); + wxMessageDialog dlg(this, msg , _("Info"), wxOK | wxICON_INFORMATION); dlg.ShowModal(); return; } - msg = "Saved successfully."; - wxMessageDialog dlg(this, msg , "Info", wxOK | wxICON_INFORMATION); + msg = _("Saved successfully."); + wxMessageDialog dlg(this, msg , _("Info"), wxOK | wxICON_INFORMATION); dlg.ShowModal(); EndDialog(wxID_OK); } catch (GdaException& e) { - wxMessageDialog dlg (this, e.what(), "Error", wxOK | wxICON_ERROR); + wxMessageDialog dlg (this, e.what(), _("Error"), wxOK | wxICON_ERROR); dlg.ShowModal(); return; } diff --git a/DialogTools/SaveAsDlg.h b/DialogTools/SaveAsDlg.h index a47e5f501..75152f7be 100644 --- a/DialogTools/SaveAsDlg.h +++ b/DialogTools/SaveAsDlg.h @@ -38,7 +38,7 @@ class SaveAsDlg: public wxDialog SaveAsDlg(wxWindow* parent, Project* project, wxWindowID id = wxID_ANY, - const wxString& title = "Save Project File As...", + const wxString& title = _("Save Project File As..."), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize ); void OnOkClick( wxCommandEvent& event ); diff --git a/DialogTools/SaveSelectionDlg.cpp b/DialogTools/SaveSelectionDlg.cpp index beabd26dc..48b2b8445 100644 --- a/DialogTools/SaveSelectionDlg.cpp +++ b/DialogTools/SaveSelectionDlg.cpp @@ -292,8 +292,8 @@ void SaveSelectionDlg::OnApplySaveClick( wxCommandEvent& event ) wxString field_name = m_save_sel_var_name->GetValue(); if (field_name.empty()) { - wxMessageDialog dlg(this, "Variable name can't be empty.", - "Error", wxOK | wxICON_ERROR ); + wxMessageDialog dlg(this, _("Variable name can't be empty."), + _("Error"), wxOK | wxICON_ERROR ); dlg.ShowModal(); return; } @@ -389,14 +389,14 @@ void SaveSelectionDlg::OnApplySaveClick( wxCommandEvent& event ) table_int->SetColData(write_col, sf_tm, t); table_int->SetColUndefined(write_col, sf_tm, undefined); } else { - wxString msg = "Chosen field is not a numeric type. Please select a numeric type field."; + wxString msg = _("Chosen field is not a numeric type. Please select a numeric type field."); - wxMessageDialog dlg(this, msg, "Error", wxOK | wxICON_ERROR ); + wxMessageDialog dlg(this, msg, _("Error"), wxOK | wxICON_ERROR ); dlg.ShowModal(); return; } - wxString msg = "Values assigned to target field successfully."; + wxString msg = _("Values assigned to target field successfully."); wxMessageDialog dlg(this, msg, "Success", wxOK | wxICON_INFORMATION ); dlg.ShowModal(); OnCancelClick(event); diff --git a/DialogTools/SaveToTableDlg.cpp b/DialogTools/SaveToTableDlg.cpp index 4d857b94d..6133f7043 100644 --- a/DialogTools/SaveToTableDlg.cpp +++ b/DialogTools/SaveToTableDlg.cpp @@ -25,7 +25,6 @@ #include #include -#include "../DbfFile.h" #include "../DataViewer/DataViewerAddColDlg.h" #include "../DataViewer/TableInterface.h" #include "../DataViewer/TimeState.h" @@ -90,7 +89,7 @@ all_init(false) } - m_field_label = new wxStaticText(this, wxID_ANY, "Variable Name"); + m_field_label = new wxStaticText(this, wxID_ANY, _("Variable Name")); if (data.size() == 1) m_check[0]->SetValue(1); @@ -135,17 +134,17 @@ void SaveToTableDlg::CreateControls() //if (is_space_time) { // fg_sizer->Add(m_time[i], 0, wxALIGN_CENTRE_VERTICAL | wxALL, 5); //} - fg_sizer->Add(m_check[i], 0, wxALL|wxALIGN_CENTER, 2); + fg_sizer->Add(m_check[i], 0, wxALL|wxALIGN_LEFT, 2); fg_sizer->Add(m_txt_field[i], 0, wxALL|wxALIGN_CENTER, 5); } //top_sizer->Add(fg_sizer, 0, wxALL, 8); // border of 8 around fg_sizer top_sizer->Add(fg_sizer, 0, wxALL|wxALIGN_CENTER, 5); wxBoxSizer *button_sizer = new wxBoxSizer(wxHORIZONTAL); - m_ok_button = new wxButton(this, wxID_OK, "OK"); + m_ok_button = new wxButton(this, wxID_OK, _("OK")); //m_ok_button->Disable(); button_sizer->Add(m_ok_button, 0, wxALL, 5); - button_sizer->Add(new wxButton(this, wxID_CLOSE, "Close"), 0, wxALL, 5); + button_sizer->Add(new wxButton(this, wxID_CLOSE, _("Close")), 0, wxALL, 5); top_sizer->Add(button_sizer, 0, wxALL|wxALIGN_CENTER, 5); @@ -166,9 +165,8 @@ void SaveToTableDlg::OnAddFieldButton( wxCommandEvent& event ) } } if (obj_id == -1) { - wxString msg = "Could not determine which Add Variable button was " - "pressed. Please report this error."; - wxMessageDialog dlg(this, msg, "Error", wxOK | wxICON_ERROR ); + wxString msg = "Could not determine which Add Variable button was pressed. Please report this error."; + wxMessageDialog dlg(this, msg, _("Error"), wxOK | wxICON_ERROR ); dlg.ShowModal(); return; } @@ -227,9 +225,8 @@ void SaveToTableDlg::OnFieldChoice( wxCommandEvent& event ) } } if (obj_id == -1) { - wxString msg = "Could not determine which Field Choice was " - "selected. Please report this error."; - wxMessageDialog dlg(this, msg, "Error", wxOK | wxICON_ERROR ); + wxString msg = "Could not determine which Field Choice was selected. Please report this error."; + wxMessageDialog dlg(this, msg, _("Error"), wxOK | wxICON_ERROR ); dlg.ShowModal(); return; } @@ -250,9 +247,8 @@ void SaveToTableDlg::OnTimeChoice( wxCommandEvent& event ) } } if (obj_id == -1) { - wxString msg = "Could not determine which Time Choice was " - "selected. Please report this error."; - wxMessageDialog dlg(this, msg, "Error", wxOK | wxICON_ERROR ); + wxString msg = "Could not determine which Time Choice was selected. Please report this error."; + wxMessageDialog dlg(this, msg, _("Error"), wxOK | wxICON_ERROR ); dlg.ShowModal(); return; } @@ -347,8 +343,8 @@ void SaveToTableDlg::OnOkClick( wxCommandEvent& event ) if (is_check[i]) { wxString name = m_txt_field[i]->GetValue(); if (name.empty()) { - wxMessageDialog dlg(this, "Variable name can't be empty.", - "Error", wxOK | wxICON_ERROR ); + wxMessageDialog dlg(this, _("Variable name can't be empty."), + _("Error"), wxOK | wxICON_ERROR ); dlg.ShowModal(); return; } @@ -365,8 +361,8 @@ void SaveToTableDlg::OnOkClick( wxCommandEvent& event ) it = names.find(s); if (it != names.end()) { - wxMessageDialog dlg(this, "Duplicate variable names specified.", - "Error", wxOK | wxICON_ERROR ); + wxMessageDialog dlg(this, _("Duplicate variable names specified."), + _("Error"), wxOK | wxICON_ERROR ); dlg.ShowModal(); return; } @@ -410,6 +406,8 @@ void SaveToTableDlg::OnOkClick( wxCommandEvent& event ) table_int->SetColUndefined(col, time, *data[i].undefined); } } + new_col_ids.push_back(col); + new_col_names.push_back(field_name); } } diff --git a/DialogTools/SaveToTableDlg.h b/DialogTools/SaveToTableDlg.h index da5abe33c..a2d6688be 100644 --- a/DialogTools/SaveToTableDlg.h +++ b/DialogTools/SaveToTableDlg.h @@ -52,7 +52,7 @@ class SaveToTableDlg: public wxDialog public: SaveToTableDlg( Project* project, wxWindow* parent, const std::vector& data, - const wxString& title = "Save Results", + const wxString& title = _("Save Results"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER ); @@ -64,7 +64,10 @@ class SaveToTableDlg: public wxDialog void OnTimeChoice( wxCommandEvent& event ); void OnOkClick( wxCommandEvent& event ); void OnCloseClick( wxCommandEvent& event ); - + + std::vector new_col_ids; + std::vector new_col_names; + private: void FillColIdMaps(); void InitField(int button); diff --git a/DialogTools/SelectWeightsDlg.cpp b/DialogTools/SelectWeightsDlg.cpp index 541a131b9..6fb9153f7 100644 --- a/DialogTools/SelectWeightsDlg.cpp +++ b/DialogTools/SelectWeightsDlg.cpp @@ -342,8 +342,8 @@ void SelectWeightsDlg::SetDetailsWin(const std::vector& row_title, s << ""; s << " "; s << " "; - s << " "; - s << " "; + s << " "; + s << " "; s << " "; for (size_t i=0, last=row_title.size()-1; i" : ""); diff --git a/DialogTools/SkaterDlg.cpp b/DialogTools/SkaterDlg.cpp new file mode 100644 index 000000000..8bc82eae0 --- /dev/null +++ b/DialogTools/SkaterDlg.cpp @@ -0,0 +1,662 @@ +/** + * GeoDa TM, Copyright (C) 2011-2015 by Luc Anselin - all rights reserved + * + * This file is part of GeoDa. + * + * GeoDa is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * GeoDa is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../ShapeOperations/WeightUtils.h" +#include "../VarCalc/WeightsManInterface.h" +#include "../ShapeOperations/OGRDataAdapter.h" +#include "../ShapeOperations/WeightsManager.h" +#include "../Explore/MapNewView.h" +#include "../Project.h" +#include "../Algorithms/cluster.h" +#include "../Algorithms/maxp.h" +#include "../Algorithms/DataUtils.h" + +#include "../GeneralWxUtils.h" +#include "../GenUtils.h" +#include "SaveToTableDlg.h" +#include "SkaterDlg.h" + + +BEGIN_EVENT_TABLE( SkaterDlg, wxDialog ) +EVT_CLOSE( SkaterDlg::OnClose ) +END_EVENT_TABLE() + +SkaterDlg::SkaterDlg(wxFrame* parent_s, Project* project_s) +: skater(NULL), AbstractClusterDlg(parent_s, project_s, _("Skater Settings")) +{ + wxLogMessage("Open Skater dialog."); + CreateControls(); +} + +SkaterDlg::~SkaterDlg() +{ + wxLogMessage("On SkaterDlg::~SkaterDlg"); + if (skater) { + delete skater; + skater = NULL; + } +} + +void SkaterDlg::CreateControls() +{ + wxLogMessage("On SkaterDlg::CreateControls"); + wxScrolledWindow* scrl = new wxScrolledWindow(this, wxID_ANY, wxDefaultPosition, wxSize(800,780), wxHSCROLL|wxVSCROLL ); + scrl->SetScrollRate( 5, 5 ); + + wxPanel *panel = new wxPanel(scrl); + + wxBoxSizer *vbox = new wxBoxSizer(wxVERTICAL); + + // Input + AddSimpleInputCtrls(panel, vbox); + + // Parameters + wxFlexGridSizer* gbox = new wxFlexGridSizer(9,2,5,0); + + wxStaticText* st11 = new wxStaticText(panel, wxID_ANY, _("Number of Clusters:"), + wxDefaultPosition, wxSize(128,-1)); + m_max_region = new wxTextCtrl(panel, wxID_ANY, "5", wxDefaultPosition, wxSize(200,-1)); + gbox->Add(st11, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT | wxLEFT, 10); + gbox->Add(m_max_region, 1, wxEXPAND); + + // Weights Control + wxStaticText* st16 = new wxStaticText(panel, wxID_ANY, _("Weights:"), wxDefaultPosition, wxSize(128,-1)); + combo_weights = new wxChoice(panel, wxID_ANY, wxDefaultPosition, wxSize(200,-1)); + gbox->Add(st16, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT | wxLEFT, 10); + gbox->Add(combo_weights, 1, wxEXPAND); + + // Minimum Bound Control + AddMinBound(panel, gbox); + + // Min regions + st_minregions = new wxStaticText(panel, wxID_ANY, _("Min Region Size:"), wxDefaultPosition, wxSize(128,-1)); + txt_minregions = new wxTextCtrl(panel, wxID_ANY, _(""), wxDefaultPosition, wxSize(200,-1)); + txt_minregions->SetValidator(wxTextValidator(wxFILTER_NUMERIC)); + gbox->Add(st_minregions, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT | wxLEFT, 10); + gbox->Add(txt_minregions, 1, wxEXPAND); + + wxStaticText* st13 = new wxStaticText(panel, wxID_ANY, _("Distance Function:"), + wxDefaultPosition, wxSize(128,-1)); + wxString choices13[] = {"Euclidean", "Manhattan"}; + m_distance = new wxChoice(panel, wxID_ANY, wxDefaultPosition, wxSize(200,-1), 2, choices13); + m_distance->SetSelection(0); + gbox->Add(st13, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT | wxLEFT, 10); + gbox->Add(m_distance, 1, wxEXPAND); + + AddTransformation(panel, gbox); + + wxStaticText* st17 = new wxStaticText(panel, wxID_ANY, _("Use specified seed:"), + wxDefaultPosition, wxSize(128,-1)); + wxBoxSizer *hbox17 = new wxBoxSizer(wxHORIZONTAL); + chk_seed = new wxCheckBox(panel, wxID_ANY, ""); + seedButton = new wxButton(panel, wxID_OK, _("Change Seed")); + hbox17->Add(chk_seed,0, wxALIGN_CENTER_VERTICAL); + hbox17->Add(seedButton,0,wxALIGN_CENTER_VERTICAL); + seedButton->Disable(); + gbox->Add(st17, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT | wxLEFT, 10); + gbox->Add(hbox17, 1, wxEXPAND); + if (GdaConst::use_gda_user_seed) { + chk_seed->SetValue(true); + seedButton->Enable(); + } + st17->Hide(); + chk_seed->Hide(); + seedButton->Hide(); + + wxStaticBoxSizer *hbox = new wxStaticBoxSizer(wxHORIZONTAL, panel, _("Parameters:")); + hbox->Add(gbox, 1, wxEXPAND); + + // Output + wxStaticText* st3 = new wxStaticText (panel, wxID_ANY, _("Save Cluster in Field:"), + wxDefaultPosition, wxDefaultSize); + m_textbox = new wxTextCtrl(panel, wxID_ANY, "CL", wxDefaultPosition, wxSize(158,-1)); + wxStaticBoxSizer *hbox1 = new wxStaticBoxSizer(wxHORIZONTAL, panel, _("Output:")); + //wxBoxSizer *hbox1 = new wxBoxSizer(wxHORIZONTAL); + hbox1->Add(st3, 0, wxALIGN_CENTER_VERTICAL); + hbox1->Add(m_textbox, 1, wxALIGN_CENTER_VERTICAL | wxRIGHT, 10); + + // Buttons + wxButton *okButton = new wxButton(panel, wxID_OK, _("Run"), wxDefaultPosition, + wxSize(70, 30)); + saveButton = new wxButton(panel, wxID_OK, _("Save Spanning Tree"), wxDefaultPosition, + wxSize(140, 30)); + wxButton *closeButton = new wxButton(panel, wxID_EXIT, _("Close"), + wxDefaultPosition, wxSize(70, 30)); + wxBoxSizer *hbox2 = new wxBoxSizer(wxHORIZONTAL); + hbox2->Add(okButton, 0, wxALIGN_CENTER | wxALL, 5); + hbox2->Add(saveButton, 0, wxALIGN_CENTER | wxALL, 5); + hbox2->Add(closeButton, 0, wxALIGN_CENTER | wxALL, 5); + saveButton->Disable(); + + // Container + //vbox->Add(hbox0, 1, wxEXPAND | wxALL, 10); + vbox->Add(hbox, 0, wxALIGN_CENTER | wxALL, 10); + vbox->Add(hbox1, 0, wxEXPAND | wxTOP | wxLEFT | wxRIGHT, 10); + vbox->Add(hbox2, 0, wxALIGN_CENTER | wxALL, 10); + + // Summary control + wxBoxSizer *vbox1 = new wxBoxSizer(wxVERTICAL); + wxNotebook* notebook = AddSimpleReportCtrls(panel); + vbox1->Add(notebook, 1, wxEXPAND|wxALL,20); + + wxBoxSizer *container = new wxBoxSizer(wxHORIZONTAL); + container->Add(vbox); + container->Add(vbox1, 1, wxEXPAND | wxALL); + + panel->SetSizer(container); + + wxBoxSizer* panelSizer = new wxBoxSizer(wxVERTICAL); + panelSizer->Add(panel, 1, wxEXPAND|wxALL, 0); + + scrl->SetSizer(panelSizer); + + + wxBoxSizer* sizerAll = new wxBoxSizer(wxVERTICAL); + sizerAll->Add(scrl, 1, wxEXPAND|wxALL, 0); + SetSizer(sizerAll); + SetAutoLayout(true); + sizerAll->Fit(this); + + + Centre(); + + // Content + InitVariableCombobox(combo_var); + + // init weights + vector weights_ids; + WeightsManInterface* w_man_int = project->GetWManInt(); + w_man_int->GetIds(weights_ids); + + size_t sel_pos=0; + for (size_t i=0; iAppend(w_man_int->GetShortDispName(weights_ids[i])); + if (w_man_int->GetDefault() == weights_ids[i]) + sel_pos = i; + } + if (weights_ids.size() > 0) combo_weights->SetSelection(sel_pos); + + // Events + okButton->Bind(wxEVT_BUTTON, &SkaterDlg::OnOK, this); + closeButton->Bind(wxEVT_BUTTON, &SkaterDlg::OnClickClose, this); + saveButton->Bind(wxEVT_BUTTON, &SkaterDlg::OnSaveTree, this); + chk_seed->Bind(wxEVT_CHECKBOX, &SkaterDlg::OnSeedCheck, this); + seedButton->Bind(wxEVT_BUTTON, &SkaterDlg::OnChangeSeed, this); + +} + +void SkaterDlg::OnSaveTree(wxCommandEvent& event ) +{ + if (skater) { + wxString filter = "GWT|*.gwt"; + wxFileDialog dialog(NULL, _("Save Spanning Tree to a Weights File"), wxEmptyString, + wxEmptyString, filter, + wxFD_SAVE | wxFD_OVERWRITE_PROMPT); + if (dialog.ShowModal() != wxID_OK) { + return; + } + wxFileName fname = wxFileName(dialog.GetPath()); + wxString new_main_dir = fname.GetPathWithSep(); + wxString new_main_name = fname.GetName(); + wxString new_txt = new_main_dir + new_main_name+".gwt"; + wxTextFile file(new_txt); + file.Create(new_txt); + file.Open(new_txt); + file.Clear(); + + wxString header; + header << "0 " << project->GetNumRecords() << " " << project->GetProjectTitle(); + file.AddLine(header); + + for (int i=0; iordered_edges.size(); i++) { + wxString line; + line << skater->ordered_edges[i]->orig->id+1<< " " << skater->ordered_edges[i]->dest->id +1<< " " << skater->ordered_edges[i]->length ; + file.AddLine(line); + } + file.Write(); + file.Close(); + + // Load the weights file into Weights Manager + WeightsManInterface* w_man_int = project->GetWManInt(); + WeightUtils::LoadGwtInMan(w_man_int, new_txt, table_int); + } +} + +void SkaterDlg::OnCheckMinBound(wxCommandEvent& event) +{ + wxLogMessage("On SkaterDlg::OnLISACheck"); + AbstractClusterDlg::OnCheckMinBound(event); + + if (chk_floor->IsChecked()) { + st_minregions->Disable(); + txt_minregions->Disable(); + } else { + st_minregions->Enable(); + txt_minregions->Enable(); + } +} + +void SkaterDlg::OnSeedCheck(wxCommandEvent& event) +{ + wxLogMessage("On SkaterDlg::OnSeedCheck"); + bool use_user_seed = chk_seed->GetValue(); + + if (use_user_seed) { + seedButton->Enable(); + if (GdaConst::use_gda_user_seed == false && GdaConst::gda_user_seed == 0) { + OnChangeSeed(event); + return; + } + GdaConst::use_gda_user_seed = true; + + OGRDataAdapter& ogr_adapt = OGRDataAdapter::GetInstance(); + ogr_adapt.AddEntry("use_gda_user_seed", "1"); + } else { + seedButton->Disable(); + } +} + +void SkaterDlg::OnChangeSeed(wxCommandEvent& event) +{ + wxLogMessage("On SkaterDlg::OnChangeSeed"); + // prompt user to enter user seed (used globally) + wxString m = _("Enter a seed value for random number generator:"); + + long long unsigned int val; + wxString dlg_val; + wxString cur_val; + cur_val << GdaConst::gda_user_seed; + + wxTextEntryDialog dlg(NULL, m, _("Enter a seed value"), cur_val); + if (dlg.ShowModal() != wxID_OK) return; + dlg_val = dlg.GetValue(); + dlg_val.Trim(true); + dlg_val.Trim(false); + if (dlg_val.IsEmpty()) return; + if (dlg_val.ToULongLong(&val)) { + uint64_t new_seed_val = val; + GdaConst::gda_user_seed = new_seed_val; + GdaConst::use_gda_user_seed = true; + + OGRDataAdapter& ogr_adapt = OGRDataAdapter::GetInstance(); + wxString str_gda_user_seed; + str_gda_user_seed << GdaConst::gda_user_seed; + ogr_adapt.AddEntry("gda_user_seed", str_gda_user_seed.ToStdString()); + ogr_adapt.AddEntry("use_gda_user_seed", "1"); + } else { + wxString m = _("\"%s\" is not a valid seed. Seed unchanged."); + m = wxString::Format(m, dlg_val); + wxMessageDialog dlg(NULL, m, _("Error"), wxOK | wxICON_ERROR); + dlg.ShowModal(); + GdaConst::use_gda_user_seed = false; + OGRDataAdapter& ogr_adapt = OGRDataAdapter::GetInstance(); + ogr_adapt.AddEntry("use_gda_user_seed", "0"); + } +} + +void SkaterDlg::InitVariableCombobox(wxListBox* var_box) +{ + wxLogMessage("On SkaterDlg::InitVariableCombobox"); + wxArrayString items; + + int cnt_floor = 0; + std::vector col_id_map; + table_int->FillNumericColIdMap(col_id_map); + for (int i=0, iend=col_id_map.size(); iGetColName(id); + GdaConst::FieldType ftype = table_int->GetColType(id); + if (table_int->IsColTimeVariant(id)) { + for (int t=0; tGetColTimeSteps(id); t++) { + wxString nm = name; + nm << " (" << table_int->GetTimeString(t) << ")"; + name_to_nm[nm] = name; + name_to_tm_id[nm] = t; + items.Add(nm); + combo_floor->Insert(nm, cnt_floor++); + } + } else { + name_to_nm[name] = name; + name_to_tm_id[name] = 0; + items.Add(name); + combo_floor->Insert(name, cnt_floor++); + } + } + + if (!items.IsEmpty()) + var_box->InsertItems(items,0); + + combo_floor->SetSelection(-1); + txt_floor->SetValue(""); +} + +void SkaterDlg::OnClickClose(wxCommandEvent& event ) +{ + wxLogMessage("OnClickClose SkaterDlg."); + + event.Skip(); + EndDialog(wxID_CANCEL); + Destroy(); +} + +void SkaterDlg::OnClose(wxCloseEvent& ev) +{ + wxLogMessage("Close SkaterDlg"); + // Note: it seems that if we don't explictly capture the close event + // and call Destory, then the destructor is not called. + Destroy(); +} + +wxString SkaterDlg::_printConfiguration() +{ + wxString txt; + + txt << "Number of clusters:\t" << m_max_region->GetValue() << "\n"; + + txt << "Weights:\t" << combo_weights->GetString(combo_weights->GetSelection()) << "\n"; + + if (chk_floor && chk_floor->IsChecked()) { + int idx = combo_floor->GetSelection(); + wxString nm = name_to_nm[combo_floor->GetString(idx)]; + txt << "Minimum bound:\t" << txt_floor->GetValue() << "(" << nm << ")" << "\n"; + } else { + txt << "Minimum region size:\t" << txt_minregions->GetValue() << "\n"; + } + + txt << "Distance function:\t" << m_distance->GetString(m_distance->GetSelection()) << "\n"; + + txt << "Transformation:\t" << combo_tranform->GetString(combo_tranform->GetSelection()) << "\n"; + + return txt; +} + +void SkaterDlg::OnOK(wxCommandEvent& event ) +{ + wxLogMessage("Click SkaterDlg::OnOK"); + + if (GdaConst::use_gda_user_seed) { + setrandomstate(GdaConst::gda_user_seed); + resetrandom(); + } else { + setrandomstate(-1); + resetrandom(); + } + + // Get input data + int transform = combo_tranform->GetSelection(); + bool success = GetInputData(transform, 1); + if (!success) { + return; + } + + wxString str_initial = m_max_region->GetValue(); + if (str_initial.IsEmpty()) { + wxString err_msg = _("Please enter number of regions"); + wxMessageDialog dlg(NULL, err_msg, _("Error"), wxOK | wxICON_ERROR); + dlg.ShowModal(); + return; + } + + wxString field_name = m_textbox->GetValue(); + if (field_name.IsEmpty()) { + wxString err_msg = _("Please enter a field name for saving clustering results."); + wxMessageDialog dlg(NULL, err_msg, _("Error"), wxOK | wxICON_ERROR); + dlg.ShowModal(); + return; + } + + // Get Distance Selection + int transpose = 0; // row wise + char dist = 'e'; // euclidean + int dist_sel = m_distance->GetSelection(); + char dist_choices[] = {'e','b'}; + dist = dist_choices[dist_sel]; + + // Weights selection + vector weights_ids; + WeightsManInterface* w_man_int = project->GetWManInt(); + w_man_int->GetIds(weights_ids); + int sel = combo_weights->GetSelection(); + if (sel < 0) sel = 0; + if (sel >= weights_ids.size()) sel = weights_ids.size()-1; + boost::uuids::uuid w_id = weights_ids[sel]; + GalWeight* gw = w_man_int->GetGal(w_id); + if (gw == NULL) { + wxMessageDialog dlg (this, _("Invalid Weights Information:\n\n The selected weights file is not valid.\n Please choose another weights file, or use Tools > Weights > Weights Manager\n to define a valid weights file."), _("Warning"), wxOK | wxICON_WARNING); + dlg.ShowModal(); + return; + } + + // Check connectivity + if (!CheckConnectivity(gw)) { + wxString msg = _("The connectivity of selected spatial weights is incomplete, please adjust the spatial weights."); + wxMessageDialog dlg(this, msg, _("Warning"), wxOK | wxICON_WARNING ); + dlg.ShowModal(); + } + + // Get Bounds + bool check_floor = false; + double min_bound = GetMinBound(); + if (chk_floor->IsChecked()) { + wxString str_floor = txt_floor->GetValue(); + if (str_floor.IsEmpty()) { + wxString err_msg = _("Please enter minimum bound value"); + wxMessageDialog dlg(NULL, err_msg, _("Error"), wxOK | wxICON_ERROR); + dlg.ShowModal(); + return; + } + check_floor = true; + } + + double* bound_vals = GetBoundVals(); + /* + if (bound_vals == NULL) { + wxString str_min_regions = txt_minregions->GetValue(); + long val_min_regions; + if (str_min_regions.ToLong(&val_min_regions)) { + min_bound = val_min_regions; + check_floor = true; + } + bound_vals = new double[rows]; + for (int i=0; iGetValue()) rnd_seed = GdaConst::gda_user_seed; + + // Create distance matrix using weights + /* + double** ragged_distances = distancematrix(rows, columns, input_data, mask, weight, dist, transpose); + double** distances = DataUtils::fullRaggedMatrix(ragged_distances, rows, rows); + for (int i = 1; i < rows; i++) free(ragged_distances[i]); + free(ragged_distances); + */ + double** distances = new double*[rows]; + for (int i=0; i, bool> access_dict; + for (int i=0; igal[i].Size(); j++) { + int nbr = gw->gal[i][j]; + pair i_nbr(i, nbr); + pair nbr_i(nbr, i); + if (access_dict.find(i_nbr) != access_dict.end() || + access_dict.find(nbr_i) != access_dict.end() ) + { + continue; + } + { + double dis = 0; + for (int k=0; kgal, bound_vals, min_bound); + + if (skater==NULL) { + delete[] bound_vals; + bound_vals = NULL; + return; + } + + skater->Partitioning(n_regions); + + vector > cluster_ids = skater->GetRegions(); + + int ncluster = cluster_ids.size(); + + if (ncluster < n_regions) { + // show message dialog to user + wxString warn_str = _("The number of identified clusters is less than "); + warn_str << n_regions; + wxMessageDialog dlg(NULL, warn_str, _("Warning"), wxOK | wxICON_WARNING); + dlg.ShowModal(); + } + vector clusters(rows, 0); + vector clusters_undef(rows, false); + + + // sort result + std::sort(cluster_ids.begin(), cluster_ids.end(), GenUtils::less_vectors); + for (int i=0; i < ncluster; i++) { + int c = i + 1; + for (int j=0; jFindColId(field_name); + if ( col == wxNOT_FOUND) { + int col_insert_pos = table_int->GetNumberCols(); + int time_steps = 1; + int m_length_val = GdaConst::default_dbf_long_len; + int m_decimals_val = 0; + + col = table_int->InsertCol(GdaConst::long64_type, field_name, col_insert_pos, time_steps, m_length_val, m_decimals_val); + } else { + // detect if column is integer field, if not raise a warning + if (table_int->GetColType(col) != GdaConst::long64_type ) { + wxString msg = _("This field name already exists (non-integer type). Please input a unique name."); + wxMessageDialog dlg(this, msg, _("Warning"), wxOK | wxICON_WARNING ); + dlg.ShowModal(); + return; + } + } + + if (col > 0) { + table_int->SetColData(col, time, clusters); + table_int->SetColUndefined(col, time, clusters_undef); + } + + // show a cluster map + if (project->IsTableOnlyProject()) { + return; + } + std::vector new_var_info; + std::vector new_col_ids; + new_col_ids.resize(1); + new_var_info.resize(1); + new_col_ids[0] = col; + new_var_info[0].time = 0; + // Set Primary GdaVarTools::VarInfo attributes + new_var_info[0].name = field_name; + new_var_info[0].is_time_variant = table_int->IsColTimeVariant(col); + table_int->GetMinMaxVals(new_col_ids[0], new_var_info[0].min, new_var_info[0].max); + new_var_info[0].sync_with_global_time = new_var_info[0].is_time_variant; + new_var_info[0].fixed_scale = true; + + + MapFrame* nf = new MapFrame(parent, project, + new_var_info, new_col_ids, + CatClassification::unique_values, + MapCanvas::no_smoothing, 4, + boost::uuids::nil_uuid(), + wxDefaultPosition, + GdaConst::map_default_size); + wxString ttl; + ttl << "Skater " << _("Cluster Map ") << "("; + ttl << ncluster; + ttl << " clusters)"; + nf->SetTitle(ttl); + + if (n_island>0) { + nf->SetLegendLabel(0, _("Not Clustered")); + } + + saveButton->Enable(); +} diff --git a/DialogTools/SkaterDlg.h b/DialogTools/SkaterDlg.h new file mode 100644 index 000000000..279299b0e --- /dev/null +++ b/DialogTools/SkaterDlg.h @@ -0,0 +1,79 @@ +/** + * GeoDa TM, Copyright (C) 2011-2015 by Luc Anselin - all rights reserved + * + * This file is part of GeoDa. + * + * GeoDa is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * GeoDa is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#ifndef __GEODA_CENTER_SKATER_DLG_H___ +#define __GEODA_CENTER_SKATER_DLG_H___ + +#include +#include +#include +#include + + +#include "../FramesManager.h" +#include "../VarTools.h" +#include "AbstractClusterDlg.h" +#include "../Algorithms/redcap.h" + +class Project; +class TableInterface; + +class SkaterDlg : public AbstractClusterDlg +{ +public: + SkaterDlg(wxFrame *parent, Project* project); + virtual ~SkaterDlg(); + + void CreateControls(); + + void OnOK( wxCommandEvent& event ); + void OnClickClose( wxCommandEvent& event ); + void OnClose(wxCloseEvent& ev); + void OnSaveTree(wxCommandEvent& event ); + void OnSeedCheck(wxCommandEvent& event); + void OnChangeSeed(wxCommandEvent& event); + virtual void OnCheckMinBound(wxCommandEvent& event); + + void InitVariableCombobox(wxListBox* var_box); + + virtual wxString _printConfiguration(); + +private: + wxCheckBox* chk_seed; + wxCheckBox* chk_lisa; + + wxChoice* combo_weights; + wxChoice* combo_lisa; + + wxChoice* m_distance; + wxTextCtrl* m_textbox; + wxTextCtrl* m_max_region; + + wxStaticText* st_minregions; + wxTextCtrl* txt_minregions; + + wxButton* seedButton; + wxButton* saveButton; + + SpanningTreeClustering::Skater* skater; + + DECLARE_EVENT_TABLE() +}; + +#endif diff --git a/DialogTools/SpatialJoinDlg.cpp b/DialogTools/SpatialJoinDlg.cpp new file mode 100644 index 000000000..9ca5d96ed --- /dev/null +++ b/DialogTools/SpatialJoinDlg.cpp @@ -0,0 +1,348 @@ +// +// SpatialJoinDlg.cpp +// GeoDa +// +// Created by Xun Li on 9/4/18. +// +#include +#include +#include +#include +#include +#include + +#include "../Project.h" +#include "../MapLayerStateObserver.h" +#include "../Explore/MapLayerTree.hpp" +#include "SaveToTableDlg.h" +#include "ProjectInfoDlg.h" +#include "ConnectDatasourceDlg.h" +#include "SpatialJoinDlg.h" + +using namespace std; + +SpatialJoinWorker::SpatialJoinWorker(BackgroundMapLayer* _ml, Project* _project) +{ + ml = _ml; + project = _project; + spatial_counts.resize(project->GetNumRecords()); + + // always use points to create a rtree, since in normal case + // the number of points are larger than the number of polygons +} + +SpatialJoinWorker::~SpatialJoinWorker() +{ + +} + +vector SpatialJoinWorker::GetResults() +{ + return spatial_counts; +} + +void SpatialJoinWorker::Run() +{ + int initial = num_polygons; + int nCPUs = boost::thread::hardware_concurrency();; + int quotient = initial / nCPUs; + int remainder = initial % nCPUs; + int tot_threads = (quotient > 0) ? nCPUs : remainder; + + boost::thread_group threadPool; + for (int i=0; iGetNumRecords(); + + // using selected layer (points) to create rtree + int n = ml->shapes.size(); + double x, y; + for (int i=0; ishapes[i]->center_o.x; + y = ml->shapes[i]->center_o.y; + rtree.insert(std::make_pair(pt_2d(x,y), i)); + } +} + +void CountPointsInPolygon::sub_run(int start, int end) +{ + Shapefile::Main& main_data = project->main_data; + OGRLayerProxy* ogr_layer = project->layer_proxy; + Shapefile::PolygonContents* pc; + for (int i=start; i<=end; i++) { + pc = (Shapefile::PolygonContents*)main_data.records[i].contents_p; + // create a box, tl, br + box_2d b(pt_2d(pc->box[0], pc->box[1]), + pt_2d(pc->box[2], pc->box[3])); + // query points in this box + std::vector q; + rtree.query(bgi::within(b), std::back_inserter(q)); + OGRGeometry* ogr_poly = ogr_layer->GetGeometry(i); + for (int j=0; j(); + double y = v.first.get<1>(); + OGRPoint ogr_pt(x, y); + if (ogr_pt.Within(ogr_poly)) { + spatial_counts[i] += 1; + } + } + } +} +AssignPolygonToPoint::AssignPolygonToPoint(BackgroundMapLayer* _ml, Project* _project, vector& _poly_ids) +: SpatialJoinWorker(_ml, _project) +{ + poly_ids = _poly_ids; + num_polygons = ml->GetNumRecords(); + // using current map(points) to create rtree + Shapefile::Main& main_data = project->main_data; + Shapefile::PointContents* pc; + int n = project->GetNumRecords(); + double x, y; + for (int i=0; ix; + y = pc->y; + rtree.insert(std::make_pair(pt_2d(x,y), i)); + spatial_counts[i] = -1; + } +} + +void AssignPolygonToPoint::sub_run(int start, int end) +{ + // for every polygon in sub-layer + for (int i=start; i<=end; i++) { + OGRGeometry* ogr_poly = ml->geoms[i]; + // create a box, tl, br + OGREnvelope box; + ogr_poly->getEnvelope(&box); + + box_2d b(pt_2d(box.MinX, box.MinY), pt_2d(box.MaxX, box.MaxY)); + // query points in this box + std::vector q; + rtree.query(bgi::within(b), std::back_inserter(q)); + for (int j=0; j(); + double y = v.first.get<1>(); + OGRPoint ogr_pt(x, y); + if (ogr_pt.Within(ogr_poly)) { + spatial_counts[pt_idx] = poly_ids[i]; + } + } + } +} + + +SpatialJoinDlg::SpatialJoinDlg(wxWindow* parent, Project* _project) +: wxDialog(parent, -1, "Spatial Join", wxDefaultPosition, wxSize(350, 250)) +{ + project = _project; + panel = new wxPanel(this, -1); + + wxString info = _("Please select a map layer to apply spatial join to current map (%s):"); + info = wxString::Format(info, project->GetProjectTitle()); + wxStaticText* st = new wxStaticText(panel, -1, info); + + map_list = new wxChoice(panel, wxID_ANY, wxDefaultPosition, wxSize(160,-1)); + field_st = new wxStaticText(panel, -1, "Select ID Variable (Optional)"); + field_list = new wxChoice(panel, wxID_ANY, wxDefaultPosition, wxSize(100,-1)); + wxBoxSizer* mbox = new wxBoxSizer(wxHORIZONTAL); + mbox->Add(map_list, 0, wxALIGN_CENTER | wxALL, 5); + mbox->Add(field_st, 0, wxALIGN_CENTER | wxALL, 5); + mbox->Add(field_list, 0, wxALIGN_CENTER | wxALL, 5); + + cbox = new wxBoxSizer(wxVERTICAL); + cbox->Add(st, 0, wxALIGN_CENTER | wxALL, 15); + cbox->Add(mbox, 0, wxALIGN_CENTER | wxALL, 10); + panel->SetSizerAndFit(cbox); + + wxButton* add_btn = new wxButton(this, XRCID("IDC_SPATIALJOIN_ADD_LAYER"), _("Add Map Layer"), wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT); + wxButton* ok_btn = new wxButton(this, wxID_ANY, _("OK"), wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT); + wxButton* cancel_btn = new wxButton(this, wxID_CANCEL, _("Close"), wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT); + + wxBoxSizer* hbox = new wxBoxSizer(wxHORIZONTAL); + hbox->Add(add_btn, 0, wxALIGN_CENTER | wxALL, 5); + hbox->Add(ok_btn, 0, wxALIGN_CENTER | wxALL, 5); + hbox->Add(cancel_btn, 0, wxALIGN_CENTER | wxALL, 5); + + vbox = new wxBoxSizer(wxVERTICAL); + vbox->Add(panel, 1, wxALL, 15); + vbox->Add(hbox, 0, wxALIGN_CENTER | wxALL, 10); + + SetSizer(vbox); + vbox->Fit(this); + + Center(); + + map_list->Bind(wxEVT_CHOICE, &SpatialJoinDlg::OnLayerSelect, this); + add_btn->Bind(wxEVT_BUTTON, &SpatialJoinDlg::OnAddMapLayer, this); + ok_btn->Bind(wxEVT_BUTTON, &SpatialJoinDlg::OnOK, this); + + InitMapList(); + field_st->Disable(); + field_list->Disable(); +} + +void SpatialJoinDlg::InitMapList() +{ + map_list->Clear(); + map::iterator it; + + for (it=project->bg_maps.begin(); it!=project->bg_maps.end(); it++) { + wxString name = it->first; + map_list->Append(name); + } + for (it=project->fg_maps.begin(); it!=project->fg_maps.end(); it++) { + wxString name = it->first; + map_list->Append(name); + } + if (map_list->GetCount() > 0) { + // check the first item in list + wxString name = map_list->GetString(0); + UpdateFieldList(name); + } +} + +void SpatialJoinDlg::UpdateFieldList(wxString name) +{ + BackgroundMapLayer* ml = project->GetMapLayer(name); + if (ml) { + if (Shapefile::POLYGON == ml->GetShapeType() && + project->IsPointTypeData()) { + // assign polygon to point + field_list->Clear(); + vector field_names = ml->GetIntegerFieldNames(); + field_list->Append(""); + for (int i=0; iAppend(field_names[i]); + } + field_list->Enable(); + field_st->Enable(); + + } else { + field_list->Clear(); + field_list->Disable(); + field_st->Disable(); + } + } +} + +void SpatialJoinDlg::OnAddMapLayer(wxCommandEvent& e) +{ + ConnectDatasourceDlg connect_dlg(this, wxDefaultPosition, wxDefaultSize); + if (connect_dlg.ShowModal() != wxID_OK) { + return; + } + wxString proj_title = connect_dlg.GetProjectTitle(); + wxString layer_name = connect_dlg.GetLayerName(); + IDataSource* datasource = connect_dlg.GetDataSource(); + wxString datasource_name = datasource->GetOGRConnectStr(); + GdaConst::DataSourceType ds_type = datasource->GetType(); + + BackgroundMapLayer* map_layer = project->AddMapLayer(datasource_name, ds_type, layer_name); + if (map_layer == NULL) { + wxMessageDialog dlg (this, _("GeoDa could not load this layer. \nPlease check if the datasource is valid and not table only."), _("Load Layer Failed."), wxOK | wxICON_ERROR); + dlg.ShowModal(); + } else { + map_list->Append(layer_name); + UpdateFieldList(layer_name); + MapLayerState* ml_state = project->GetMapLayerState(); + ml_state->notifyObservers(); + } +} + +void SpatialJoinDlg::OnLayerSelect(wxCommandEvent& e) +{ + int layer_idx = map_list->GetSelection(); + if ( layer_idx < 0) { + return; + } + wxString layer_name = map_list->GetString(layer_idx); + UpdateFieldList(layer_name); +} + +void SpatialJoinDlg::OnOK(wxCommandEvent& e) +{ + int layer_idx = map_list->GetSelection(); + if ( layer_idx < 0) { + return; + } + wxString layer_name = map_list->GetString(layer_idx); + BackgroundMapLayer* ml = NULL; + ml = project->GetMapLayer(layer_name); + + if (ml) { + int n = ml->GetNumRecords(); + if (project->IsPointTypeData() && + ml->GetShapeType() == Shapefile::POINT_TYP) { + wxMessageDialog dlg (this, _("Spatial Join can not be applied on two points layers. Please select another layer."), _("Warning"), wxOK | wxICON_INFORMATION); + dlg.ShowModal(); + return; + } + wxString label = "Spatial Count"; + wxString field_name = "SC"; + + SpatialJoinWorker* sj; + if (project->IsPointTypeData()) { + vector poly_ids; + for (int i=0; iGetSelection(); + if (field_idx > 0) { + wxString field_name = field_list->GetString(field_idx); + bool success = ml->GetIntegerColumnData(field_name, poly_ids); + if ( !success || poly_ids.size() != n) { + wxMessageDialog dlg (this, _("Select field is not integer type. Default record order will be used instead."), _("Warning"), wxOK | wxICON_INFORMATION); + dlg.ShowModal(); + poly_ids.clear(); + } + } + sj = new AssignPolygonToPoint(ml, project, poly_ids); + label = "Spatial Assign"; + field_name = "SA"; + } else { + sj = new CountPointsInPolygon(ml, project); + } + sj->Run(); + + wxString dlg_title = _("Save Results: ") + label; + vector spatial_counts = sj->GetResults(); + // save results + int new_col = 1; + std::vector new_data(new_col); + vector undefs(project->GetNumRecords(), false); + new_data[0].l_val = &spatial_counts; + new_data[0].label = label; + new_data[0].field_default = field_name; + new_data[0].type = GdaConst::long64_type; + new_data[0].undefined = &undefs; + SaveToTableDlg dlg(project, this, new_data, dlg_title, + wxDefaultPosition, wxSize(400,400)); + dlg.ShowModal(); + + delete sj; + } +} + diff --git a/DialogTools/SpatialJoinDlg.h b/DialogTools/SpatialJoinDlg.h new file mode 100644 index 000000000..0e406ae65 --- /dev/null +++ b/DialogTools/SpatialJoinDlg.h @@ -0,0 +1,78 @@ +// +// SpatialJoinDlg.hpp +// GeoDa +// +// Created by Xun Li on 9/4/18. +// + +#ifndef SpatialJoinDlg_hpp +#define SpatialJoinDlg_hpp + +#include +#include +#include "../SpatialIndTypes.h" + +class Project; +class BackgroundMapLayer; +class MapLayerState; +class MapLayerStateObserver; + +class SpatialJoinWorker +{ +protected: + rtree_pt_2d_t rtree; + vector spatial_counts; + Project* project; + BackgroundMapLayer* ml; + int num_polygons; + +public: + SpatialJoinWorker(BackgroundMapLayer* ml, Project* project); + virtual ~SpatialJoinWorker(); + + void Run(); + void points_in_polygons(int start, int end); + void polygon_at_point(int start, int end); + vector GetResults(); + + virtual void sub_run(int start, int end) = 0; +}; + +class CountPointsInPolygon : public SpatialJoinWorker +{ +public: + CountPointsInPolygon(BackgroundMapLayer* ml, Project* project); + virtual void sub_run(int start, int end); +}; + +class AssignPolygonToPoint : public SpatialJoinWorker +{ + vector poly_ids; +public: + AssignPolygonToPoint(BackgroundMapLayer* ml, Project* project, vector& poly_ids); + virtual void sub_run(int start, int end); +}; + +class SpatialJoinDlg : public wxDialog +{ + Project* project; + wxChoice* map_list; + wxChoice* field_list; + wxStaticText* field_st; + wxBoxSizer* vbox; + wxBoxSizer* cbox; + wxPanel* panel; + + void UpdateFieldList(wxString name); + +public: + SpatialJoinDlg(wxWindow* parent, Project* project); + + void OnOK(wxCommandEvent& e); + void OnAddMapLayer(wxCommandEvent& e); + void OnLayerSelect(wxCommandEvent& e); + + void InitMapList(); +}; + +#endif /* SpatialJoinDlg_h */ diff --git a/DialogTools/SpectralClusteringDlg.cpp b/DialogTools/SpectralClusteringDlg.cpp new file mode 100644 index 000000000..414a9a4c2 --- /dev/null +++ b/DialogTools/SpectralClusteringDlg.cpp @@ -0,0 +1,694 @@ +/** + * GeoDa TM, Copyright (C) 2011-2015 by Luc Anselin - all rights reserved + * + * This file is part of GeoDa. + * + * GeoDa is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * GeoDa is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../VarCalc/WeightsManInterface.h" +#include "../ShapeOperations/OGRDataAdapter.h" +#include "../Explore/MapNewView.h" +#include "../Project.h" +#include "../Algorithms/cluster.h" +#include "../Algorithms/spectral.h" +#include "../Algorithms/DataUtils.h" + +#include "../GeneralWxUtils.h" +#include "../GenUtils.h" +#include "SaveToTableDlg.h" +#include "SpectralClusteringDlg.h" + + +BEGIN_EVENT_TABLE( SpectralClusteringDlg, wxDialog ) +EVT_CLOSE( SpectralClusteringDlg::OnClose ) +END_EVENT_TABLE() + +SpectralClusteringDlg::SpectralClusteringDlg(wxFrame* parent_s, Project* project_s) +: AbstractClusterDlg(parent_s, project_s, _("Spectral Clustering Settings")) +{ + wxLogMessage("Open SpectralClusteringDlg."); + + parent = parent_s; + project = project_s; + + bool init_success = Init(); + + if (init_success == false) { + EndDialog(wxID_CANCEL); + } else { + CreateControls(); + } +} + +SpectralClusteringDlg::~SpectralClusteringDlg() +{ +} + +bool SpectralClusteringDlg::Init() +{ + if (project == NULL) + return false; + + table_int = project->GetTableInt(); + if (table_int == NULL) + return false; + + table_int->GetTimeStrings(tm_strs); + + return true; +} + +void SpectralClusteringDlg::CreateControls() +{ + wxScrolledWindow* scrl = new wxScrolledWindow(this, wxID_ANY, wxDefaultPosition, wxSize(820,880), wxHSCROLL|wxVSCROLL ); + scrl->SetScrollRate( 5, 5 ); + + wxPanel *panel = new wxPanel(scrl); + + wxBoxSizer *vbox = new wxBoxSizer(wxVERTICAL); + + // Input + AddInputCtrls(panel, vbox); + + // Parameters + wxFlexGridSizer* gbox = new wxFlexGridSizer(14,2,5,0); + + // NumberOfCluster Control + wxStaticText* st1 = new wxStaticText(panel, wxID_ANY, _("Number of Clusters:"), wxDefaultPosition, wxSize(128,-1)); + combo_n = new wxChoice(panel, wxID_ANY); + int max_n_clusters = num_obs < 60 ? num_obs : 60; + for (int i=2; iAppend(wxString::Format("%d", i)); + combo_n->SetSelection(3); + gbox->Add(st1, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT | wxLEFT, 10); + gbox->Add(combo_n, 1, wxEXPAND); + + // Spectral controls: KNN + lbl_knn = new wxStaticText(panel, wxID_ANY, _("Affinity with K-NN:"), wxDefaultPosition, wxSize(130,-1)); + wxBoxSizer* hbox19 = new wxBoxSizer(wxHORIZONTAL); + chk_knn = new wxCheckBox(panel, wxID_ANY, ""); + lbl_neighbors = new wxStaticText(panel, wxID_ANY, _("# Neighors:")); + m_knn = new wxTextCtrl(panel, wxID_ANY, "4", wxDefaultPosition, wxSize(40,-1)); + hbox19->Add(chk_knn); + hbox19->Add(lbl_neighbors); + hbox19->Add(m_knn); + gbox->Add(lbl_knn, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT | wxLEFT, 10); + gbox->Add(hbox19, 1, wxEXPAND); + + // Spectral Controls: Kernel + double suggest_sigma = sqrt(1.0/(double)num_obs); + wxString str_sigma; + str_sigma << suggest_sigma; + lbl_kernel = new wxStaticText(panel, wxID_ANY, _("Affinity with Kernel:"), + wxDefaultPosition, wxSize(130,-1)); + wxBoxSizer* hbox18 = new wxBoxSizer(wxHORIZONTAL); + chk_kernel = new wxCheckBox(panel, wxID_ANY, ""); + lbl_sigma = new wxStaticText(panel, wxID_ANY, _("(Gaussian) Sigma:")); + m_sigma = new wxTextCtrl(panel, wxID_ANY, str_sigma, wxDefaultPosition, wxSize(40,-1)); + hbox18->Add(chk_kernel); + hbox18->Add(lbl_sigma); + hbox18->Add(m_sigma); + gbox->Add(lbl_kernel, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT | wxLEFT, 10); + gbox->Add(hbox18, 1, wxEXPAND); + + // Weights (not enabled) + lbl_weights = new wxStaticText(panel, wxID_ANY, _("Use Weights:"), + wxDefaultPosition, wxSize(128,-1)); + wxBoxSizer *hbox22 = new wxBoxSizer(wxHORIZONTAL); + chk_weights = new wxCheckBox(panel, wxID_ANY, ""); + combo_weights = new wxChoice(panel, wxID_ANY); + chk_weights->SetValue(true); + hbox22->Add(chk_weights); + hbox22->Add(combo_weights); + gbox->Add(lbl_weights, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT | wxLEFT, 10); + gbox->Add(hbox22, 1, wxEXPAND); + + // power iteration option approximation + wxStaticText* st15 = new wxStaticText(panel, wxID_ANY, _("Use Power Iteration:"), wxDefaultPosition, wxSize(134,-1)); + wxBoxSizer *hbox15 = new wxBoxSizer(wxHORIZONTAL); + chk_poweriteration = new wxCheckBox(panel, wxID_ANY, ""); + lbl_poweriteration = new wxStaticText(panel, wxID_ANY, _("# Max Iteration:")); + txt_poweriteration = new wxTextCtrl(panel, wxID_ANY, "300",wxDefaultPosition, wxSize(70,-1)); + txt_poweriteration->SetValidator( wxTextValidator(wxFILTER_NUMERIC) ); + chk_poweriteration->Bind(wxEVT_CHECKBOX, &SpectralClusteringDlg::OnCheckPowerIteration, this); + if (project->GetNumRecords() < 2000) { + lbl_poweriteration->Disable(); + txt_poweriteration->Disable(); + } else { + chk_poweriteration->SetValue(true); + } + hbox15->Add(chk_poweriteration); + hbox15->Add(lbl_poweriteration); + hbox15->Add(txt_poweriteration); + gbox->Add(st15, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT | wxLEFT, 10); + gbox->Add(hbox15, 1, wxEXPAND); + + // Transformation + AddTransformation(panel, gbox); + + wxStaticText* st20 = new wxStaticText(panel, wxID_ANY, "(K-Means)", + wxDefaultPosition, wxSize(128,-1)); + wxStaticText* st21 = new wxStaticText(panel, wxID_ANY, "", + wxDefaultPosition, wxSize(0,-1)); + gbox->Add(st20, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT | wxLEFT, 10); + gbox->Add(st21, 1, wxEXPAND); + + wxStaticText* st16 = new wxStaticText(panel, wxID_ANY, _("Initialization Method:"), wxDefaultPosition, wxSize(128,-1)); + wxString choices16[] = {"KMeans++", "Random"}; + combo_method = new wxChoice(panel, wxID_ANY, wxDefaultPosition, + wxSize(160,-1), 2, choices16); + combo_method->SetSelection(0); + + gbox->Add(st16, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT | wxLEFT, 10); + gbox->Add(combo_method, 1, wxEXPAND); + + + wxStaticText* st10 = new wxStaticText(panel, wxID_ANY, _("Initialization Re-runs:"), wxDefaultPosition, wxSize(128,-1)); + wxTextCtrl *box10 = new wxTextCtrl(panel, wxID_ANY, "150", wxDefaultPosition, wxSize(160,-1)); + gbox->Add(st10, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT | wxLEFT, 10); + gbox->Add(box10, 1, wxEXPAND); + + wxStaticText* st17 = new wxStaticText(panel, wxID_ANY, _("Use specified seed:"), + wxDefaultPosition, wxSize(128,-1)); + wxBoxSizer *hbox17 = new wxBoxSizer(wxHORIZONTAL); + chk_seed = new wxCheckBox(panel, wxID_ANY, ""); + seedButton = new wxButton(panel, wxID_OK, _("Change Seed")); + + hbox17->Add(chk_seed,0, wxALIGN_CENTER_VERTICAL); + hbox17->Add(seedButton,0,wxALIGN_CENTER_VERTICAL); + seedButton->Disable(); + gbox->Add(st17, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT | wxLEFT, 10); + gbox->Add(hbox17, 1, wxEXPAND); + + if (GdaConst::use_gda_user_seed) { + chk_seed->SetValue(true); + seedButton->Enable(); + } + + wxStaticText* st11 = new wxStaticText(panel, wxID_ANY, _("Maximal Iterations:"),wxDefaultPosition, wxSize(128,-1)); + wxTextCtrl *box11 = new wxTextCtrl(panel, wxID_ANY, "300"); + gbox->Add(st11, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT | wxLEFT, 10); + gbox->Add(box11, 1, wxEXPAND); + + /* + wxStaticText* st12 = new wxStaticText(panel, wxID_ANY, _("Method:"), + wxDefaultPosition, wxSize(128,-1)); + wxString choices12[] = {"Arithmetic Mean", "Arithmetic Median"}; + wxChoice* box12 = new wxChoice(panel, wxID_ANY, wxDefaultPosition, + wxSize(160,-1), 2, choices12); + box12->SetSelection(0); + gbox->Add(st12, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT | wxLEFT, 10); + gbox->Add(box12, 1, wxEXPAND); + */ + wxStaticText* st13 = new wxStaticText(panel, wxID_ANY, _("Distance Function:"), + wxDefaultPosition, wxSize(128,-1)); + wxString choices13[] = {"Euclidean", "Manhattan"}; + wxChoice* box13 = new wxChoice(panel, wxID_ANY, wxDefaultPosition, wxSize(160,-1), 2, choices13); + box13->SetSelection(0); + gbox->Add(st13, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT | wxLEFT, 10); + gbox->Add(box13, 1, wxEXPAND); + + + wxStaticBoxSizer *hbox = new wxStaticBoxSizer(wxHORIZONTAL, panel, _("Parameters:")); + hbox->Add(gbox, 1, wxEXPAND); + + + // Output + wxStaticText* st3 = new wxStaticText (panel, wxID_ANY, _("Save Cluster in Field:"), + wxDefaultPosition, wxDefaultSize); + wxTextCtrl *box3 = new wxTextCtrl(panel, wxID_ANY, "CL", wxDefaultPosition, wxSize(158,-1)); + wxStaticBoxSizer *hbox1 = new wxStaticBoxSizer(wxHORIZONTAL, panel, _("Output:")); + hbox1->Add(st3, 0, wxALIGN_CENTER_VERTICAL); + hbox1->Add(box3, 1, wxALIGN_CENTER_VERTICAL | wxRIGHT, 10); + + + // Buttons + wxButton *okButton = new wxButton(panel, wxID_OK, _("Run"), wxDefaultPosition, + wxSize(70, 30)); + wxButton *closeButton = new wxButton(panel, wxID_EXIT, _("Close"), + wxDefaultPosition, wxSize(70, 30)); + wxBoxSizer *hbox2 = new wxBoxSizer(wxHORIZONTAL); + hbox2->Add(okButton, 1, wxALIGN_CENTER | wxALL, 5); + hbox2->Add(closeButton, 1, wxALIGN_CENTER | wxALL, 5); + + // Container + //vbox->Add(hbox0, 1, wxEXPAND | wxALL, 10); + vbox->Add(hbox, 0, wxALIGN_CENTER | wxALL, 10); + vbox->Add(hbox1, 0, wxEXPAND | wxTOP | wxLEFT | wxRIGHT, 10); + vbox->Add(hbox2, 0, wxALIGN_CENTER | wxALL, 10); + + // Summary control + wxBoxSizer *vbox1 = new wxBoxSizer(wxVERTICAL); + wxNotebook* notebook = AddSimpleReportCtrls(panel); + vbox1->Add(notebook, 1, wxEXPAND|wxALL,20); + + wxBoxSizer *container = new wxBoxSizer(wxHORIZONTAL); + container->Add(vbox); + container->Add(vbox1,1, wxEXPAND | wxALL); + + panel->SetSizer(container); + + wxBoxSizer* panelSizer = new wxBoxSizer(wxVERTICAL); + panelSizer->Add(panel, 1, wxEXPAND|wxALL, 0); + + scrl->SetSizer(panelSizer); + + wxBoxSizer* sizerAll = new wxBoxSizer(wxVERTICAL); + sizerAll->Add(scrl, 1, wxEXPAND|wxALL, 0); + SetSizer(sizerAll); + SetAutoLayout(true); + sizerAll->Fit(this); + + Centre(); + + // Content + //InitVariableCombobox(box); + + // temp solution: + chk_kernel->SetValue(false); + lbl_kernel->Disable(); + lbl_sigma->Disable(); + m_sigma->Disable(); + + + chk_knn->SetValue(true); + lbl_knn ->Enable(); + lbl_neighbors->Enable(); + m_knn->Enable(); + + chk_weights->SetValue(false); + chk_weights->Disable(); + lbl_weights->Disable(); + combo_weights->Disable(); + chk_weights->Hide(); + lbl_weights->Hide(); + combo_weights->Hide(); + + m_textbox = box3; + m_iterations = box11; + m_pass = box10; + //m_method = box12; + m_distance = box13; + + // Events + chk_kernel->Bind(wxEVT_CHECKBOX, &SpectralClusteringDlg::OnKernelCheck, this); + chk_knn->Bind(wxEVT_CHECKBOX, &SpectralClusteringDlg::OnKNNCheck, this); + chk_weights->Bind(wxEVT_CHECKBOX, &SpectralClusteringDlg::OnWeightsCheck, this); + + okButton->Bind(wxEVT_BUTTON, &SpectralClusteringDlg::OnOK, this); + closeButton->Bind(wxEVT_BUTTON, &SpectralClusteringDlg::OnClickClose, this); + chk_seed->Bind(wxEVT_CHECKBOX, &SpectralClusteringDlg::OnSeedCheck, this); + seedButton->Bind(wxEVT_BUTTON, &SpectralClusteringDlg::OnChangeSeed, this); + + m_distance->Connect(wxEVT_CHOICE, + wxCommandEventHandler(SpectralClusteringDlg::OnDistanceChoice), + NULL, this); +} + +void SpectralClusteringDlg::OnCheckPowerIteration(wxCommandEvent& event) +{ + if (chk_poweriteration->IsChecked()) { + txt_poweriteration->Enable(); + lbl_poweriteration->Enable(); + } else { + txt_poweriteration->Disable(); + lbl_poweriteration->Disable(); + } +} + +void SpectralClusteringDlg::OnWeightsCheck(wxCommandEvent& event) +{ + +} + +void SpectralClusteringDlg::OnKernelCheck(wxCommandEvent& event) +{ + bool flag = chk_kernel->IsChecked(); + chk_knn->SetValue(!flag); + lbl_neighbors->Enable(!flag); + m_knn->Enable(!flag); + + lbl_sigma->Enable(flag); + m_sigma->Enable(flag); +} + +void SpectralClusteringDlg::OnKNNCheck(wxCommandEvent& event) +{ + bool flag = chk_knn->IsChecked(); + lbl_neighbors->Enable(flag); + m_knn->Enable(flag); + + chk_kernel->SetValue(!flag); + lbl_sigma->Enable(!flag); + m_sigma->Enable(!flag); +} + +void SpectralClusteringDlg::OnSeedCheck(wxCommandEvent& event) +{ + bool use_user_seed = chk_seed->GetValue(); + + if (use_user_seed) { + seedButton->Enable(); + if (GdaConst::use_gda_user_seed == false && GdaConst::gda_user_seed == 0) { + OnChangeSeed(event); + return; + } + GdaConst::use_gda_user_seed = true; + + OGRDataAdapter& ogr_adapt = OGRDataAdapter::GetInstance(); + ogr_adapt.AddEntry("use_gda_user_seed", "1"); + } else { + seedButton->Disable(); + } +} + +void SpectralClusteringDlg::OnChangeSeed(wxCommandEvent& event) +{ + // prompt user to enter user seed (used globally) + wxString m; + m << _("Enter a seed value for random number generator:"); + + long long unsigned int val; + wxString dlg_val; + wxString cur_val; + cur_val << GdaConst::gda_user_seed; + + wxTextEntryDialog dlg(NULL, m, _("Enter a seed value"), cur_val); + if (dlg.ShowModal() != wxID_OK) return; + dlg_val = dlg.GetValue(); + dlg_val.Trim(true); + dlg_val.Trim(false); + if (dlg_val.IsEmpty()) return; + if (dlg_val.ToULongLong(&val)) { + uint64_t new_seed_val = val; + GdaConst::gda_user_seed = new_seed_val; + GdaConst::use_gda_user_seed = true; + + OGRDataAdapter& ogr_adapt = OGRDataAdapter::GetInstance(); + wxString str_gda_user_seed; + str_gda_user_seed << GdaConst::gda_user_seed; + ogr_adapt.AddEntry("gda_user_seed", str_gda_user_seed.ToStdString()); + ogr_adapt.AddEntry("use_gda_user_seed", "1"); + } else { + wxString m = _("\"%s\" is not a valid seed. Seed unchanged."); + m = wxString::Format(m, dlg_val); + wxMessageDialog dlg(NULL, m, _("Error"), wxOK | wxICON_ERROR); + dlg.ShowModal(); + GdaConst::use_gda_user_seed = false; + OGRDataAdapter& ogr_adapt = OGRDataAdapter::GetInstance(); + ogr_adapt.AddEntry("use_gda_user_seed", "0"); + } +} + +void SpectralClusteringDlg::OnDistanceChoice(wxCommandEvent& event) +{ + + if (m_distance->GetSelection() == 0) { + m_distance->SetSelection(1); + } else if (m_distance->GetSelection() == 3) { + m_distance->SetSelection(4); + } else if (m_distance->GetSelection() == 6) { + m_distance->SetSelection(7); + } else if (m_distance->GetSelection() == 9) { + m_distance->SetSelection(10); + } +} + +void SpectralClusteringDlg::InitVariableCombobox(wxListBox* var_box) +{ + wxArrayString items; + + std::vector col_id_map; + table_int->FillNumericColIdMap(col_id_map); + for (int i=0, iend=col_id_map.size(); iGetColName(id); + if (table_int->IsColTimeVariant(id)) { + for (int t=0; tGetColTimeSteps(id); t++) { + wxString nm = name; + nm << " (" << table_int->GetTimeString(t) << ")"; + name_to_nm[nm] = name; + name_to_tm_id[nm] = t; + items.Add(nm); + } + } else { + name_to_nm[name] = name; + name_to_tm_id[name] = 0; + items.Add(name); + } + } + if (!items.IsEmpty()) + var_box->InsertItems(items,0); +} + +void SpectralClusteringDlg::OnClickClose(wxCommandEvent& event ) +{ + wxLogMessage("OnClickClose SpectralClusteringDlg."); + + event.Skip(); + EndDialog(wxID_CANCEL); + Destroy(); +} + +void SpectralClusteringDlg::OnClose(wxCloseEvent& ev) +{ + wxLogMessage("Close SpectralClusteringDlg"); + // Note: it seems that if we don't explictly capture the close event + // and call Destory, then the destructor is not called. + Destroy(); +} + +wxString SpectralClusteringDlg::_printConfiguration() +{ + wxString txt; + txt << _("Number of clusters:\t") << combo_n->GetString(combo_n->GetSelection()) << "\n"; + + if (chk_kernel->IsChecked()) { + txt << _("Affinity with Guassian Kernel:\tSigma=") << m_sigma->GetValue() << "\n"; + } + if (chk_knn->IsChecked()) { + txt << _("Affinity with K-Nearest Neighbors:\tK=") << m_knn->GetValue() << "\n"; + } + + txt << _("Transformation:\t") << combo_tranform->GetString(combo_tranform->GetSelection()) << "\n"; + + txt << _("Distance function:\t") << m_distance->GetString(m_distance->GetSelection()) << "\n"; + + txt << "(K-Means) " << _("Initialization method:\t") << combo_method->GetString(combo_method->GetSelection()) << "\n"; + txt << "(K-Means) " << _("Initialization re-runs:\t") << m_pass->GetValue() << "\n"; + txt << "(K-Means) " << _("Maximum iterations:\t") << m_iterations->GetValue() << "\n"; + //txt << "(K-Means) Method:\t" << m_method->GetString(m_method->GetSelection()) << "\n"; + return txt; +} + +void SpectralClusteringDlg::OnOK(wxCommandEvent& event ) +{ + wxLogMessage("Click SpectralClusteringDlg::OnOK"); + + if (GdaConst::use_gda_user_seed) { + setrandomstate(GdaConst::gda_user_seed); + resetrandom(); + } + + int ncluster = combo_n->GetSelection() + 2; + + wxString field_name = m_textbox->GetValue(); + if (field_name.IsEmpty()) { + wxString err_msg = _("Please enter a field name for saving clustering results."); + wxMessageDialog dlg(NULL, err_msg, _("Error"), wxOK | wxICON_ERROR); + dlg.ShowModal(); + return; + } + + int transform = combo_tranform->GetSelection(); + + bool success = GetInputData(transform, 1); + if (!success) { + return; + } + + wxString field_sigma = m_sigma->GetValue(); + if (field_sigma.IsEmpty()) { + wxString err_msg = _("Please enter a sigma value."); + wxMessageDialog dlg(NULL, err_msg, _("Error"), wxOK | wxICON_ERROR); + dlg.ShowModal(); + return; + } + + char method = 'a'; // mean, 'm' median + char dist = 'e'; // euclidean + int npass = 10; + int n_maxiter = 300; // max iteration of EM + int transpose = 0; // row wise + int* clusterid = new int[rows]; + + wxString iterations = m_iterations->GetValue(); + long value; + if(iterations.ToLong(&value)) { + n_maxiter = value; + } + + if (combo_method->GetSelection() == 0) method = 'b'; // mean with kmeans++ + + wxString str_pass = m_pass->GetValue(); + long value_pass; + if(str_pass.ToLong(&value_pass)) { + npass = value_pass; + } + + int dist_sel = m_distance->GetSelection(); + char dist_choices[] = {'e','e','b','c','c','a','u','u','x','s','s','k'}; + dist = dist_choices[dist_sel]; + + wxString str_sigma = m_sigma->GetValue(); + double value_sigma; + if(str_sigma.ToDouble(&value_sigma)) { + value_sigma = value_sigma; + } + + long l_iterations = 0; + if (chk_poweriteration->IsChecked()) { + wxString str_iterations; + str_iterations = txt_poweriteration->GetValue(); + str_iterations.ToLong(&l_iterations); + } + + int knn = 4; + wxString str_knn = m_knn->GetValue(); + long value_knn; + if(str_knn.ToLong(&value_knn)) { + knn = value_knn; + } + + int affinity_type = 0; + + Spectral spectral; + spectral.set_data(input_data, rows, columns); + spectral.set_centers(ncluster); + spectral.set_power_iters(l_iterations); + if (chk_kernel->IsChecked()) { + spectral.set_kernel(0); + spectral.set_sigma(value_sigma); + affinity_type = 0; + } else { + spectral.set_knn(knn); + affinity_type = 1; + } + spectral.cluster(affinity_type); + + + vector clusters = spectral.get_assignments(); + + vector clusters_undef; + + // sort result + std::vector > cluster_ids(ncluster); + + for (int i=0; i < clusters.size(); i++) { + cluster_ids[ clusters[i] - 1 ].push_back(i); + } + + std::sort(cluster_ids.begin(), cluster_ids.end(), GenUtils::less_vectors); + + for (int i=0; i < ncluster; i++) { + int c = i + 1; + for (int j=0; jFindColId(field_name); + if ( col == wxNOT_FOUND) { + int col_insert_pos = table_int->GetNumberCols(); + int time_steps = 1; + int m_length_val = GdaConst::default_dbf_long_len; + int m_decimals_val = 0; + + col = table_int->InsertCol(GdaConst::long64_type, field_name, col_insert_pos, time_steps, m_length_val, m_decimals_val); + } else { + // detect if column is integer field, if not raise a warning + if (table_int->GetColType(col) != GdaConst::long64_type ) { + wxString msg = _("This field name already exists (non-integer type). Please input a unique name."); + wxMessageDialog dlg(this, msg, _("Warning"), wxOK | wxICON_WARNING ); + dlg.ShowModal(); + return; + } + } + + if (col > 0) { + table_int->SetColData(col, time, clusters); + table_int->SetColUndefined(col, time, clusters_undef); + } + + // show a cluster map + if (project->IsTableOnlyProject()) { + return; + } + std::vector new_var_info; + std::vector new_col_ids; + new_col_ids.resize(1); + new_var_info.resize(1); + new_col_ids[0] = col; + new_var_info[0].time = 0; + // Set Primary GdaVarTools::VarInfo attributes + new_var_info[0].name = field_name; + new_var_info[0].is_time_variant = table_int->IsColTimeVariant(col); + table_int->GetMinMaxVals(new_col_ids[0], new_var_info[0].min, new_var_info[0].max); + new_var_info[0].sync_with_global_time = new_var_info[0].is_time_variant; + new_var_info[0].fixed_scale = true; + + + MapFrame* nf = new MapFrame(parent, project, + new_var_info, new_col_ids, + CatClassification::unique_values, + MapCanvas::no_smoothing, 4, + boost::uuids::nil_uuid(), + wxDefaultPosition, + GdaConst::map_default_size); + + wxString ttl; + ttl << "Spectral Clustering Map ("; + ttl << ncluster; + ttl << " clusters)"; + nf->SetTitle(ttl); +} diff --git a/DialogTools/SpectralClusteringDlg.h b/DialogTools/SpectralClusteringDlg.h new file mode 100644 index 000000000..2e2984044 --- /dev/null +++ b/DialogTools/SpectralClusteringDlg.h @@ -0,0 +1,94 @@ +/** + * GeoDa TM, Copyright (C) 2011-2015 by Luc Anselin - all rights reserved + * + * This file is part of GeoDa. + * + * GeoDa is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * GeoDa is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#ifndef __GEODA_CENTER_SPECTRAL_DLG_H___ +#define __GEODA_CENTER_SPECTRAL_DLG_H___ + +#include +#include +#include +#include + +#include "../FramesManager.h" +#include "../VarTools.h" +#include "AbstractClusterDlg.h" + +class Project; +class TableInterface; + +class SpectralClusteringDlg : public AbstractClusterDlg +{ +public: + SpectralClusteringDlg(wxFrame *parent, Project* project); + virtual ~SpectralClusteringDlg(); + + void CreateControls(); + virtual bool Init(); + + void OnOK( wxCommandEvent& event ); + void OnClickClose( wxCommandEvent& event ); + void OnClose(wxCloseEvent& ev); + + void OnCheckPowerIteration(wxCommandEvent& event); + void OnWeightsCheck(wxCommandEvent& event); + void OnKernelCheck(wxCommandEvent& event); + void OnKNNCheck(wxCommandEvent& event); + void OnSeedCheck(wxCommandEvent& event); + void OnChangeSeed(wxCommandEvent& event); + void OnDistanceChoice(wxCommandEvent& event); + + virtual void InitVariableCombobox(wxListBox* var_box); + + virtual wxString _printConfiguration(); +protected: + wxCheckBox* chk_seed; + wxChoice* combo_method; + wxChoice* combo_n; + wxChoice* combo_cov; + wxTextCtrl* m_textbox; + wxTextCtrl* m_iterations; + wxTextCtrl* m_pass; + + wxTextCtrl* m_sigma; + wxChoice* combo_kernel; + wxChoice* m_method; + wxChoice* m_distance; + wxCheckBox* chk_kernel; + wxStaticText* lbl_kernel; + wxStaticText* lbl_sigma; + + wxCheckBox* chk_knn; + wxStaticText* lbl_knn; + wxStaticText* lbl_neighbors; + wxTextCtrl* m_knn; + + wxStaticText* lbl_weights; + wxCheckBox* chk_weights; + wxChoice* combo_weights; + + wxCheckBox* chk_poweriteration; + wxTextCtrl* txt_poweriteration; + wxStaticText* lbl_poweriteration; + + wxButton* seedButton; + + DECLARE_EVENT_TABLE() +}; + +#endif diff --git a/DialogTools/TimeEditorDlg.cpp b/DialogTools/TimeEditorDlg.cpp index 354354836..82add0079 100644 --- a/DialogTools/TimeEditorDlg.cpp +++ b/DialogTools/TimeEditorDlg.cpp @@ -96,7 +96,7 @@ void TimeEditorDlg::OnNewButton(wxCommandEvent& ev) { if (table_state->GetNumDisallowTimelineChanges() > 0) { wxString msg = table_state->GetDisallowTimelineChangesMsg(); - wxMessageDialog dlg (this, msg, "Warning", + wxMessageDialog dlg (this, msg, _("Warning"), wxOK | wxICON_INFORMATION); dlg.ShowModal(); return; @@ -124,7 +124,7 @@ void TimeEditorDlg::OnBackButton(wxCommandEvent& ev) if (sel <= 0 || sel >= lc->GetItemCount()) return; if (table_state->GetNumDisallowTimelineChanges() > 0) { wxString msg = table_state->GetDisallowTimelineChangesMsg(); - wxMessageDialog dlg (this, msg, "Warning", + wxMessageDialog dlg (this, msg, _("Warning"), wxOK | wxICON_INFORMATION); dlg.ShowModal(); return; @@ -140,7 +140,7 @@ void TimeEditorDlg::OnForwardButton(wxCommandEvent& ev) if (sel < 0 || sel >= lc->GetItemCount()-1) return; if (table_state->GetNumDisallowTimelineChanges() > 0) { wxString msg = table_state->GetDisallowTimelineChangesMsg(); - wxMessageDialog dlg (this, msg, "Warning", + wxMessageDialog dlg (this, msg, _("Warning"), wxOK | wxICON_INFORMATION); dlg.ShowModal(); return; @@ -156,7 +156,7 @@ void TimeEditorDlg::OnDeleteButton(wxCommandEvent& ev) if (sel < 0) return; if (table_state->GetNumDisallowTimelineChanges() > 0) { wxString msg = table_state->GetDisallowTimelineChangesMsg(); - wxMessageDialog dlg (this, msg, "Warning", + wxMessageDialog dlg (this, msg, _("Warning"), wxOK | wxICON_INFORMATION); dlg.ShowModal(); return; @@ -199,7 +199,7 @@ void TimeEditorDlg::OnEndEditItem(wxListEvent& ev) if (item_new.IsEmpty() || is_dup || is_disallow) { if (is_disallow && !(item_new.IsEmpty() || is_dup)) { wxString msg = table_state->GetDisallowTimelineChangesMsg(); - wxMessageDialog dlg(this, msg, "Warning", + wxMessageDialog dlg(this, msg, _("Warning"), wxOK | wxICON_INFORMATION); dlg.ShowModal(); } diff --git a/DialogTools/VarGroupingEditorDlg.cpp b/DialogTools/VarGroupingEditorDlg.cpp index eca5d4d11..93b57e57c 100644 --- a/DialogTools/VarGroupingEditorDlg.cpp +++ b/DialogTools/VarGroupingEditorDlg.cpp @@ -28,8 +28,6 @@ #include #include #include "../FramesManager.h" -#include "../DbfFile.h" -#include "../DataViewer/DbfTable.h" #include "../DataViewer/OGRTable.h" #include "../DataViewer/DataViewerAddColDlg.h" #include "../DataViewer/TableInterface.h" @@ -118,7 +116,8 @@ frames_manager(project_p->GetFramesManager()), table_state(project_p->GetTableState()), highlight_state(project_p->GetHighlightState()), wmi(project_p->GetWManInt()), -common_empty(true), all_init(false), pos_ungrouped_list(0),is_editing(false) +common_empty(true), all_init(false), pos_ungrouped_list(0),is_editing(false), +export_dlg(NULL), mem_table_int(NULL) { wxLogMessage("Open VarGroupingEditorDlg."); CreateControls(); @@ -136,6 +135,16 @@ VarGroupingEditorDlg::~VarGroupingEditorDlg() frames_manager->removeObserver(this); table_state->removeObserver(this); + + if (export_dlg) { + export_dlg->Destroy(); + delete export_dlg; + } + + if (mem_table_int) { + delete mem_table_int; + mem_table_int = NULL; + } } void VarGroupingEditorDlg::CreateControls() @@ -150,9 +159,9 @@ void VarGroupingEditorDlg::CreateControls() placeholder_button = wxDynamicCast(FindWindow(XRCID("ID_PLACEHOLDER_BUTTON")), wxButton); include_list = wxDynamicCast(FindWindow(XRCID("ID_INCLUDE_LIST")), wxListCtrl); - include_list->AppendColumn("Time"); + include_list->AppendColumn(_("Time")); include_list->SetColumnWidth(0, 50); - include_list->AppendColumn("Name"); + include_list->AppendColumn(_("Name")); include_list->SetColumnWidth(1, 120); @@ -165,9 +174,9 @@ void VarGroupingEditorDlg::CreateControls() ungroup_button = wxDynamicCast(FindWindow(XRCID("ID_UNGROUP_BUTTON")), wxButton); ungrouped_list = wxDynamicCast(FindWindow(XRCID("ID_UNGROUPED_LIST")), wxListCtrl); - ungrouped_list->AppendColumn("Name"); + ungrouped_list->AppendColumn(_("Name")); ungrouped_list->SetColumnWidth(0, 120); - ungrouped_list->AppendColumn("Type"); + ungrouped_list->AppendColumn(_("Type")); ungrouped_list->SetColumnWidth(1, 50); grouped_list = wxDynamicCast(FindWindow(XRCID("ID_GROUPED_LIST")), wxListBox); @@ -183,8 +192,6 @@ void VarGroupingEditorDlg::CreateControls() UpdateButtons(); ungrouped_list->Bind(wxEVT_LEFT_DOWN, &VarGroupingEditorDlg::OnUngroupedListLeftDown, this); - - include_list->Bind(wxEVT_LEFT_DCLICK, &VarGroupingEditorDlg::OnIncludeListDblClicked, this); include_list->Bind(wxEVT_RIGHT_UP, &VarGroupingEditorDlg::OnIncludeListRightUp, this); include_list->Bind(wxEVT_RIGHT_DOWN, &VarGroupingEditorDlg::OnIncludeListRightDown, this); @@ -231,14 +238,18 @@ void VarGroupingEditorDlg::InitUngroupedList(std::set& excl_nms) wxString type_str; if (type == GdaConst::double_type || type == GdaConst::long64_type) { type_str << "num"; - } else if (type == GdaConst::string_type) { - type_str << "str"; + } else if (type == GdaConst::string_type) { + //type_str << "str"; + continue; } else if (type == GdaConst::date_type) { - type_str << "date"; + //type_str << "date"; + continue; } else if (type == GdaConst::time_type) { - type_str << "time"; + //type_str << "time"; + continue; } else if (type == GdaConst::datetime_type) { - type_str << "datetime"; + //type_str << "datetime"; + continue; } ungrouped_list->InsertItem(ug_cnt, wxEmptyString); ungrouped_list->SetItem(ug_cnt, 0, table_int->GetColName(col)); @@ -251,7 +262,9 @@ void VarGroupingEditorDlg::InitUngroupedList(std::set& excl_nms) pos_ungrouped_list = ug_cnt -1; } ungrouped_list->EnsureVisible(pos_ungrouped_list); - ungrouped_list->SetItemState(pos_ungrouped_list, wxLIST_STATE_FOCUSED|wxLIST_STATE_SELECTED, wxLIST_STATE_FOCUSED|wxLIST_STATE_SELECTED); + ungrouped_list->SetItemState(pos_ungrouped_list, + wxLIST_STATE_FOCUSED|wxLIST_STATE_SELECTED, + wxLIST_STATE_FOCUSED|wxLIST_STATE_SELECTED); } } @@ -278,9 +291,12 @@ void VarGroupingEditorDlg::InitGroupedList() void VarGroupingEditorDlg::OnClose(wxCloseEvent& event) { wxLogMessage("In VarGroupingEditorDlg::OnClose"); - // Note: it seems that if we don't explictly capture the close event - // and call Destory, then the destructor is not called. - Destroy(); + + if (export_dlg) { + export_dlg->Close(); + } + + event.Skip(); } void VarGroupingEditorDlg::OnSaveSpaceTimeTableClick( wxCommandEvent& event ) @@ -319,7 +335,11 @@ void VarGroupingEditorDlg::OnSaveSpaceTimeTableClick( wxCommandEvent& event ) } // create in-memory table - OGRTable* mem_table_int = new OGRTable(n); + if (mem_table_int != NULL) { + delete mem_table_int; + mem_table_int = NULL; + } + mem_table_int = new OGRTable(n); OGRColumn* id_col = new OGRColumnInteger("STID", 18, 0, n); id_col->UpdateData(new_ids, undefs); @@ -423,9 +443,14 @@ void VarGroupingEditorDlg::OnSaveSpaceTimeTableClick( wxCommandEvent& event ) } // export - ExportDataDlg dlg(this, (TableInterface*)mem_table_int); - if (dlg.ShowModal() == wxID_OK) { - wxString ds_name = dlg.GetDatasourceName(); + if (export_dlg != NULL) { + export_dlg->Destroy(); + delete export_dlg; + } + export_dlg = new ExportDataDlg(this, (TableInterface*)mem_table_int); + + if (export_dlg->ShowModal() == wxID_OK) { + wxString ds_name = export_dlg->GetDatasourceName(); wxFileName wx_fn(ds_name); // save weights @@ -443,9 +468,6 @@ void VarGroupingEditorDlg::OnSaveSpaceTimeTableClick( wxCommandEvent& event ) } } } - - // clean memory - delete mem_table_int; } void VarGroupingEditorDlg::OnCreateGrpClick( wxCommandEvent& event ) @@ -464,7 +486,7 @@ void VarGroupingEditorDlg::OnCreateGrpClick( wxCommandEvent& event ) m << "Variable name \"" << grp_nm << "\" is either a duplicate\n"; m << "or is invalid. Please enter an alternative,\n"; m << "non-duplicate variable name."; - wxMessageDialog dlg (this, m, "Error", wxOK | wxICON_ERROR ); + wxMessageDialog dlg (this, m, _("Error"), wxOK | wxICON_ERROR ); dlg.ShowModal(); return; } @@ -484,7 +506,7 @@ void VarGroupingEditorDlg::OnCreateGrpClick( wxCommandEvent& event ) if (table_int->GetTimeSteps() == 1 && tot_items > 1) { if (table_state->GetNumDisallowTimelineChanges() > 0) { wxString msg = table_state->GetDisallowTimelineChangesMsg(); - wxMessageDialog dlg (this, msg, "Warning", + wxMessageDialog dlg (this, msg, _("Warning"), wxOK | wxICON_INFORMATION); dlg.ShowModal(); return; @@ -522,7 +544,8 @@ void VarGroupingEditorDlg::OnUngroupClick( wxCommandEvent& event ) vector col_nms(tms); for (int t=0; tGetColName(col, t); - if (nm.IsEmpty()) nm = GdaConst::placeholder_str; + if (nm.IsEmpty()) + nm = GdaConst::placeholder_str; col_nms[t] = nm; col_nms_set.insert(nm); } @@ -803,8 +826,8 @@ void VarGroupingEditorDlg::OnAddToListClick( wxCommandEvent& event ) for (int i=0; iGetTimeString(0); - if (t.IsEmpty()) t = "time 0"; + t = "time 0"; + table_int->RenameTimeStep(0, t); } else { t = GenerateTimeLabel(); table_int->InsertTimeStep(item_cnt+i, t); @@ -840,7 +863,7 @@ void VarGroupingEditorDlg::OnAddToListClick( wxCommandEvent& event ) int inc_list_cnt = GetIncListNameCnt(); UpdateTimeStepsTxt(); - if (new_group_name_txt_ctrl->GetValue().IsEmpty() && inc_list_cnt > 1) { + if (new_group_name_txt_ctrl->GetValue().IsEmpty() || inc_list_cnt > 1) { vector names(inc_list_cnt); for (int i=0; iGetItemText(i, 1); @@ -943,18 +966,17 @@ void VarGroupingEditorDlg::OnIncludeListRightUp( wxMouseEvent& event) { wxLogMessage("In VarGroupingEditorDlg::OnIncludeListRightUp"); if (!is_editing) { - wxMenu mnu; - int id1 = XRCID("INCLUDE_ADD_TIME"); - mnu.Append(id1, _("Add Time")); - mnu.Append(XRCID("INCLUDE_DELETE_TIME"), _("Remove Time")); - mnu.Connect(wxEVT_COMMAND_MENU_SELECTED, - wxCommandEventHandler(VarGroupingEditorDlg::OnIncludePopupClick), - NULL, this); - if (GetListSel(include_list).size() == 0) { - mnu.Enable(XRCID("INCLUDE_DELETE_TIME"), false); - } - - PopupMenu(&mnu); + wxMenu mnu; + int id1 = XRCID("INCLUDE_ADD_TIME"); + mnu.Append(id1, _("Add Time")); + mnu.Append(XRCID("INCLUDE_DELETE_TIME"), _("Remove Time")); + mnu.Connect(wxEVT_COMMAND_MENU_SELECTED, + wxCommandEventHandler(VarGroupingEditorDlg::OnIncludePopupClick), + NULL, this); + if (GetListSel(include_list).size() == 0) { + mnu.Enable(XRCID("INCLUDE_DELETE_TIME"), false); + } + PopupMenu(&mnu); } event.Skip(); @@ -1060,7 +1082,7 @@ void VarGroupingEditorDlg::OnIncludeListEditEnd( wxListEvent& event ) if (item_new.IsEmpty() || is_dup || is_disallow) { if (is_disallow && !(item_new.IsEmpty() || is_dup)) { wxString msg = table_state->GetDisallowTimelineChangesMsg(); - wxMessageDialog dlg(this, msg, "Warning", + wxMessageDialog dlg(this, msg, _("Warning"), wxOK | wxICON_INFORMATION); dlg.ShowModal(); } @@ -1215,12 +1237,11 @@ void VarGroupingEditorDlg::UpdateTimeStepsTxt() { wxString s; int cur_tm_steps = table_int->GetTimeSteps(); - if (cur_tm_steps > 1) { - s << GetIncListNameCnt() << " of " << cur_tm_steps; - } else { - s << GetIncListNameCnt(); + if (cur_tm_steps > 1) { + s = wxString::Format(_("%d of %d variables to include"), GetIncListNameCnt(), cur_tm_steps); + } else { + s = wxString::Format(_("%d variables to include"), GetIncListNameCnt()); } - s << " variables to include"; include_list_stat_txt->SetLabelText(s); //wxSizer* szr = include_list_stat_txt->GetContainingSizer(); //if (szr) szr->Layout(); @@ -1276,7 +1297,7 @@ void VarGroupingEditorDlg::OnLoadFromGda( wxCommandEvent& event ) ProjectConfiguration* project_conf = new ProjectConfiguration(full_proj_path); project->UpdateProjectConf(project_conf); } catch( GdaException& ex) { - wxMessageDialog dlg (this, ex.what(), "Error", wxOK | wxICON_ERROR ); + wxMessageDialog dlg (this, ex.what(), _("Error"), wxOK | wxICON_ERROR ); dlg.ShowModal(); } diff --git a/DialogTools/VarGroupingEditorDlg.h b/DialogTools/VarGroupingEditorDlg.h index 6cb3a193f..729628c79 100644 --- a/DialogTools/VarGroupingEditorDlg.h +++ b/DialogTools/VarGroupingEditorDlg.h @@ -39,6 +39,8 @@ class TableState; class TableInterface; class Project; class WeightsManInterface; +class ExportDataDlg; +class OGRTable; class VarGroupingEditorDlg: public wxDialog, public FramesManagerObserver, public TableStateObserver @@ -96,7 +98,7 @@ public TableStateObserver void OnNewGroupHelp( wxCommandEvent& event ); void OnCurGroupedHelp( wxCommandEvent& event ); void OnLoadFromGda( wxCommandEvent& event ); - + void UpdateGroupButton(); void UpdateAddToListButton(); void UpdateButtons(); @@ -156,11 +158,14 @@ public TableStateObserver bool sort_asc; wxListBox* grouped_list; + + ExportDataDlg* export_dlg; FramesManager* frames_manager; TableState* table_state; TableInterface* table_int; Project* project; + OGRTable* mem_table_int; bool common_empty; wxString common_type; diff --git a/DialogTools/VariableSettingsDlg.cpp b/DialogTools/VariableSettingsDlg.cpp index 605f26eed..4ace2ebbf 100644 --- a/DialogTools/VariableSettingsDlg.cpp +++ b/DialogTools/VariableSettingsDlg.cpp @@ -102,20 +102,20 @@ void DiffMoranVarSettingDlg::CreateControls() wxStaticText *st = new wxStaticText (panel, wxID_ANY, _("Select variable "), wxDefaultPosition, wxDefaultSize); - wxComboBox* box = new wxComboBox(panel, wxID_ANY, _(""), wxDefaultPosition, + wxComboBox* box = new wxComboBox(panel, wxID_ANY, "", wxDefaultPosition, var_size, 0, NULL, wxCB_READONLY); wxStaticText *st1 = new wxStaticText (panel, wxID_ANY, _(" and two time periods: "), wxDefaultPosition, wxDefaultSize); - wxComboBox* box1 = new wxComboBox(panel, wxID_ANY, _(""), wxDefaultPosition, + wxComboBox* box1 = new wxComboBox(panel, wxID_ANY, "", wxDefaultPosition, time_size, 0, NULL, wxCB_READONLY); wxStaticText *st2 = new wxStaticText (panel, wxID_ANY, _(" and "), wxDefaultPosition, wxDefaultSize); - wxComboBox* box2 = new wxComboBox(panel, wxID_ANY, _(""), wxDefaultPosition, + wxComboBox* box2 = new wxComboBox(panel, wxID_ANY, "", wxDefaultPosition, time_size, 0, NULL, wxCB_READONLY); hbox->Add(st, 1, wxALIGN_CENTER | wxLEFT| wxTOP | wxBOTTOM, 10); @@ -126,10 +126,10 @@ void DiffMoranVarSettingDlg::CreateControls() hbox->Add(box2, 1, wxALIGN_CENTER | wxTOP | wxBOTTOM |wxRIGHT, 10); - wxStaticText *st3 = new wxStaticText (panel, wxID_ANY, wxT("Weights"), + wxStaticText *st3 = new wxStaticText (panel, wxID_ANY, _("Weights"), wxDefaultPosition, wxSize(70,-1)); - wxComboBox* box3 = new wxComboBox(panel, wxID_ANY, wxT(""), wxDefaultPosition, + wxComboBox* box3 = new wxComboBox(panel, wxID_ANY, _(""), wxDefaultPosition, wxSize(160,-1), 0, NULL, wxCB_READONLY); hbox1->Add(st3, 0, wxALIGN_CENTER | wxLEFT| wxTOP | wxBOTTOM, 10); @@ -140,9 +140,9 @@ void DiffMoranVarSettingDlg::CreateControls() panel->SetSizer(vbox); - wxButton *okButton = new wxButton(this, wxID_OK, wxT("OK"), wxDefaultPosition, + wxButton *okButton = new wxButton(this, wxID_OK, _("OK"), wxDefaultPosition, wxSize(70, 30)); - wxButton *closeButton = new wxButton(this, wxID_EXIT, wxT("Close"), + wxButton *closeButton = new wxButton(this, wxID_EXIT, _("Close"), wxDefaultPosition, wxSize(70, 30)); hbox2->Add(okButton, 1); @@ -220,7 +220,7 @@ void DiffMoranVarSettingDlg::OnOK(wxCommandEvent& event ) if (col_name.IsEmpty()) { wxMessageDialog dlg (this, "Please select a variable first.", - "Warning", + _("Warning"), wxOK | wxICON_WARNING); dlg.ShowModal(); return; @@ -231,7 +231,7 @@ void DiffMoranVarSettingDlg::OnOK(wxCommandEvent& event ) if (time1 < 0 || time2 < 0 || time1 == time2) { wxMessageDialog dlg (this, "Please choose two different time periods.", - "Warning", wxOK | wxICON_WARNING); + _("Warning"), wxOK | wxICON_WARNING); dlg.ShowModal(); return; } @@ -267,7 +267,7 @@ void DiffMoranVarSettingDlg::OnOK(wxCommandEvent& event ) } } catch(GdaException& ex) { // place holder found - wxString str_tmplt = _T("The selected group variable should contains %d items. Please modify the group variable in Time Editor, or select another variable."); + wxString str_tmplt = _("The selected group variable should contains %d items. Please modify the group variable in Time Editor, or select another variable."); wxString msg = wxString::Format(str_tmplt, project->GetTableInt()->GetTimeSteps()); wxMessageDialog dlg (this, msg.mb_str(), "Incomplete Group Variable ", wxOK | wxICON_ERROR); dlg.ShowModal(); @@ -289,526 +289,7 @@ boost::uuids::uuid DiffMoranVarSettingDlg::GetWeightsId() return weights_ids[sel]; } -//////////////////////////////////////////////////////////////////////////// -// -// PCASettingsDlg -// -//////////////////////////////////////////////////////////////////////////// - -BEGIN_EVENT_TABLE(SimpleReportTextCtrl, wxTextCtrl) -EVT_CONTEXT_MENU(SimpleReportTextCtrl::OnContextMenu) -END_EVENT_TABLE() - -void SimpleReportTextCtrl::OnContextMenu(wxContextMenuEvent& event) -{ - wxMenu* menu = new wxMenu; - // Some standard items - menu->Append(XRCID("SAVE_SIMPLE_REPORT"), _("&Save")); - menu->AppendSeparator(); - menu->Append(wxID_UNDO, _("&Undo")); - menu->Append(wxID_REDO, _("&Redo")); - menu->AppendSeparator(); - menu->Append(wxID_CUT, _("Cu&t")); - menu->Append(wxID_COPY, _("&Copy")); - menu->Append(wxID_PASTE, _("&Paste")); - menu->Append(wxID_CLEAR, _("&Delete")); - menu->AppendSeparator(); - menu->Append(wxID_SELECTALL, _("Select &All")); - - // Add any custom items here - Connect(XRCID("SAVE_SIMPLE_REPORT"), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(SimpleReportTextCtrl::OnSaveClick)); - - PopupMenu(menu); -} - -void SimpleReportTextCtrl::OnSaveClick( wxCommandEvent& event ) -{ - wxLogMessage("In SimpleReportTextCtrl::OnSaveClick()"); - wxFileDialog dlg( this, "Save PCA results", wxEmptyString, - wxEmptyString, - "TXT files (*.txt)|*.txt", - wxFD_SAVE ); - if (dlg.ShowModal() != wxID_OK) return; - - wxFileName new_txt_fname(dlg.GetPath()); - wxString new_txt = new_txt_fname.GetFullPath(); - wxFFileOutputStream output(new_txt); - if (output.IsOk()) { - wxTextOutputStream txt_out( output ); - txt_out << this->GetValue(); - txt_out.Flush(); - output.Close(); - } -} - - -BEGIN_EVENT_TABLE( PCASettingsDlg, wxDialog ) -EVT_CLOSE( PCASettingsDlg::OnClose ) -END_EVENT_TABLE() - -PCASettingsDlg::PCASettingsDlg(Project* project_s) - : wxDialog(NULL, -1, _("PCA Settings"), wxDefaultPosition, wxSize(860, 600), wxDEFAULT_DIALOG_STYLE|wxRESIZE_BORDER), -frames_manager(project_s->GetFramesManager()) -{ - wxLogMessage("Open PCASettingsDlg."); - - SetMinSize(wxSize(860,600)); - - project = project_s; - - bool init_success = Init(); - - if (init_success == false) { - EndDialog(wxID_CANCEL); - } else { - CreateControls(); - } - frames_manager->registerObserver(this); -} - -PCASettingsDlg::~PCASettingsDlg() -{ - frames_manager->removeObserver(this); -} - -void PCASettingsDlg::update(FramesManager* o) -{ -} - -bool PCASettingsDlg::Init() -{ - if (project == NULL) - return false; - - table_int = project->GetTableInt(); - if (table_int == NULL) - return false; - - - table_int->GetTimeStrings(tm_strs); - - return true; -} - -void PCASettingsDlg::CreateControls() -{ - wxPanel *panel = new wxPanel(this); - - wxBoxSizer *vbox = new wxBoxSizer(wxVERTICAL); - - // input - wxStaticText* st = new wxStaticText (panel, wxID_ANY, _("Select Variables"), - wxDefaultPosition, wxDefaultSize); - - wxListBox* box = new wxListBox(panel, wxID_ANY, wxDefaultPosition, - wxSize(250,250), 0, NULL, - wxLB_MULTIPLE | wxLB_HSCROLL| wxLB_NEEDED_SB); - - wxStaticBoxSizer *hbox0 = new wxStaticBoxSizer(wxVERTICAL, panel, "Input:"); - hbox0->Add(st, 0, wxALIGN_CENTER | wxLEFT | wxRIGHT, 10); - hbox0->Add(box, 1, wxEXPAND | wxLEFT | wxRIGHT | wxBOTTOM, 10); - - // parameters - wxFlexGridSizer* gbox = new wxFlexGridSizer(5,2,10,0); - - wxStaticText* st12 = new wxStaticText(panel, wxID_ANY, _("Method:"), - wxDefaultPosition, wxSize(120,-1)); - const wxString _methods[2] = {"SVD", "Eigen"}; - wxChoice* box0 = new wxChoice(panel, wxID_ANY, wxDefaultPosition, - wxSize(120,-1), 2, _methods); - gbox->Add(st12, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT | wxLEFT, 10); - gbox->Add(box0, 1, wxEXPAND); - - - wxStaticText* st14 = new wxStaticText(panel, wxID_ANY, _("Transformation:"), - wxDefaultPosition, wxSize(120,-1)); - const wxString _transform[3] = {"Raw", "Demean", "Standardize"}; - wxChoice* box01 = new wxChoice(panel, wxID_ANY, wxDefaultPosition, - wxSize(120,-1), 3, _transform); - - gbox->Add(st14, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT | wxLEFT, 10); - gbox->Add(box01, 1, wxEXPAND); - - - wxStaticBoxSizer *hbox = new wxStaticBoxSizer(wxHORIZONTAL, panel, "Parameters:"); - hbox->Add(gbox, 1, wxEXPAND); - - // Output - wxStaticText* st1 = new wxStaticText(panel, wxID_ANY, _("Components:"), - wxDefaultPosition, wxSize(140,-1)); - wxChoice* box1 = new wxChoice(panel, wxID_ANY, wxDefaultPosition, - wxSize(120,-1), 0, NULL); - - wxStaticBoxSizer *hbox1 = new wxStaticBoxSizer(wxHORIZONTAL, panel, "Output:"); - hbox1->Add(st1, 0, wxALIGN_CENTER_VERTICAL); - hbox1->Add(box1, 1, wxALIGN_CENTER_VERTICAL); - - - - // buttons - wxButton *okButton = new wxButton(panel, wxID_OK, wxT("Run"), wxDefaultPosition, - wxSize(70, 30)); - saveButton = new wxButton(panel, wxID_SAVE, wxT("Save"), wxDefaultPosition, - wxSize(70, 30)); - wxButton *closeButton = new wxButton(panel, wxID_EXIT, wxT("Close"), - wxDefaultPosition, wxSize(70, 30)); - wxBoxSizer *hbox2 = new wxBoxSizer(wxHORIZONTAL); - hbox2->Add(okButton, 1, wxALIGN_CENTER | wxALL, 5); - hbox2->Add(saveButton, 1, wxALIGN_CENTER | wxALL, 5); - hbox2->Add(closeButton, 1, wxALIGN_CENTER | wxALL, 5); - - // Container - vbox->Add(hbox0, 1, wxEXPAND | wxALL, 10); - vbox->Add(hbox, 0, wxALIGN_CENTER | wxALL, 10); - vbox->Add(hbox1, 1, wxALIGN_CENTER | wxTOP | wxLEFT | wxRIGHT, 10); - vbox->Add(hbox2, 1, wxALIGN_CENTER | wxALL, 10); - - - wxBoxSizer *vbox1 = new wxBoxSizer(wxVERTICAL); - m_textbox = new SimpleReportTextCtrl(panel, XRCID("ID_TEXTCTRL"), "", wxDefaultPosition, wxSize(320,830), wxTE_MULTILINE | wxTE_READONLY); - - if (GeneralWxUtils::isWindows()) { - wxFont font(8,wxFONTFAMILY_TELETYPE,wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL); - m_textbox->SetFont(font); - } else { - wxFont font(12,wxFONTFAMILY_TELETYPE,wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL); - m_textbox->SetFont(font); - - } - vbox1->Add(m_textbox, 1, wxEXPAND|wxALL,20); - - wxBoxSizer *container = new wxBoxSizer(wxHORIZONTAL); - container->Add(vbox); - container->Add(vbox1,1, wxEXPAND | wxALL); - - panel->SetSizer(container); - - Centre(); - - // Content - InitVariableCombobox(box); - - saveButton->Enable(false); - combo_var = box; - combo_n = box1; - - combo_method = box0; - combo_transform = box01; - - combo_method->SetSelection(0); - combo_transform->SetSelection(2); - - // Events - okButton->Bind(wxEVT_BUTTON, &PCASettingsDlg::OnOK, this); - saveButton->Bind(wxEVT_BUTTON, &PCASettingsDlg::OnSave, this); - closeButton->Bind(wxEVT_BUTTON, &PCASettingsDlg::OnCloseClick, this); - - combo_method->Connect(wxEVT_CHOICE, - wxCommandEventHandler(PCASettingsDlg::OnMethodChoice), - NULL, this); - -} - -void PCASettingsDlg::OnMethodChoice(wxCommandEvent& event) -{ - /* - if (combo_method->GetSelection() == 0) { - combo_transform->Enable(); - } else if (combo_method->GetSelection() == 1) { - combo_transform->SetSelection(2); - combo_transform->Disable(); - } - */ -} - -void PCASettingsDlg::InitVariableCombobox(wxListBox* var_box) -{ - wxArrayString items; - - std::vector col_id_map; - table_int->FillNumericColIdMap(col_id_map); - for (int i=0, iend=col_id_map.size(); iGetColName(id); - if (table_int->IsColTimeVariant(id)) { - for (int t=0; tGetColTimeSteps(id); t++) { - wxString nm = name; - nm << " (" << table_int->GetTimeString(t) << ")"; - name_to_nm[nm] = name;// table_int->GetColName(id, t); - name_to_tm_id[nm] = t; - items.Add(nm); - } - } else { - name_to_nm[name] = name; - name_to_tm_id[name] = 0; - items.Add(name); - } - } - - var_box->InsertItems(items,0); -} - -void PCASettingsDlg::OnClose(wxCloseEvent& ev) -{ - wxLogMessage("Close HClusterDlg"); - // Note: it seems that if we don't explictly capture the close event - // and call Destory, then the destructor is not called. - Destroy(); -} - -void PCASettingsDlg::OnCloseClick(wxCommandEvent& event ) -{ - wxLogMessage("Close PCASettingsDlg."); - - event.Skip(); - EndDialog(wxID_CANCEL); - Destroy(); -} - -void PCASettingsDlg::OnSave(wxCommandEvent& event ) -{ - wxLogMessage("OnSave PCASettingsDlg."); - - if (scores.size()==0) - return; - - // save to table - int new_col = combo_n->GetSelection() + 1; - - std::vector new_data(new_col); - std::vector > vals(new_col); - std::vector > undefs(new_col); - - for (unsigned int j = 0; j < new_col; ++j) { - vals[j].resize(row_lim); - undefs[j].resize(row_lim); - for (unsigned int i = 0; i < row_lim; ++i) { - vals[j][i] = double(scores[j + col_lim*i]); - undefs[j][i] = false; - } - new_data[j].d_val = &vals[j]; - new_data[j].label = wxString::Format("PC%d", j+1); - new_data[j].field_default = wxString::Format("PC%d", j+1); - new_data[j].type = GdaConst::double_type; - new_data[j].undefined = &undefs[j]; - } - - SaveToTableDlg dlg(project, this, new_data, - "Save Results: PCA", - wxDefaultPosition, wxSize(400,400)); - dlg.ShowModal(); - - event.Skip(); - -} - -void PCASettingsDlg::OnOK(wxCommandEvent& event ) -{ - wxLogMessage("Click PCASettingsDlg::OnOK"); - - wxArrayString sel_names; - int max_sel_name_len = 0; - - wxArrayInt selections; - combo_var->GetSelections(selections); - - int num_var = selections.size(); - if (num_var < 2) { - // show message box - wxString err_msg = _("Please select at least 2 variables."); - wxMessageDialog dlg(NULL, err_msg, "Info", wxOK | wxICON_ERROR); - dlg.ShowModal(); - return; - } - - int rows = project->GetNumRecords(); - int columns = num_var; - - col_ids.resize(num_var); - std::vector > data; - data.resize(num_var); - - var_info.resize(num_var); - - for (int i=0; iGetString(idx); - - sel_names.Add(sel_name); - if (sel_name.length() > max_sel_name_len) { - max_sel_name_len = sel_name.length(); - } - - wxString nm = name_to_nm[sel_name]; - - int col = table_int->FindColId(nm); - if (col == wxNOT_FOUND) { - wxString err_msg = wxString::Format(_("Variable %s is no longer in the Table. Please close and reopen the Regression Dialog to synchronize with Table data."), nm); wxMessageDialog dlg(NULL, err_msg, "Error", wxOK | wxICON_ERROR); - dlg.ShowModal(); - return; - } - - int tm = name_to_tm_id[sel_name]; - - data[i].resize(rows); - - table_int->GetColData(col, tm, data[i]); - } - - // Call function to set all Secondary Attributes based on Primary Attributes - //GdaVarTools::UpdateVarInfoSecondaryAttribs(var_info); - - vector vec; - - for (int k=0; k< rows;k++) { - for (int i=0; iGetSelection() == 1; - - bool is_center = false; - bool is_scale = false; - - if (combo_transform->GetSelection() == 1) { - is_center = true; - is_scale = false; - - } else if (combo_transform->GetSelection() == 2) { - is_center = true; - is_scale = true; - } - - if (rows < columns && is_corr == true) { - wxString msg = _("SVD will be automatically used for PCA since the number of rows is less than the number of columns."); - wxMessageDialog dlg(NULL, msg, "Information", wxOK | wxICON_INFORMATION); - dlg.ShowModal(); - combo_method->SetSelection(0); - is_corr = false; - } - - int init_result = pca.Calculate(vec, rows, columns, is_corr, is_center, is_scale); - if (0 != init_result) { - wxString msg = _("There is an error during PCA calculation. Please check if the data is valid."); - wxMessageDialog dlg(NULL, msg, "Error", wxOK | wxICON_ERROR); - dlg.ShowModal(); - return; - } - vector sd = pca.sd(); - vector prop_of_var = pca.prop_of_var(); - vector cum_prop = pca.cum_prop(); - scores = pca.scores(); - - vector el_cols = pca.eliminated_columns(); - - float kaiser = pca.kaiser(); - thresh95 = pca.thresh95(); - - unsigned int ncols = pca.ncols(); - unsigned int nrows = pca.nrows(); - - wxString method = pca.method(); - - wxString pca_log; - //pca_log << "\n\nPCA method: " << method; - - pca_log << "\n\nStandard deviation:\n"; - for (int i=0; i 0 && (token[pos] == ' ' || pos == n_len-1) ) { - // end of a number - pca_log << wxString::Format("%*s%d", sub_len-1, "PC", pc_idx++); - sub_len = 1; - start = false; - } else { - if (!start && token[pos] != ' ') { - start = true; - } - sub_len += 1; - } - pos += 1; - } - header = true; - pca_log << "\n"; - } - } - - for (int k=0; kSetValue(pca_log); - - combo_n->Clear(); - for (int i=0; iAppend(wxString::Format("%d", i+1)); - } - combo_n->SetSelection((int)thresh95 -1); - - saveButton->Enable(true); -} //////////////////////////////////////////////////////////////////////////// // @@ -819,7 +300,7 @@ void PCASettingsDlg::OnOK(wxCommandEvent& event ) MultiVariableSettingsDlg::MultiVariableSettingsDlg(Project* project_s) : wxDialog(NULL, -1, _("Multi-Variable Settings"), wxDefaultPosition, wxSize(320, 430)) { - wxLogMessage("Open MultiVariableSettingsDlg."); + wxLogMessage("Entering MultiVariableSettingsDlg::MultiVariableSettingsDlg()."); combo_time1 = NULL; @@ -834,10 +315,12 @@ MultiVariableSettingsDlg::MultiVariableSettingsDlg(Project* project_s) } else { CreateControls(); } + wxLogMessage("Exiting MultiVariableSettingsDlg::MultiVariableSettingsDlg()."); } MultiVariableSettingsDlg::~MultiVariableSettingsDlg() { + wxLogMessage("In ~MultiVariableSettingsDlg."); } bool MultiVariableSettingsDlg::Init() @@ -870,7 +353,7 @@ void MultiVariableSettingsDlg::CreateControls() wxLB_MULTIPLE | wxLB_HSCROLL| wxLB_NEEDED_SB); // weights - wxStaticText *st3 = new wxStaticText(panel, wxID_ANY, wxT("Weights:"), + wxStaticText *st3 = new wxStaticText(panel, wxID_ANY, _("Weights:"), wxDefaultPosition, wxSize(60,-1)); wxChoice* box3 = new wxChoice(panel, wxID_ANY, wxDefaultPosition, wxSize(160,-1), 0, NULL); @@ -879,9 +362,9 @@ void MultiVariableSettingsDlg::CreateControls() hbox1->Add(box3, 1, wxALIGN_CENTER_VERTICAL); // buttons - wxButton *okButton = new wxButton(panel, wxID_OK, wxT("OK"), wxDefaultPosition, + wxButton *okButton = new wxButton(panel, wxID_OK, _("OK"), wxDefaultPosition, wxSize(70, 30)); - wxButton *closeButton = new wxButton(panel, wxID_EXIT, wxT("Close"), + wxButton *closeButton = new wxButton(panel, wxID_EXIT, _("Close"), wxDefaultPosition, wxSize(70, 30)); wxBoxSizer *hbox2 = new wxBoxSizer(wxHORIZONTAL); hbox2->Add(okButton, 1, wxALIGN_CENTER | wxALL, 5); @@ -932,7 +415,7 @@ void MultiVariableSettingsDlg::CreateControls() void MultiVariableSettingsDlg::OnTimeSelect( wxCommandEvent& event ) { - wxLogMessage("MultiVariableSettingsDlg::OnTimeSelect"); + wxLogMessage("In MultiVariableSettingsDlg::OnTimeSelect()"); combo_var->Clear(); InitVariableCombobox(combo_var); @@ -940,6 +423,7 @@ void MultiVariableSettingsDlg::OnTimeSelect( wxCommandEvent& event ) void MultiVariableSettingsDlg::InitVariableCombobox(wxListBox* var_box) { + wxLogMessage("In MultiVariableSettingsDlg::InitVariableCombobox()."); var_box->Clear(); wxArrayString items; @@ -964,12 +448,14 @@ void MultiVariableSettingsDlg::InitVariableCombobox(wxListBox* var_box) items.Add(name); } } - - var_box->InsertItems(items,0); + + if (!items.IsEmpty()) + var_box->InsertItems(items,0); } void MultiVariableSettingsDlg::InitTimeComboboxes(wxChoice* time1) { + wxLogMessage("In MultiVariableSettingsDlg::InitTimeComboboxes()."); for (size_t i=0, n=tm_strs.size(); i < n; i++ ) { time1->Append(tm_strs[i]); } @@ -978,6 +464,7 @@ void MultiVariableSettingsDlg::InitTimeComboboxes(wxChoice* time1) void MultiVariableSettingsDlg::InitWeightsCombobox(wxChoice* weights_ch) { + wxLogMessage("In MultiVariableSettingsDlg::InitWeightsCombobox()."); WeightsManInterface* w_man_int = project->GetWManInt(); w_man_int->GetIds(weights_ids); @@ -992,7 +479,7 @@ void MultiVariableSettingsDlg::InitWeightsCombobox(wxChoice* weights_ch) void MultiVariableSettingsDlg::OnClose(wxCommandEvent& event ) { - wxLogMessage("Close MultiVariableSettingsDlg."); + wxLogMessage("In MultiVariableSettingsDlg::OnClose"); event.Skip(); EndDialog(wxID_CANCEL); @@ -1000,7 +487,7 @@ void MultiVariableSettingsDlg::OnClose(wxCommandEvent& event ) void MultiVariableSettingsDlg::OnOK(wxCommandEvent& event ) { - wxLogMessage("Click MultiVariableSettingsDlg::OnOK"); + wxLogMessage("Entering MultiVariableSettingsDlg::OnOK"); wxArrayInt selections; combo_var->GetSelections(selections); @@ -1009,7 +496,7 @@ void MultiVariableSettingsDlg::OnOK(wxCommandEvent& event ) if (num_var < 2) { // show message box wxString err_msg = _("Please select at least 2 variables."); - wxMessageDialog dlg(NULL, err_msg, "Info", wxOK | wxICON_ERROR); + wxMessageDialog dlg(NULL, err_msg, _("Info"), wxOK | wxICON_ERROR); dlg.ShowModal(); return; } @@ -1020,12 +507,11 @@ void MultiVariableSettingsDlg::OnOK(wxCommandEvent& event ) for (int i=0; iGetString(idx); - LOG_MSG(list_item); wxString nm = name_to_nm[list_item]; - LOG_MSG(nm); + wxLogMessage(nm); int col = table_int->FindColId(nm); if (col == wxNOT_FOUND) { - wxString err_msg = wxString::Format(_("Variable %s is no longer in the Table. Please close and reopen the Regression Dialog to synchronize with Table data."), nm); wxMessageDialog dlg(NULL, err_msg, "Error", wxOK | wxICON_ERROR); + wxString err_msg = wxString::Format(_("Variable %s is no longer in the Table. Please close and reopen this dialog to synchronize with Table data."), nm); wxMessageDialog dlg(NULL, err_msg, _("Error"), wxOK | wxICON_ERROR); dlg.ShowModal(); return; } @@ -1047,15 +533,15 @@ void MultiVariableSettingsDlg::OnOK(wxCommandEvent& event ) // Call function to set all Secondary Attributes based on Primary Attributes GdaVarTools::UpdateVarInfoSecondaryAttribs(var_info); - EndDialog(wxID_OK); + wxLogMessage("Exiting MultiVariableSettingsDlg::OnOK"); } boost::uuids::uuid MultiVariableSettingsDlg::GetWeightsId() { - + wxLogMessage("In MultiVariableSettingsDlg::GetWeightsId()"); int sel = combo_weights->GetSelection(); if (sel < 0) sel = 0; if (sel >= weights_ids.size()) sel = weights_ids.size()-1; @@ -1097,7 +583,6 @@ BEGIN_EVENT_TABLE(VariableSettingsDlg, wxDialog) EVT_BUTTON(XRCID("wxID_CANCEL"), VariableSettingsDlg::OnCancelClick) END_EVENT_TABLE() -/** All new code should use this constructor. */ VariableSettingsDlg::VariableSettingsDlg(Project* project_s, VarType v_type_s, bool show_weights_s, @@ -1109,7 +594,11 @@ VariableSettingsDlg::VariableSettingsDlg(Project* project_s, const wxString& var4_title_s, bool _set_second_from_first_mode, bool _set_fourth_from_third_mode, - bool hide_time) + bool hide_time, + bool _var1_str, + bool _var2_str, + bool _var3_str, + bool _var4_str) : project(project_s), table_int(project_s->GetTableInt()), show_weights(show_weights_s), @@ -1127,9 +616,18 @@ set_fourth_from_third_mode(_set_fourth_from_third_mode), num_cats_spin(0), num_categories(4), hide_time(hide_time), -all_init(false) +all_init(false), +var1_str(_var1_str), +var2_str(_var2_str), +var3_str(_var3_str), +var4_str(_var4_str) { wxLogMessage("Open VariableSettingsDlg"); + + default_var_name1 = project->GetDefaultVarName(0); + default_var_name2 = project->GetDefaultVarName(1); + default_var_name3 = project->GetDefaultVarName(2); + default_var_name4 = project->GetDefaultVarName(3); if (show_weights && project->GetWManInt()->GetIds().size() == 0) { no_weights_found_fail = true; @@ -1162,6 +660,7 @@ void VariableSettingsDlg::Init(VarType var_type) } else { // (var_type == quadvariate) num_var = 4; } + if (num_var > 2) show_weights = false; int num_obs = project->GetNumRecords(); @@ -1187,41 +686,12 @@ void VariableSettingsDlg::Init(VarType var_type) lb2_cur_sel = 0; lb3_cur_sel = 0; lb4_cur_sel = 0; - table_int->FillNumericColIdMap(col_id_map); - for (int i=0, iend=col_id_map.size(); iGetColName(col_id_map[i]) == project->GetDefaultVarName(0)) { - lb1_cur_sel = i; - if (set_second_from_first_mode && num_var >= 2) { - lb2_cur_sel = i; - } - } - if (num_var >= 2 && - table_int->GetColName(col_id_map[i]) == project->GetDefaultVarName(1)) - { - if (!set_second_from_first_mode) { - lb2_cur_sel = i; - } - } - if (num_var >= 3 && - table_int->GetColName(col_id_map[i]) == project->GetDefaultVarName(2)) - { - lb3_cur_sel = i; - if (set_fourth_from_third_mode && num_var >= 4) { - lb4_cur_sel = i; - } - } - if (num_var >= 4 && - table_int->GetColName(col_id_map[i]) == project->GetDefaultVarName(3)) - { - if (!set_fourth_from_third_mode) { - lb4_cur_sel = i; - } - } - } + + table_int->FillColIdMap(col_id_map); if (col_id_map.size() == 0) { - wxString msg("No numeric variables found."); - wxMessageDialog dlg (this, msg, "Warning", wxOK | wxICON_WARNING); + wxString msg = _("No numeric variables found."); + wxMessageDialog dlg (this, msg, _("Warning"), wxOK | wxICON_WARNING); dlg.ShowModal(); return; } @@ -1230,13 +700,13 @@ void VariableSettingsDlg::Init(VarType var_type) if (map_theme_ch) { map_theme_ch->Clear(); - map_theme_ch->Append("Quantile Map"); - map_theme_ch->Append("Percentile Map"); - map_theme_ch->Append("Box Map (Hinge=1.5)"); - map_theme_ch->Append("Box Map (Hinge=3.0)"); - map_theme_ch->Append("Standard Deviation Map"); - map_theme_ch->Append("Natural Breaks"); - map_theme_ch->Append("Equal Intervals"); + map_theme_ch->Append(_("Quantile Map")); + map_theme_ch->Append(_("Percentile Map")); + map_theme_ch->Append(_("Box Map (Hinge=1.5)")); + map_theme_ch->Append(_("Box Map (Hinge=3.0)")); + map_theme_ch->Append(_("Standard Deviation Map")); + map_theme_ch->Append(_("Natural Breaks")); + map_theme_ch->Append(_("Equal Intervals")); map_theme_ch->SetSelection(0); } } @@ -1311,7 +781,6 @@ void VariableSettingsDlg::CreateControls() } wxXmlResource::Get()->LoadDialog(this, GetParent(), ctrl_xrcid); - if (is_time) { if (hide_time) { wxStaticText* time_txt = XRCCTRL(*this, "ID_VARSEL_TIME", wxStaticText); @@ -1339,9 +808,11 @@ void VariableSettingsDlg::CreateControls() size_t sel_pos=0; for (size_t i=0; iAppend(w_man_int->GetShortDispName(weights_ids[i])); - if (w_man_int->GetDefault() == weights_ids[i]) sel_pos = i; + if (w_man_int->GetDefault() == weights_ids[i]) + sel_pos = i; } - if (weights_ids.size() > 0) weights_ch->SetSelection(sel_pos); + if (weights_ids.size() > 0) + weights_ch->SetSelection(sel_pos); } if (show_distance && v_type == univariate) { distance_ch = XRCCTRL(*this, "ID_DISTANCE_METRIC", wxChoice); @@ -1391,7 +862,6 @@ void VariableSettingsDlg::CreateControls() num_cats_spin = XRCCTRL(*this, "ID_NUM_CATEGORIES_SPIN", wxSpinCtrl); num_categories = num_cats_spin->GetValue(); } - } void VariableSettingsDlg::OnMapThemeChange(wxCommandEvent& event) @@ -1505,6 +975,11 @@ void VariableSettingsDlg::OnVar1Change(wxCommandEvent& event) if (!all_init) return; lb1_cur_sel = lb1->GetSelection(); + if (lb1_cur_sel >= 0) { + int x_pos = sel1_idx_map[lb1_cur_sel]; + if (x_pos >= 0) + default_var_name1 = table_int->GetColName(col_id_map[x_pos]); + } if (num_var >= 2 && set_second_from_first_mode) { lb2->SetSelection(lb1_cur_sel); lb2_cur_sel = lb1_cur_sel; @@ -1520,6 +995,11 @@ void VariableSettingsDlg::OnVar2Change(wxCommandEvent& event) if (!all_init) return; lb2_cur_sel = lb2->GetSelection(); + if (lb2_cur_sel >= 0) { + int x_pos = sel2_idx_map[lb2_cur_sel]; + if (x_pos >= 0) + default_var_name2 = table_int->GetColName(col_id_map[x_pos]); + } } void VariableSettingsDlg::OnVar3Change(wxCommandEvent& event) @@ -1527,6 +1007,12 @@ void VariableSettingsDlg::OnVar3Change(wxCommandEvent& event) if (!all_init) return; lb3_cur_sel = lb3->GetSelection(); + if (lb3_cur_sel >= 0) { + int x_pos = sel3_idx_map[lb3_cur_sel]; + if (x_pos >= 0) + default_var_name3 = table_int->GetColName(col_id_map[x_pos]); + } + if (num_var >= 4 && set_fourth_from_third_mode) { lb4->SetSelection(lb3_cur_sel); lb4_cur_sel = lb3_cur_sel; @@ -1542,6 +1028,11 @@ void VariableSettingsDlg::OnVar4Change(wxCommandEvent& event) if (!all_init) return; lb4_cur_sel = lb4->GetSelection(); + if (lb4_cur_sel >= 0) { + int x_pos = sel4_idx_map[lb4_cur_sel]; + if (x_pos >= 0) + default_var_name4 = table_int->GetColName(col_id_map[x_pos]); + } } void VariableSettingsDlg::OnSpinCtrl( wxSpinEvent& event ) @@ -1578,12 +1069,14 @@ void VariableSettingsDlg::OnOkClick(wxCommandEvent& event) } if (lb1->GetSelection() == wxNOT_FOUND) { - wxString msg(_T("No field chosen for first variable.")); - wxMessageDialog dlg (this, msg, _T("Error"), wxOK | wxICON_ERROR); + wxString msg(_("No field chosen for first variable.")); + wxMessageDialog dlg (this, msg, _("Error"), wxOK | wxICON_ERROR); dlg.ShowModal(); return; } - v1_col_id = col_id_map[lb1->GetSelection()]; + + v1_col_id = col_id_map[sel1_idx_map[lb1->GetSelection()]]; + v1_name = table_int->GetColName(v1_col_id); project->SetDefaultVarName(0, v1_name); if (is_time) { @@ -1593,14 +1086,15 @@ void VariableSettingsDlg::OnOkClick(wxCommandEvent& event) v1_time = 0; } wxLogMessage(v1_name); + if (num_var >= 2) { if (lb2->GetSelection() == wxNOT_FOUND) { - wxString msg(_T("No field chosen for second variable.")); - wxMessageDialog dlg (this, msg, _T("Error"), wxOK | wxICON_ERROR); + wxString msg(_("No field chosen for second variable.")); + wxMessageDialog dlg (this, msg, _("Error"), wxOK | wxICON_ERROR); dlg.ShowModal(); return; } - v2_col_id = col_id_map[lb2->GetSelection()]; + v2_col_id = col_id_map[sel2_idx_map[lb2->GetSelection()]]; v2_name = table_int->GetColName(v2_col_id); project->SetDefaultVarName(1, v2_name); if (is_time) { @@ -1613,12 +1107,12 @@ void VariableSettingsDlg::OnOkClick(wxCommandEvent& event) } if (num_var >= 3) { if (lb3->GetSelection() == wxNOT_FOUND) { - wxString msg(_T("No field chosen for third variable.")); - wxMessageDialog dlg (this, msg, "Error", wxOK | wxICON_ERROR); + wxString msg(_("No field chosen for third variable.")); + wxMessageDialog dlg (this, msg, _("Error"), wxOK | wxICON_ERROR); dlg.ShowModal(); return; } - v3_col_id = col_id_map[lb3->GetSelection()]; + v3_col_id = col_id_map[sel3_idx_map[lb3->GetSelection()]]; v3_name = table_int->GetColName(v3_col_id); project->SetDefaultVarName(2, v3_name); if (is_time) { @@ -1631,12 +1125,12 @@ void VariableSettingsDlg::OnOkClick(wxCommandEvent& event) } if (num_var >= 4) { if (lb4->GetSelection() == wxNOT_FOUND) { - wxString msg(_T("No field chosen for fourth variable.")); - wxMessageDialog dlg (this, msg, "Error", wxOK | wxICON_ERROR); + wxString msg(_("No field chosen for fourth variable.")); + wxMessageDialog dlg (this, msg, _("Error"), wxOK | wxICON_ERROR); dlg.ShowModal(); return; } - v4_col_id = col_id_map[lb4->GetSelection()]; + v4_col_id = col_id_map[sel4_idx_map[lb4->GetSelection()]]; v4_name = table_int->GetColName(v4_col_id); project->SetDefaultVarName(3, v4_name); if (is_time) { @@ -1648,35 +1142,40 @@ void VariableSettingsDlg::OnOkClick(wxCommandEvent& event) wxLogMessage(v4_name); } - FillData(); - - if (show_weights) - project->GetWManInt()->MakeDefault(GetWeightsId()); - - if (GetDistanceMetric() != WeightsMetaInfo::DM_unspecified) { - project->SetDefaultDistMetric(GetDistanceMetric()); - } - if (GetDistanceUnits() != WeightsMetaInfo::DU_unspecified) { - project->SetDefaultDistUnits(GetDistanceUnits()); - } + wxString emptyVar = FillData(); + if (emptyVar.empty()== false) { + wxString msg = wxString::Format(_("The selected variable %s is not valid. If it's a grouped variable, please modify it in Time->Time Editor. Or please select another variable."), emptyVar); + wxMessageDialog dlg (this, msg.mb_str(), _("Invalid Variable"), wxOK | wxICON_ERROR); + dlg.ShowModal(); + + } else { - - bool check_group_var = true; - try { - for (int i=0; iGetTableInt()->GetColTypes(col_ids[i]); + if (show_weights) + project->GetWManInt()->MakeDefault(GetWeightsId()); + + if (GetDistanceMetric() != WeightsMetaInfo::DM_unspecified) { + project->SetDefaultDistMetric(GetDistanceMetric()); + } + if (GetDistanceUnits() != WeightsMetaInfo::DU_unspecified) { + project->SetDefaultDistUnits(GetDistanceUnits()); + } + + bool check_group_var = true; + try { + for (int i=0; iGetTableInt()->GetColTypes(col_ids[i]); + } + } catch(GdaException& ex) { + // place holder found + wxString msg = wxString::Format(_("The selected group variable should contains %d items. Please modify the group variable in Time->Time Editor, or select another variable."), project->GetTableInt()->GetTimeSteps()); + wxMessageDialog dlg (this, msg.mb_str(), _("Incomplete Group Variable"), wxOK | wxICON_ERROR); + dlg.ShowModal(); + check_group_var = false; } - } catch(GdaException& ex) { - // place holder found - wxString msg = wxString::Format(_T("The selected group variable should contains %d items. Please modify the group variable in Time Editor, or select another variable."), project->GetTableInt()->GetTimeSteps()); - wxMessageDialog dlg (this, msg.mb_str(), _T("Incomplete Group Variable"), wxOK | wxICON_ERROR); - dlg.ShowModal(); - check_group_var = false; - } - if (check_group_var == true) - EndDialog(wxID_OK); - + if (check_group_var == true) + EndDialog(wxID_OK); + } } // Theme choice for Rate Smoothed variable settings @@ -1804,82 +1303,215 @@ void VariableSettingsDlg::InitFieldChoices() if (num_var >= 3) lb3->Clear(); if (num_var >= 4) lb4->Clear(); + sel1_idx_map.clear(); + sel2_idx_map.clear(); + sel3_idx_map.clear(); + sel4_idx_map.clear(); + idx_sel1_map.clear(); + idx_sel2_map.clear(); + idx_sel3_map.clear(); + idx_sel4_map.clear(); + + int sel1_idx = 0; + int sel2_idx = 0; + int sel3_idx = 0; + int sel4_idx = 0; + for (int i=0, iend=col_id_map.size(); iGetColType(col_id_map[i]); wxString name = table_int->GetColName(col_id_map[i]); + if (table_int->IsColTimeVariant(col_id_map[i])) name << t1; - lb1->Append(name); + + if ((var1_str) || + (!var1_str && ftype == GdaConst::double_type) || + (!var1_str && ftype == GdaConst::long64_type)) + { + lb1->Append(name); + sel1_idx_map[sel1_idx] = i; + idx_sel1_map[i] = sel1_idx; + sel1_idx += 1; + } if (num_var >= 2) { wxString name = table_int->GetColName(col_id_map[i]); if (table_int->IsColTimeVariant(col_id_map[i])) name << t2; - lb2->Append(name); - } + if ((var2_str) || + (!var2_str && ftype == GdaConst::double_type) || + (!var2_str && ftype == GdaConst::long64_type)) + { + lb2->Append(name); + sel2_idx_map[sel2_idx] = i; + idx_sel2_map[i] = sel2_idx; + sel2_idx += 1; + } + } + if (num_var >= 3) { wxString name = table_int->GetColName(col_id_map[i]); if (table_int->IsColTimeVariant(col_id_map[i])) name << t3; - lb3->Append(name); + if ((var3_str) || + (!var3_str && ftype == GdaConst::double_type) || + (!var3_str && ftype == GdaConst::long64_type)) + { + lb3->Append(name); + sel3_idx_map[sel3_idx] = i; + idx_sel3_map[i] = sel3_idx; + sel3_idx += 1; + } } + if (num_var >= 4) { wxString name = table_int->GetColName(col_id_map[i]); if (table_int->IsColTimeVariant(col_id_map[i])) name << t4; - lb4->Append(name); + if ((var4_str) || + (!var4_str && ftype == GdaConst::double_type) || + (!var4_str && ftype == GdaConst::long64_type)) + { + lb4->Append(name); + sel4_idx_map[sel4_idx] = i; + idx_sel4_map[i] = sel4_idx; + sel4_idx += 1; + } } + } - int pos = lb1->GetScrollPos(wxVERTICAL); - lb1->SetSelection(lb1_cur_sel); - lb1->SetFirstItem(lb1->GetSelection()); - if (num_var >= 2) { + for (int i=0, iend=col_id_map.size(); iGetColName(col_id_map[i]); + if (item_str == default_var_name1) { + lb1_cur_sel = idx_sel1_map[i]; + if (set_second_from_first_mode && num_var >= 2) { + lb2_cur_sel = idx_sel1_map[i]; + } + } + if (num_var >= 2 && item_str == default_var_name2) { + if (!set_second_from_first_mode) { + lb2_cur_sel = idx_sel2_map[i]; + } + } + if (num_var >= 3 && item_str == default_var_name3){ + lb3_cur_sel = idx_sel3_map[i]; + if (set_fourth_from_third_mode && num_var >= 4) { + lb4_cur_sel = idx_sel3_map[i]; + } + } + if (num_var >= 4 && item_str == default_var_name4) { + if (!set_fourth_from_third_mode) { + lb4_cur_sel = idx_sel4_map[i]; + } + } + } + + if (sel1_idx > 0) { + int pos = lb1->GetScrollPos(wxVERTICAL); + lb1->SetSelection(lb1_cur_sel); + lb1->SetFirstItem(lb1->GetSelection()); + } + if (sel2_idx > 0 && num_var >= 2) { lb2->SetSelection(lb2_cur_sel); lb2->SetFirstItem(lb2->GetSelection()); } - if (num_var >= 3) { + if (sel3_idx > 0 && num_var >= 3) { lb3->SetSelection(lb3_cur_sel); lb3->SetFirstItem(lb3->GetSelection()); } - if (num_var >= 4) { + if (sel4_idx > 0 && num_var >= 4) { lb4->SetSelection(lb4_cur_sel); lb4->SetFirstItem(lb4->GetSelection()); } + + if (sel1_idx == 0 && sel2_idx == 0 && sel3_idx == 0 && sel4_idx == 0) { + wxString msg("No numeric variables found."); + wxMessageDialog dlg (this, msg, _("Warning"), wxOK | wxICON_WARNING); + dlg.ShowModal(); + } +} + +bool VariableSettingsDlg::CheckEmptyColumn(int col_id, int time) +{ + std::vector undefs; + table_int->GetColUndefined(col_id, time, undefs); + for (int i=0; i= 1) { - v1_col_id = col_id_map[lb1->GetSelection()]; + int sel_idx = lb1->GetSelection(); + int col_idx = sel1_idx_map[sel_idx]; + v1_col_id = col_id_map[col_idx]; v1_name = table_int->GetColName(v1_col_id); col_ids[0] = v1_col_id; var_info[0].time = v1_time; + + if (CheckEmptyColumn(v1_col_id, v1_time)) { + emptyVar = v1_name; + } } if (num_var >= 2) { - v2_col_id = col_id_map[lb2->GetSelection()]; + //v2_col_id = col_id_map[lb2->GetSelection()]; + int sel_idx = lb2->GetSelection(); + int col_idx = sel2_idx_map[sel_idx]; + v2_col_id = col_id_map[col_idx]; v2_name = table_int->GetColName(v2_col_id); col_ids[1] = v2_col_id; var_info[1].time = v2_time; + + if (emptyVar.empty() && CheckEmptyColumn(v2_col_id, v2_time)) { + emptyVar = v2_name; + } } if (num_var >= 3) { - v3_col_id = col_id_map[lb3->GetSelection()]; + //v3_col_id = col_id_map[lb3->GetSelection()]; + int sel_idx = lb3->GetSelection(); + int col_idx = sel3_idx_map[sel_idx]; + v3_col_id = col_id_map[col_idx]; v3_name = table_int->GetColName(v3_col_id); col_ids[2] = v3_col_id; var_info[2].time = v3_time; + + if (emptyVar.empty() && CheckEmptyColumn(v3_col_id, v3_time)) { + emptyVar = v3_name; + } } if (num_var >= 4) { - v4_col_id = col_id_map[lb4->GetSelection()]; + //v4_col_id = col_id_map[lb4->GetSelection()]; + int sel_idx = lb4->GetSelection(); + int col_idx = sel4_idx_map[sel_idx]; + v4_col_id = col_id_map[col_idx]; v4_name = table_int->GetColName(v4_col_id); col_ids[3] = v4_col_id; var_info[3].time = v4_time; + + if (emptyVar.empty() && CheckEmptyColumn(v4_col_id, v4_time)) { + emptyVar = v4_name; + } } - + + for (int i=0; iGetColName(col_ids[i]); var_info[i].is_time_variant = table_int->IsColTimeVariant(col_ids[i]); + + if (var_info[i].is_time_variant) { + int n_timesteps = table_int->GetColTimeSteps(col_ids[i]); + var_info[i].time_min = 0; + var_info[i].time_max = n_timesteps>0 ? n_timesteps - 1 : 0; + } // var_info[i].time already set above table_int->GetMinMaxVals(col_ids[i], var_info[i].min, var_info[i].max); @@ -1888,6 +1520,8 @@ void VariableSettingsDlg::FillData() } // Call function to set all Secondary Attributes based on Primary Attributes GdaVarTools::UpdateVarInfoSecondaryAttribs(var_info); - //GdaVarTools::PrintVarInfoVector(var_info); + GdaVarTools::PrintVarInfoVector(var_info); + + return emptyVar; } diff --git a/DialogTools/VariableSettingsDlg.h b/DialogTools/VariableSettingsDlg.h index 02b3f5270..cdb3570b1 100644 --- a/DialogTools/VariableSettingsDlg.h +++ b/DialogTools/VariableSettingsDlg.h @@ -42,7 +42,7 @@ class TableInterface; //////////////////////////////////////////////////////////////////////////// // -// +// class DiffMoranVarSettingDlg // //////////////////////////////////////////////////////////////////////////// class DiffMoranVarSettingDlg : public wxDialog @@ -80,81 +80,7 @@ class DiffMoranVarSettingDlg : public wxDialog //////////////////////////////////////////////////////////////////////////// // -// -// -//////////////////////////////////////////////////////////////////////////// - -class SimpleReportTextCtrl : public wxTextCtrl -{ -public: - SimpleReportTextCtrl(wxWindow* parent, wxWindowID id, const wxString& value = "", - const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, - long style = 0, const wxValidator& validator = wxDefaultValidator, - const wxString& name = wxTextCtrlNameStr) - : wxTextCtrl(parent, id, value, pos, size, style, validator, name) {} -protected: - void OnContextMenu(wxContextMenuEvent& event); - void OnSaveClick( wxCommandEvent& event ); - DECLARE_EVENT_TABLE() -}; - -class PCASettingsDlg : public wxDialog, public FramesManagerObserver -{ -public: - PCASettingsDlg(Project* project); - virtual ~PCASettingsDlg(); - - void CreateControls(); - bool Init(); - - void OnOK( wxCommandEvent& event ); - void OnSave( wxCommandEvent& event ); - void OnCloseClick( wxCommandEvent& event ); - void OnClose(wxCloseEvent& ev); - void OnMethodChoice( wxCommandEvent& event ); - - void InitVariableCombobox(wxListBox* var_box); - - //boost::uuids::uuid GetWeightsId(); - - /** Implementation of FramesManagerObserver interface */ - virtual void update(FramesManager* o); - - std::vector var_info; - std::vector col_ids; - -private: - FramesManager* frames_manager; - - Project* project; - TableInterface* table_int; - std::vector tm_strs; - //std::vector weights_ids; - - wxListBox* combo_var; - wxChoice* combo_n; - - SimpleReportTextCtrl* m_textbox; - wxButton *saveButton; - - wxChoice* combo_method; - wxChoice* combo_transform; - - - std::map name_to_nm; - std::map name_to_tm_id; - - unsigned int row_lim; - unsigned int col_lim; - std::vector scores; - float thresh95; - - DECLARE_EVENT_TABLE() -}; - -//////////////////////////////////////////////////////////////////////////// -// -// +// class MultiVariableSettingsDlg // //////////////////////////////////////////////////////////////////////////// class MultiVariableSettingsDlg : public wxDialog @@ -196,17 +122,18 @@ class MultiVariableSettingsDlg : public wxDialog //////////////////////////////////////////////////////////////////////////// // -// +// class VariableSettingsDlg // //////////////////////////////////////////////////////////////////////////// + class VariableSettingsDlg: public wxDialog { public: enum VarType { univariate, bivariate, trivariate, quadvariate, rate_smoothed }; - + VariableSettingsDlg( Project* project, VarType v_type, bool show_weights = false, bool show_distance = false, @@ -217,7 +144,11 @@ class VariableSettingsDlg: public wxDialog const wxString& var4_title=_("Fourth Variable"), bool set_second_from_first_mode = false, bool set_fourth_from_third_mode = false, - bool hide_time = false); + bool hide_time = false, + bool var1_str = false, // if show string fields + bool var2_str = false, + bool var3_str = false, + bool var4_str = false); virtual ~VariableSettingsDlg(); void CreateControls(); void Init(VarType var_type); @@ -247,14 +178,31 @@ class VariableSettingsDlg: public wxDialog WeightsMetaInfo::DistanceMetricEnum GetDistanceMetric(); WeightsMetaInfo::DistanceUnitsEnum GetDistanceUnits(); -private: +protected: int m_theme; // for rate_smoothed + bool var1_str; + bool var2_str; + bool var3_str; + bool var4_str; + std::map sel1_idx_map; + std::map sel2_idx_map; + std::map sel3_idx_map; + std::map sel4_idx_map; + std::map idx_sel1_map; + std::map idx_sel2_map; + std::map idx_sel3_map; + std::map idx_sel4_map; + bool hide_time; wxString v1_name; wxString v2_name; wxString v3_name; wxString v4_name; + wxString default_var_name1; + wxString default_var_name2; + wxString default_var_name3; + wxString default_var_name4; int v1_time; int v2_time; int v3_time; @@ -311,7 +259,9 @@ class VariableSettingsDlg: public wxDialog void InitTimeChoices(); void InitFieldChoices(); - void FillData(); + wxString FillData(); + + bool CheckEmptyColumn(int col_id, int time); /** Automatically set the second variable to the same value as the first variable when first variable is changed. */ @@ -323,4 +273,97 @@ class VariableSettingsDlg: public wxDialog DECLARE_EVENT_TABLE() }; +/* +class UniVarSettingsDlg: public VariableSettingsDlg +{ + UniVarSettingsDlg(Project* project, + VarType v_type, + bool show_weights = false, + bool show_distance = false, + bool show_time = true, + bool var1_str = false // if show string fields + ); + virtual ~UniVarSettingsDlg(); + + virtual void CreateControls(); + virtual void InitFieldChoices(); + virtual void FillData(); + + void OnOkClick( wxCommandEvent& event ); +}; + + +class BiVarSettingsDlg: public VariableSettingsDlg +{ + BiVarSettingsDlg(Project* project, + VarType v_type, + bool show_weights = false, + bool show_distance = false, + bool show_time = true, + bool var1_str = false, // if show string fields + bool var2_str = false, // if show string fields + bool set_second_from_first_mode = false); + virtual ~BiVarSettingsDlg(); + + virtual void CreateControls(); + virtual void InitFieldChoices(); + virtual void FillData(); + + void OnOkClick( wxCommandEvent& event ); +}; + +class TriVarSettingsDlg: public VariableSettingsDlg +{ + TriVarSettingsDlg(Project* project, + VarType v_type, + bool show_weights = false, + bool show_distance = false, + bool show_time = true, + bool var1_str = false, // if show string fields + bool var2_str = false, // if show string fields + bool var3_str = false); + virtual ~TriVarSettingsDlg(); + + virtual void CreateControls(); + virtual void InitFieldChoices(); + virtual void FillData(); + + void OnOkClick( wxCommandEvent& event ); +}; + +class QuadVarSettingsDlg: public VariableSettingsDlg +{ + QuadVarSettingsDlg(Project* project, + VarType v_type, + bool show_weights = false, + bool show_distance = false, + bool show_time = true, + bool var1_str = false, // if show string fields + bool var2_str = false, // if show string fields + bool var3_str = false); + virtual ~QuadVarSettingsDlg(); + + virtual void CreateControls(); + virtual void InitFieldChoices(); + virtual void FillData(); + + void OnOkClick( wxCommandEvent& event ); +}; + +class RateSmoothedSettingsDlg: public VariableSettingsDlg +{ + RateSmoothedSettingsDlg(Project* project, + VarType v_type, + bool show_weights = false, + bool show_time = true + ); + virtual ~RateSmoothedSettingsDlg(); + + virtual void CreateControls(); + virtual void InitFieldChoices(); + virtual void FillData(); + + void OnOkClick( wxCommandEvent& event ); +}; +*/ #endif diff --git a/DialogTools/WebViewHelpWin.h b/DialogTools/WebViewHelpWin.h index 8acbb88fd..afb2273de 100644 --- a/DialogTools/WebViewHelpWin.h +++ b/DialogTools/WebViewHelpWin.h @@ -38,7 +38,7 @@ class WebViewHelpWin: public wxFrame, public FramesManagerObserver WebViewHelpWin(Project* project, const wxString& page_source, wxWindow* parent, wxWindowID id = wxID_ANY, - const wxString& title = "GeoDa Help", + const wxString& title = _("GeoDa Help"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize); virtual ~WebViewHelpWin(); diff --git a/DialogTools/WeightsManDlg.cpp b/DialogTools/WeightsManDlg.cpp index f524f6817..5e825b419 100644 --- a/DialogTools/WeightsManDlg.cpp +++ b/DialogTools/WeightsManDlg.cpp @@ -39,6 +39,9 @@ #include "../ShapeOperations/WeightsManager.h" #include "../logger.h" #include "../GeoDa.h" +#include "../io/arcgis_swm.h" +#include "../io/matlab_mat.h" +#include "../io/weights_interface.h" #include "WeightsManDlg.h" BEGIN_EVENT_TABLE(WeightsManFrame, TemplateFrame) @@ -62,26 +65,29 @@ create_btn(0), load_btn(0), remove_btn(0), w_list(0) panel->SetBackgroundColour(*wxWHITE); SetBackgroundColour(*wxWHITE); - create_btn = new wxButton(panel, XRCID("ID_CREATE_BTN"), "Create", wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT); + create_btn = new wxButton(panel, XRCID("ID_CREATE_BTN"), _("Create"), wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT); - load_btn = new wxButton(panel, XRCID("ID_LOAD_BTN"), "Load", wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT); + load_btn = new wxButton(panel, XRCID("ID_LOAD_BTN"), _("Load"), wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT); - remove_btn = new wxButton(panel, XRCID("ID_REMOVE_BTN"), "Remove", wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT); + remove_btn = new wxButton(panel, XRCID("ID_REMOVE_BTN"), _("Remove"), wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT); - histogram_btn = new wxButton(panel, XRCID("ID_HISTOGRAM_BTN"), "Histogram", wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT); + histogram_btn = new wxButton(panel, XRCID("ID_HISTOGRAM_BTN"), _("Histogram"), wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT); - connectivity_map_btn = new wxButton(panel, XRCID("ID_CONNECT_MAP_BTN"), "Connectivity Map", wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT); + connectivity_map_btn = new wxButton(panel, XRCID("ID_CONNECT_MAP_BTN"), _("Connectivity Map"), wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT); + + connectivity_graph_btn = new wxButton(panel, XRCID("ID_CONNECT_GRAPH_BTN"), _("Connectivity Graph"), wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT); Connect(XRCID("ID_CREATE_BTN"), wxEVT_BUTTON, wxCommandEventHandler(WeightsManFrame::OnCreateBtn)); Connect(XRCID("ID_LOAD_BTN"), wxEVT_BUTTON, wxCommandEventHandler(WeightsManFrame::OnLoadBtn)); Connect(XRCID("ID_REMOVE_BTN"), wxEVT_BUTTON, wxCommandEventHandler(WeightsManFrame::OnRemoveBtn)); Connect(XRCID("ID_HISTOGRAM_BTN"), wxEVT_BUTTON, wxCommandEventHandler(WeightsManFrame::OnHistogramBtn)); Connect(XRCID("ID_CONNECT_MAP_BTN"), wxEVT_BUTTON, wxCommandEventHandler(WeightsManFrame::OnConnectMapBtn)); + Connect(XRCID("ID_CONNECT_GRAPH_BTN"), wxEVT_BUTTON, wxCommandEventHandler(WeightsManFrame::OnConnectGraphBtn)); w_list = new wxListCtrl(panel, XRCID("ID_W_LIST"), wxDefaultPosition, wxSize(-1, 100), wxLC_REPORT); // Note: search for "ungrouped_list" for examples of wxListCtrl usage. - w_list->AppendColumn("Weights Name"); + w_list->AppendColumn(_("Weights Name")); w_list->SetColumnWidth(TITLE_COL, 300); InitWeightsList(); @@ -106,6 +112,8 @@ create_btn(0), load_btn(0), remove_btn(0), w_list(0) btns_row2_h_szr->Add(histogram_btn, 0, wxALIGN_CENTER_VERTICAL); btns_row2_h_szr->AddSpacer(5); btns_row2_h_szr->Add(connectivity_map_btn, 0, wxALIGN_CENTER_VERTICAL); + btns_row2_h_szr->AddSpacer(5); + btns_row2_h_szr->Add(connectivity_graph_btn, 0, wxALIGN_CENTER_VERTICAL); btns_row2_h_szr->AddSpacer(5); @@ -125,19 +133,6 @@ create_btn(0), load_btn(0), remove_btn(0), w_list(0) panel->SetSizer(panel_h_szr); - - //wxBoxSizer* right_v_szr = new wxBoxSizer(wxVERTICAL); - //conn_hist_canvas = new ConnectivityHistCanvas(this, this, project, boost::uuids::nil_uuid()); - //right_v_szr->Add(conn_hist_canvas, 1, wxEXPAND); - - // We have decided not to display the ConnectivityMapCanvas. Uncomment - // the following 4 lines to re-enable for shape-enabled projects. - //if (!project->IsTableOnlyProject()) { - // conn_map_canvas = new ConnectivityMapCanvas(this, this, project, - // boost::uuids::nil_uuid()); - // right_v_szr->Add(conn_map_canvas, 1, wxEXPAND); - //} - boost::uuids::uuid default_id = w_man_int->GetDefault(); SelectId(default_id); UpdateButtons(); @@ -174,12 +169,54 @@ void WeightsManFrame::OnHistogramBtn(wxCommandEvent& ev) ConnectivityHistFrame* f = new ConnectivityHistFrame(this, project_p, id); } +wxString WeightsManFrame::GetMapTitle(wxString title, boost::uuids::uuid w_id) +{ + wxString weights_title = w_man_int->GetTitle(w_id); + wxString map_title = _("%s (Weights: %s)"); + map_title = wxString::Format(map_title, title, weights_title); + return map_title; +} + void WeightsManFrame::OnConnectMapBtn(wxCommandEvent& ev) { wxLogMessage("WeightsManFrame::OnConnectMapBtn()"); - boost::uuids::uuid id = GetHighlightId(); - if (id.is_nil()) return; - ConnectivityMapFrame* f = new ConnectivityMapFrame(this, project_p, id, wxDefaultPosition, GdaConst::conn_map_default_size); + boost::uuids::uuid w_id = GetHighlightId(); + if (w_id.is_nil()) return; + + std::vector col_ids; + std::vector var_info; + MapFrame* nf = new MapFrame(this, project_p, + var_info, col_ids, + CatClassification::no_theme, + MapCanvas::no_smoothing, 1, + w_id, + wxPoint(80,160), + GdaConst::map_default_size); + wxString title = GetMapTitle(_("Connectivity Map"), w_id); + nf->SetTitle(title); + ev.SetString("Connectivity"); + nf->OnAddNeighborToSelection(ev); +} + +void WeightsManFrame::OnConnectGraphBtn(wxCommandEvent& ev) +{ + wxLogMessage("WeightsManFrame::OnConnectGraphBtn()"); + boost::uuids::uuid w_id = GetHighlightId(); + if (w_id.is_nil()) return; + + std::vector col_ids; + std::vector var_info; + MapFrame* nf = new MapFrame(this, project_p, + var_info, col_ids, + CatClassification::no_theme, + MapCanvas::no_smoothing, 1, + w_id, + wxPoint(80,160), + GdaConst::map_default_size); + wxString title = GetMapTitle(_("Connectivity Graph"), w_id); + nf->SetTitle(title); + ev.SetString("Connectivity"); + nf->OnDisplayWeightsGraph(ev); } void WeightsManFrame::OnActivate(wxActivateEvent& event) @@ -221,25 +258,36 @@ void WeightsManFrame::OnLoadBtn(wxCommandEvent& ev) wxLogMessage("In WeightsManFrame::OnLoadBtn"); wxFileName default_dir = project_p->GetWorkingDir(); wxString default_path = default_dir.GetPath(); - wxFileDialog dlg( this, "Choose Weights File", default_path, "", - "Weights Files (*.gal, *.gwt)|*.gal;*.gwt"); + wxFileDialog dlg( this, _("Choose Weights File"), default_path, "", + "Weights Files (*.gal, *.gwt, *.kwt, *.swm, *.mat)|*.gal;*.gwt;*.kwt;*.swm;*.mat"); if (dlg.ShowModal() != wxID_OK) return; wxString path = dlg.GetPath(); wxString ext = GenUtils::GetFileExt(path).Lower(); - if (ext != "gal" && ext != "gwt") { - wxString msg("Only 'gal' and 'gwt' weights files supported."); - wxMessageDialog dlg(this, msg, "Error", wxOK|wxICON_ERROR); + if (ext != "gal" && ext != "gwt" && ext != "kwt" && ext != "mat" && ext != "swm") { + wxString msg = _("Only 'gal', 'gwt', 'kwt', 'mat' and 'swm' weights files supported."); + wxMessageDialog dlg(this, msg, _("Error"), wxOK|wxICON_ERROR); dlg.ShowModal(); return; } WeightsMetaInfo wmi; - wxString id_field = WeightUtils::ReadIdField(path); + wxString id_field; + if (ext == "mat") { + id_field = "Unknown"; + } else if (ext == "swm") { + id_field = ReadIdFieldFromSwm(path); + } else { + id_field = WeightUtils::ReadIdField(path); + } wmi.SetToCustom(id_field); - wmi.filename = path; + wmi.filename = path; + if (path.EndsWith("kwt")) { + wmi.weights_type = WeightsMetaInfo::WT_kernel; + } + suspend_w_man_state_updates = true; // Check if weights already loaded and simply select and set as @@ -257,36 +305,80 @@ void WeightsManFrame::OnLoadBtn(wxCommandEvent& ev) } GalElement* tempGal = 0; - if (ext == "gal") { - tempGal = WeightUtils::ReadGal(path, table_int); - } else { - tempGal = WeightUtils::ReadGwtAsGal(path, table_int); - } + try { + if (ext == "gal") { + tempGal = WeightUtils::ReadGal(path, table_int); + } else if (ext == "swm") { + tempGal = ReadSwmAsGal(path, table_int); + } else if (ext == "mat") { + tempGal = ReadMatAsGal(path, table_int); + } else { + tempGal = WeightUtils::ReadGwtAsGal(path, table_int); + } + } catch (WeightsMismatchObsException& e) { + wxString msg = _("The number of observations specified in chosen weights file is incompatible with current Table."); + wxMessageDialog dlg(NULL, msg, _("Error"), wxOK | wxICON_ERROR); + dlg.ShowModal(); + tempGal = 0; + } catch (WeightsIntegerKeyNotFoundException& e) { + wxString msg = _("Specified key (%d) not found in currently loaded Table."); + msg = wxString::Format(msg, e.key); + wxMessageDialog dlg(NULL, msg, _("Error"), wxOK | wxICON_ERROR); + dlg.ShowModal(); + tempGal = 0; + } catch (WeightsStringKeyNotFoundException& e) { + wxString msg = _("Specified key (%s) not found in currently loaded Table."); + msg = wxString::Format(msg, e.key); + wxMessageDialog dlg(NULL, msg, _("Error"), wxOK | wxICON_ERROR); + dlg.ShowModal(); + tempGal = 0; + } catch (WeightsIdNotFoundException& e) { + wxString msg = _("Specified id field (%s) not found in currently loaded Table."); + msg = wxString::Format(msg, e.id); + wxMessageDialog dlg(NULL, msg, _("Error"), wxOK | wxICON_ERROR); + dlg.ShowModal(); + tempGal = 0; + } catch (WeightsNotValidException& e) { + wxString msg = _("Weights file/format is not valid."); + wxMessageDialog dlg(NULL, msg, _("Error"), wxOK | wxICON_ERROR); + dlg.ShowModal(); + tempGal = 0; + } + if (tempGal == NULL) { // WeightsUtils read functions already reported any issues // to user when NULL returned. suspend_w_man_state_updates = false; return; } + + GalWeight* gw = new GalWeight(); + gw->num_obs = table_int->GetNumberRows(); + gw->wflnm = wmi.filename; + gw->id_field = id_field; + gw->gal = tempGal; + + gw->GetNbrStats(); + wmi.num_obs = gw->GetNumObs(); + wmi.SetMinNumNbrs(gw->GetMinNumNbrs()); + wmi.SetMaxNumNbrs(gw->GetMaxNumNbrs()); + wmi.SetMeanNumNbrs(gw->GetMeanNumNbrs()); + wmi.SetMedianNumNbrs(gw->GetMedianNumNbrs()); + wmi.SetSparsity(gw->GetSparsity()); + wmi.SetDensity(gw->GetDensity()); id = w_man_int->RequestWeights(wmi); if (id.is_nil()) { - wxString msg("There was a problem requesting the weights file."); - wxMessageDialog dlg(this, msg, "Error", wxOK|wxICON_ERROR); + wxString msg = _("There was a problem requesting the weights file."); + wxMessageDialog dlg(this, msg, _("Error"), wxOK|wxICON_ERROR); dlg.ShowModal(); suspend_w_man_state_updates = false; return; } - GalWeight* gw = new GalWeight(); - gw->num_obs = table_int->GetNumberRows(); - gw->wflnm = wmi.filename; - gw->id_field = id_field; - gw->gal = tempGal; - if (!((WeightsNewManager*) w_man_int)->AssociateGal(id, gw)) { - wxString msg("There was a problem associating the weights file."); - wxMessageDialog dlg(this, msg, "Error", wxOK|wxICON_ERROR); + wxString msg = _("There was a problem associating the weights file."); + wxMessageDialog dlg(this, msg, _("Error"), wxOK|wxICON_ERROR); dlg.ShowModal(); delete gw; suspend_w_man_state_updates = false; @@ -310,26 +402,23 @@ void WeightsManFrame::OnRemoveBtn(wxCommandEvent& ev) if (id.is_nil()) return; int nb = w_man_state->NumBlockingRemoveId(id); if (nb > 0) { - wxString msg; - msg << "There " << (nb==1 ? "is" : "are") << " "; - if (nb==1) { msg << "one"; } else { msg << nb; } - msg << " other " << (nb==1 ? "view" : "views"); - msg << " open that depend" << (nb==1 ? "s" : ""); - msg << " on this matrix. "; - msg << "OK to close " << (nb==1 ? "this view" : "these views"); - msg << " and remove?"; - wxMessageDialog dlg(this, msg, "Notice", - wxYES_NO | wxNO_DEFAULT | wxICON_QUESTION); + wxString msg = _("There is one other view open that depends on this matrix. Ok to close this view and remove?"); + if (nb > 1) { + wxString tmp = _("There is at least one view open that depends on this matrix. Ok to close these views and remove?"); + msg = wxString::Format(tmp, nb); + } + wxMessageDialog dlg(this, msg, _("Notice"), wxYES_NO | wxNO_DEFAULT | wxICON_QUESTION); if (dlg.ShowModal() == wxID_YES) { w_man_state->closeObservers(id, this); int nb = w_man_state->NumBlockingRemoveId(id); if (nb > 0) { // there was a problem closing some views - wxString s; - s << nb << " " << (nb==1 ? "view" : "views"); - s << " could not be closed. "; - s << "Please manually close and try again."; - wxMessageDialog dlg(this, s, "Error", wxICON_ERROR | wxOK); + wxString s = _("There is a view could not be closed. Please manually close and try again."); + if (nb > 1) { + wxString tmp = _("There is at least one view could not be closed. Please manually close and try again."); + s = wxString::Format(tmp, nb); + } + wxMessageDialog dlg(this, s, _("Error"), wxICON_ERROR | wxOK); dlg.ShowModal(); } else { w_man_int->Remove(id); @@ -338,7 +427,7 @@ void WeightsManFrame::OnRemoveBtn(wxCommandEvent& ev) } else { w_man_int->Remove(id); } - LOG_MSG("Exiting WeightsManFrame::OnRemoveBtn"); + wxLogMessage("Exiting WeightsManFrame::OnRemoveBtn"); } /** Implementation of WeightsManStateObserver interface */ @@ -459,62 +548,136 @@ void WeightsManFrame::SetDetailsForId(boost::uuids::uuid id) WeightsMetaInfo wmi = w_man_int->GetMetaInfo(id); - row_title.push_back("type"); + row_title.push_back(_("type")); row_content.push_back(wmi.TypeToStr()); + + if (wmi.TypeToStr() == "kernel") { + row_title.push_back(_("kernel method")); + if (wmi.kernel.IsEmpty()) + row_content.push_back(_("unknown")); + else + row_content.push_back(wmi.kernel); + + if (wmi.bandwidth >0) { + row_title.push_back(_("bandwidth")); + wxString ss; + ss << wmi.bandwidth; + row_content.push_back(ss); + } else if (wmi.k > 0) { + row_title.push_back("knn"); + wxString ss; + ss << wmi.k; + row_content.push_back(ss); + if (wmi.is_adaptive_kernel) { + row_title.push_back(_("adaptive kernel")); + row_content.push_back( wmi.is_adaptive_kernel? _("true"):_("false")); + } + } + + if (!wmi.kernel.IsEmpty()) { + row_title.push_back(_("kernel to diagonal")); + row_content.push_back( wmi.use_kernel_diagnals ? _("true"):_("false")); + } + } else { + if (wmi.power < 0) { + row_title.push_back(_("inverse distance")); + row_content.push_back(_("true")); + row_title.push_back(_("power")); + wxString ss; + ss << -wmi.power; + row_content.push_back(ss); + } + } - row_title.push_back("symmetry"); + row_title.push_back(_("symmetry")); row_content.push_back(wmi.SymToStr()); - row_title.push_back("file"); + row_title.push_back(_("file")); if (wmi.filename.IsEmpty()) { - row_content.push_back("not saved"); + row_content.push_back(_("not saved")); } else { wxFileName fm(wmi.filename); row_content.push_back(fm.GetFullName()); } - row_title.push_back("id variable"); + row_title.push_back(_("id variable")); row_content.push_back(wmi.id_var); if (wmi.weights_type == WeightsMetaInfo::WT_rook || wmi.weights_type == WeightsMetaInfo::WT_queen) { - row_title.push_back("order"); + row_title.push_back(_("order")); wxString rs; rs << wmi.order; row_content.push_back(rs); if (wmi.order > 1) { - row_title.push_back("include lower orders"); + row_title.push_back(_("include lower orders")); if (wmi.inc_lower_orders) { - row_content.push_back("true"); + row_content.push_back(_("true")); } else { - row_content.push_back("false"); + row_content.push_back(_("false")); } } } else if (wmi.weights_type == WeightsMetaInfo::WT_knn || wmi.weights_type == WeightsMetaInfo::WT_threshold) { - row_title.push_back("distance metric"); + row_title.push_back(_("distance metric")); row_content.push_back(wmi.DistMetricToStr()); - row_title.push_back("distance vars"); + row_title.push_back(_("distance vars")); row_content.push_back(wmi.DistValsToStr()); if (wmi.weights_type == WeightsMetaInfo::WT_threshold) { - row_title.push_back("distance unit"); + row_title.push_back(_("distance unit")); row_content.push_back(wmi.DistUnitsToStr()); } if (wmi.weights_type == WeightsMetaInfo::WT_knn) { - row_title.push_back("neighbors"); + row_title.push_back(_("neighbors")); wxString rs; rs << wmi.num_neighbors; row_content.push_back(rs); } else { - row_title.push_back("threshold value"); + row_title.push_back(_("threshold value")); wxString rs; rs << wmi.threshold_val; row_content.push_back(rs); } } + row_title.push_back(_("# observations")); + if (wmi.num_obs >= 0) + row_content.push_back(wxString::Format("%d", wmi.num_obs)); + else + row_content.push_back(_("unknown")); + + row_title.push_back(_("min neighbors")); + if (wmi.min_nbrs>=0) + row_content.push_back(wxString::Format("%d", wmi.min_nbrs)); + else + row_content.push_back(_("unknown")); + + row_title.push_back(_("max neighbors")); + if (wmi.max_nbrs >= 0) + row_content.push_back(wxString::Format("%d", wmi.max_nbrs)); + else + row_content.push_back(_("unknown")); + + row_title.push_back(_("mean neighbors")); + if (wmi.mean_nbrs>=0) + row_content.push_back(wxString::Format("%.2f", wmi.mean_nbrs)); + else + row_content.push_back(_("unknown")); + + row_title.push_back(_("median neighbors")); + if (wmi.median_nbrs >=0) + row_content.push_back(wxString::Format("%.2f", wmi.median_nbrs)); + else + row_content.push_back(_("unknown")); + + wxString sp = _("unknown"); + if (wmi.density_val>=0) + sp = wxString::Format("%.2f%%", wmi.density_val); + row_title.push_back(_("% non-zero")); + row_content.push_back(sp); + SetDetailsWin(row_title, row_content); } @@ -568,8 +731,8 @@ void WeightsManFrame::SetDetailsWin(const std::vector& row_title, s << ""; s << "
    PropertyValue" << _("Property") << "" << _("Value") << "
    "; s << " "; - s << " "; - s << " "; + s << " "; + s << " "; s << " "; for (size_t i=0, last=row_title.size()-1; i" : ""); @@ -601,6 +764,12 @@ void WeightsManFrame::SelectId(boost::uuids::uuid id) { w_man_int->MakeDefault(id); SetDetailsForId(id); + + if (w_man_state) { + w_man_state->SetAddEvtTyp(id); + w_man_state->notifyObservers(this); + } + if (conn_hist_canvas) conn_hist_canvas->ChangeWeights(id); if (conn_map_canvas) conn_map_canvas->ChangeWeights(id); } @@ -639,8 +808,10 @@ void WeightsManFrame::UpdateButtons() if (remove_btn) remove_btn->Enable(any_sel); if (histogram_btn) histogram_btn->Enable(any_sel); if (connectivity_map_btn) connectivity_map_btn->Enable(any_sel); + if (connectivity_graph_btn) connectivity_graph_btn->Enable(any_sel); if (project_p->isTableOnly) { connectivity_map_btn->Disable(); + connectivity_graph_btn->Disable(); } } diff --git a/DialogTools/WeightsManDlg.h b/DialogTools/WeightsManDlg.h index 7addfbda7..f7cc9db2d 100644 --- a/DialogTools/WeightsManDlg.h +++ b/DialogTools/WeightsManDlg.h @@ -49,7 +49,7 @@ class WeightsManFrame : public TemplateFrame, public WeightsManStateObserver { public: WeightsManFrame(wxFrame *parent, Project* project, - const wxString& title = "Weights Manager", + const wxString& title = _("Weights Manager"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = GdaConst::weights_man_dlg_default_size, const long style = wxDEFAULT_FRAME_STYLE); @@ -65,6 +65,7 @@ class WeightsManFrame : public TemplateFrame, public WeightsManStateObserver void OnRemoveBtn(wxCommandEvent& ev); void OnHistogramBtn(wxCommandEvent& ev); void OnConnectMapBtn(wxCommandEvent& ev); + void OnConnectGraphBtn(wxCommandEvent& ev); /** Implementation of WeightsManStateObserver interface */ virtual void update(WeightsManState* o); @@ -78,7 +79,7 @@ class WeightsManFrame : public TemplateFrame, public WeightsManStateObserver void OnSaveConnectivityToTable(wxCommandEvent& event); void OnSelectIsolates(wxCommandEvent& event); -private: +protected: void InitWeightsList(); void SetDetailsForId(boost::uuids::uuid id); void SetDetailsWin(const std::vector& row_title, @@ -86,6 +87,7 @@ class WeightsManFrame : public TemplateFrame, public WeightsManStateObserver void SelectId(boost::uuids::uuid id); void HighlightId(boost::uuids::uuid id); boost::uuids::uuid GetHighlightId(); + wxString GetMapTitle(wxString title, boost::uuids::uuid id); void UpdateButtons(); ConnectivityHistCanvas* conn_hist_canvas; @@ -95,6 +97,7 @@ class WeightsManFrame : public TemplateFrame, public WeightsManStateObserver wxPanel* panel; wxButton* histogram_btn; // wxButton* connectivity_map_btn; // + wxButton* connectivity_graph_btn; // wxButton* create_btn; // ID_CREATE_BTN wxButton* load_btn; // ID_LOAD_BTN wxButton* remove_btn; // ID_REMOVE_BTN diff --git a/Explore/3DPlotView.cpp b/Explore/3DPlotView.cpp index 21f7269f8..1c7f25846 100644 --- a/Explore/3DPlotView.cpp +++ b/Explore/3DPlotView.cpp @@ -941,6 +941,15 @@ wxString C3DPlotCanvas::GetCanvasTitle() return s; } +wxString C3DPlotCanvas::GetVariableNames() +{ + wxString s; + s << GetNameWithTime(0) << ", "; + s << GetNameWithTime(1) << ", "; + s << GetNameWithTime(2); + return s; +} + wxString C3DPlotCanvas::GetNameWithTime(int var) { if (var < 0 || var >= var_info.size()) return wxEmptyString; @@ -1098,6 +1107,8 @@ C3DPlotFrame::C3DPlotFrame(wxFrame *parent, Project* project, control->template_frame = this; m_splitter->SplitVertically(control, canvas, 70); UpdateTitle(); + + SetMinSize(wxSize(600,400)); Show(true); } @@ -1132,7 +1143,7 @@ void C3DPlotFrame::MapMenus() LoadMenu("ID_3D_PLOT_VIEW_MENU_OPTIONS"); canvas->AddTimeVariantOptionsToMenu(optMenu); canvas->SetCheckMarks(optMenu); - GeneralWxUtils::ReplaceMenu(mb, "Options", optMenu); + GeneralWxUtils::ReplaceMenu(mb, _("Options"), optMenu); UpdateOptionMenuItems(); } @@ -1140,7 +1151,7 @@ void C3DPlotFrame::UpdateOptionMenuItems() { TemplateFrame::UpdateOptionMenuItems(); // set common items first wxMenuBar* mb = GdaFrame::GetGdaFrame()->GetMenuBar(); - int menu = mb->FindMenu("Options"); + int menu = mb->FindMenu(_("Options")); if (menu == wxNOT_FOUND) { } else { canvas->SetCheckMarks(mb->GetMenu(menu)); diff --git a/Explore/3DPlotView.h b/Explore/3DPlotView.h index 21a3129bb..5fa1c2d1e 100644 --- a/Explore/3DPlotView.h +++ b/Explore/3DPlotView.h @@ -53,6 +53,7 @@ class C3DPlotCanvas: public wxGLCanvas, public HighlightStateObserver virtual void AddTimeVariantOptionsToMenu(wxMenu* menu); virtual void SetCheckMarks(wxMenu* menu); virtual wxString GetCanvasTitle(); + virtual wxString GetVariableNames(); virtual wxString GetNameWithTime(int var); virtual void TimeChange(); void VarInfoAttributeChange(); diff --git a/Explore/AbstractClusterMap.cpp b/Explore/AbstractClusterMap.cpp new file mode 100644 index 000000000..870f07810 --- /dev/null +++ b/Explore/AbstractClusterMap.cpp @@ -0,0 +1,844 @@ +/** + * GeoDa TM, Copyright (C) 2011-2015 by Luc Anselin - all rights reserved + * + * This file is part of GeoDa. + * + * GeoDa is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * GeoDa is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include +#include +#include +#include +#include +#include +#include "../DataViewer/TableInterface.h" +#include "../DataViewer/TimeState.h" +#include "../GeneralWxUtils.h" +#include "../GeoDa.h" +#include "../logger.h" +#include "../Project.h" +#include "../DialogTools/PermutationCounterDlg.h" +#include "../DialogTools/SaveToTableDlg.h" +#include "../DialogTools/VariableSettingsDlg.h" +#include "../DialogTools/RandomizationDlg.h" +#include "../VarCalc/WeightsManInterface.h" + +#include "ConditionalClusterMapView.h" +#include "AbstractCoordinator.h" +#include "AbstractClusterMap.h" + + +IMPLEMENT_CLASS(AbstractMapCanvas, MapCanvas) +BEGIN_EVENT_TABLE(AbstractMapCanvas, MapCanvas) + EVT_PAINT(TemplateCanvas::OnPaint) + EVT_ERASE_BACKGROUND(TemplateCanvas::OnEraseBackground) + EVT_MOUSE_EVENTS(TemplateCanvas::OnMouseEvent) + EVT_MOUSE_CAPTURE_LOST(TemplateCanvas::OnMouseCaptureLostEvent) +END_EVENT_TABLE() + +using namespace std; + +AbstractMapCanvas::AbstractMapCanvas(wxWindow *parent, TemplateFrame* t_frame, + Project* project, + AbstractCoordinator* a_coordinator, + CatClassification::CatClassifType theme_type_s, + bool is_clust_s, + const wxPoint& pos, const wxSize& size) +:MapCanvas(parent, t_frame, project, + vector(0), vector(0), + CatClassification::no_theme, + no_smoothing, 1, boost::uuids::nil_uuid(), pos, size), +a_coord(a_coordinator), +is_clust(is_clust_s), +str_not_sig(_("Not Significant")), +str_undefined(_("Undefined")), +str_neighborless(_("Neighborless")), +str_p005("p = 0.05"), +str_p001("p = 0.01"), +str_p0001("p = 0.001"), +str_p00001("p = 0.0001"), +clr_not_sig_point(wxColour(190, 190, 190)), +clr_not_sig_polygon(wxColour(240, 240, 240)) +{ + wxLogMessage("Entering AbstractMapCanvas::AbstractMapCanvas"); + + SetPredefinedColor(str_not_sig, wxColour(240, 240, 240)); + SetPredefinedColor(str_undefined, wxColour(70, 70, 70)); + SetPredefinedColor(str_neighborless, wxColour(140, 140, 140)); + SetPredefinedColor(str_p005, wxColour(75, 255, 80)); + SetPredefinedColor(str_p001, wxColour(6, 196, 11)); + SetPredefinedColor(str_p0001, wxColour(3, 116, 6)); + SetPredefinedColor(str_p00001, wxColour(1, 70, 3)); + + cat_classif_def.cat_classif_type = theme_type_s; + // must set var_info times from AbstractCoordinator initially + var_info = a_coordinator->var_info; + template_frame->ClearAllGroupDependencies(); + for (int t=0, sz=var_info.size(); tAddGroupDependancy(var_info[t].name); + } + + UpdateStatusBar(); + wxLogMessage("Exiting AbstractMapCanvas::AbstractMapCanvas"); +} + +AbstractMapCanvas::~AbstractMapCanvas() +{ + wxLogMessage("In AbstractMapCanvas::~AbstractMapCanvas"); +} + +void AbstractMapCanvas::DisplayRightClickMenu(const wxPoint& pos) +{ + wxLogMessage("Entering AbstractMapCanvas::DisplayRightClickMenu"); + // Workaround for right-click not changing window focus in OSX / wxW 3.0 + wxActivateEvent ae(wxEVT_NULL, true, 0, wxActivateEvent::Reason_Mouse); + ((AbstractMapFrame*) template_frame)->OnActivate(ae); + + wxMenu* optMenu = wxXmlResource::Get()->LoadMenu(menu_xrcid); + AddTimeVariantOptionsToMenu(optMenu); + SetCheckMarks(optMenu); + + template_frame->UpdateContextMenuItems(optMenu); + template_frame->PopupMenu(optMenu, pos + GetPosition()); + template_frame->UpdateOptionMenuItems(); + wxLogMessage("Exiting AbstractMapCanvas::DisplayRightClickMenu"); +} + +wxString AbstractMapCanvas::GetCanvasTitle() +{ + return ""; +} + +wxString AbstractMapCanvas::GetVariableNames() +{ + return ""; +} + +/** This method definition is empty. It is here to override any call + to the parent-class method since smoothing and theme changes are not + supported by Abstract maps */ +bool +AbstractMapCanvas::ChangeMapType(CatClassification::CatClassifType new_map_theme, + SmoothingType new_map_smoothing) +{ + wxLogMessage("In AbstractMapCanvas::ChangeMapType"); + return false; +} + +void AbstractMapCanvas::SetCheckMarks(wxMenu* menu) +{ + // Update the checkmarks and enable/disable state for the + // following menu items if they were specified for this particular + // view in the xrc file. Items that cannot be enable/disabled, + // or are not checkable do not appear. + + MapCanvas::SetCheckMarks(menu); + + int sig_filter = a_coord->GetSignificanceFilter(); + + GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_SIGNIFICANCE_FILTER_05"), + sig_filter == 1); + GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_SIGNIFICANCE_FILTER_01"), + sig_filter == 2); + GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_SIGNIFICANCE_FILTER_001"), + sig_filter == 3); + GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_SIGNIFICANCE_FILTER_0001"), + sig_filter == 4); + GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_SIGNIFICANCE_FILTER_SETUP"), + sig_filter == -1); + GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_USE_SPECIFIED_SEED"), + a_coord->IsReuseLastSeed()); +} + +void AbstractMapCanvas::TimeChange() +{ + wxLogMessage("Entering AbstractMapCanvas::TimeChange"); + if (!is_any_sync_with_global_time) return; + + int cts = project->GetTimeState()->GetCurrTime(); + int ref_time = var_info[ref_var_index].time; + int ref_time_min = var_info[ref_var_index].time_min; + int ref_time_max = var_info[ref_var_index].time_max; + + if ((cts == ref_time) || + (cts > ref_time_max && ref_time == ref_time_max) || + (cts < ref_time_min && ref_time == ref_time_min)) return; + if (cts > ref_time_max) { + ref_time = ref_time_max; + } else if (cts < ref_time_min) { + ref_time = ref_time_min; + } else { + ref_time = cts; + } + for (int i=0; iGetSignificanceCutoff(); + int s_f = a_coord->GetSignificanceFilter(); + int set_perm = a_coord->GetNumPermutations(); + int num_obs = a_coord->num_obs; + double stop_sig = 1.0 / (1.0 + set_perm); + std::vector def_cats = a_coord->GetDefaultCategories(); + std::vector def_cutoffs = a_coord->GetDefaultCutoffs(); + + bool is_cust_cutoff = true; + for (int i=0; i<4; i++) { + if (sig_cutoff == def_cutoffs[i]) { + is_cust_cutoff = false; + break; + } + } + + if ( is_cust_cutoff ) { + // if set customized cutoff value + wxString lbl = wxString::Format("p = %g", sig_cutoff); + if ( sig_cutoff > 0.05 ) { + def_cutoffs[0] = sig_cutoff; + lbl_color_dict[lbl] = lbl_color_dict[def_cats[0]]; + def_cats[0] = lbl; + } else { + for (int i = 1; i < 4; i++) { + if (def_cutoffs[i-1] + def_cutoffs[i] < 2 * sig_cutoff){ + lbl_color_dict[lbl] = lbl_color_dict[def_cats[i-1]]; + def_cutoffs[i-1] = sig_cutoff; + def_cats[i-1] = lbl; + break; + } else { + lbl_color_dict[lbl] = lbl_color_dict[def_cats[i]]; + def_cutoffs[i] = sig_cutoff; + def_cats[i] = lbl; + break; + } + } + } + } + + for (int t=0; tGetHasIsolates(t); + bool has_undefined = a_coord->GetHasUndefined(t); + double* p = a_coord->GetLocalSignificanceValues(t); + int* cluster = a_coord->GetClusterIndicators(t); + + int undefined_cat = -1; + int isolates_cat = -1; + int num_cats = 0; + + if ( has_isolates ) + num_cats++; + + if ( has_undefined ) + num_cats++; + + if (is_clust) { + // NotSig LL HH LH HL + SetLabelsAndColorForClusters(num_cats, t, cat_data); + + } else { + // significance map + // 0: >0.05 (Not sig) 1: 0.05, 2: 0.01, 3: 0.001, 4: 0.0001 + num_cats = 5; + if ( has_isolates ) { + num_cats++; + } + if ( has_undefined ) { + num_cats++; + } + for (int j=0; j < def_cats.size(); j++) { + if (sig_cutoff < def_cutoffs[j]) + num_cats -= 1; + } + // issue #474 only show significance levels that can + // be mapped for the given number of permutations, + // e.g., for 99 it would stop at 0.01, for 999 at 0.001, etc. + if ( sig_cutoff >= def_cutoffs[3] && stop_sig > def_cutoffs[3] ){ //0.0001 + num_cats -= 1; + } + if ( sig_cutoff >= def_cutoffs[2] && stop_sig > def_cutoffs[2] ){ //0.001 + num_cats -= 1; + } + if ( sig_cutoff >= def_cutoffs[1] && stop_sig > def_cutoffs[1] ){ //0.01 + num_cats -= 1; + } + cat_data.CreateCategoriesAtCanvasTm(num_cats, t); + + wxColour not_sig_clr = clr_not_sig_polygon; + if (project->IsPointTypeData()) not_sig_clr = clr_not_sig_point; + cat_data.SetCategoryColor(t, 0, not_sig_clr); + cat_data.SetCategoryLabel(t, 0, str_not_sig); + + int cat_idx = 1; + std::map level_cat_dict; + for (int j=0; j < def_cats.size(); j++) { + if (sig_cutoff >= def_cutoffs[j] && def_cutoffs[j] >= stop_sig) { + cat_data.SetCategoryColor(t, cat_idx, lbl_color_dict[def_cats[j]]); + cat_data.SetCategoryLabel(t, cat_idx, def_cats[j]); + level_cat_dict[j] = cat_idx; + cat_idx += 1; + } + } + + if (has_isolates && has_undefined) { + isolates_cat = cat_idx++; + undefined_cat = cat_idx++; + + } else if (has_undefined) { + undefined_cat = cat_idx++; + + } else if (has_isolates) { + isolates_cat = cat_idx++; + } + + if (undefined_cat != -1) { + cat_data.SetCategoryLabel(t, undefined_cat, str_undefined); + cat_data.SetCategoryColor(t, undefined_cat, lbl_color_dict[str_undefined]); + } + if (isolates_cat != -1) { + cat_data.SetCategoryLabel(t, isolates_cat, str_neighborless); + cat_data.SetCategoryColor(t, isolates_cat, lbl_color_dict[str_neighborless]); + } + for (int i=0; i sig_cutoff && cluster[i] != 5 && cluster[i] != 6) { + cat_data.AppendIdToCategory(t, 0, i); // not significant + } else if (cluster[i] == 5) { + cat_data.AppendIdToCategory(t, isolates_cat, i); + } else if (cluster[i] == 6) { + cat_data.AppendIdToCategory(t, undefined_cat, i); + } else { + //cat_data.AppendIdToCategory(t, (sigCat[i]-s_f)+1, i); + for ( int c = def_cats.size()-1; c >= 0; c-- ) { + if ( p[i] <= def_cutoffs[c] ) { + cat_data.AppendIdToCategory(t, level_cat_dict[c], i); + break; + } + } + } + } + } + + for (int cat=0; catmy_times(var_info.size()); + for (int t=0; tvar_info; + template_frame->ClearAllGroupDependencies(); + for (int t=0; tAddGroupDependancy(var_info[t].name); + } + is_any_time_variant = a_coord->is_any_time_variant; + is_any_sync_with_global_time = a_coord->is_any_sync_with_global_time; + ref_var_index = a_coord->ref_var_index; + num_time_vals = a_coord->num_time_vals; + map_valid = a_coord->map_valid; + map_error_message = a_coord->map_error_message; +} + +void AbstractMapCanvas::TimeSyncVariableToggle(int var_index) +{ + LOG_MSG("In AbstractMapCanvas::TimeSyncVariableToggle"); + a_coord->var_info[var_index].sync_with_global_time = + !a_coord->var_info[var_index].sync_with_global_time; + for (int i=0; ivar_info[i].time = var_info[i].time; + } + a_coord->VarInfoAttributeChange(); + a_coord->InitFromVarInfo(); + a_coord->notifyObservers(); +} + +void AbstractMapCanvas::UpdateStatusBar() +{ + wxStatusBar* sb = 0; + if (template_frame) { + sb = template_frame->GetStatusBar(); + } + if (!sb) + return; + wxString s; + s << _("#obs=") << project->GetNumRecords() <<" "; + + if ( highlight_state->GetTotalHighlighted() > 0) { + // for highlight from other windows + s << _("#selected=") << highlight_state->GetTotalHighlighted()<< " "; + } + if (mousemode == select && selectstate == start) { + if (total_hover_obs >= 1) { + s << _("#hover obs ") << hover_obs[0]+1; + } + if (total_hover_obs >= 2) { + s << ", "; + s << _("obs ") << hover_obs[1]+1; + } + if (total_hover_obs >= 3) { + s << ", "; + s << _("obs ") << hover_obs[2]+1; + } + if (total_hover_obs >= 4) { + s << ", ..."; + } + } + if (is_clust && a_coord) { + double p_val = a_coord->GetSignificanceCutoff(); + wxString inf_str = wxString::Format(" p <= %g", p_val); + s << inf_str; + } + sb->SetStatusText(s); +} + +IMPLEMENT_CLASS(AbstractMapFrame, MapFrame) + BEGIN_EVENT_TABLE(AbstractMapFrame, MapFrame) + EVT_ACTIVATE(AbstractMapFrame::OnActivate) +END_EVENT_TABLE() + +AbstractMapFrame::AbstractMapFrame(wxFrame *parent, Project* project, + AbstractCoordinator* a_coordinator, + const wxPoint& pos, const wxSize& size, + const long style) +: MapFrame(parent, project, pos, size, style), +a_coord(a_coordinator) +{ + LOG_MSG("Entering AbstractMapFrame::AbstractMapFrame"); +} + +void AbstractMapFrame::Init() +{ + wxSplitterWindow* splitter_win = new wxSplitterWindow(this,-1, + wxDefaultPosition, wxDefaultSize, + wxSP_3D|wxSP_LIVE_UPDATE|wxCLIP_CHILDREN); + splitter_win->SetMinimumPaneSize(10); + + CatClassification::CatClassifType theme_type = GetThemeType(); + + wxPanel* rpanel = new wxPanel(splitter_win); + template_canvas = CreateMapCanvas(rpanel); + template_canvas->SetScrollRate(1,1); + wxBoxSizer* rbox = new wxBoxSizer(wxVERTICAL); + rbox->Add(template_canvas, 1, wxEXPAND); + rpanel->SetSizer(rbox); + + WeightsManInterface* w_man_int = project->GetWManInt(); + boost::uuids::uuid w_id = w_man_int->GetDefault(); + ((AbstractMapCanvas*) template_canvas)->SetWeightsId(w_id); + + wxPanel* lpanel = new wxPanel(splitter_win); + template_legend = new MapNewLegend(lpanel, template_canvas, + wxPoint(0,0), wxSize(0,0)); + wxBoxSizer* lbox = new wxBoxSizer(wxVERTICAL); + template_legend->GetContainingSizer()->Detach(template_legend); + lbox->Add(template_legend, 1, wxEXPAND); + lpanel->SetSizer(lbox); + + splitter_win->SplitVertically(lpanel, rpanel, GdaConst::map_default_legend_width); + + wxPanel* toolbar_panel = new wxPanel(this,-1, wxDefaultPosition); + wxBoxSizer* toolbar_sizer= new wxBoxSizer(wxVERTICAL); + toolbar = wxXmlResource::Get()->LoadToolBar(toolbar_panel, "ToolBar_MAP"); + SetupToolbar(); + toolbar_sizer->Add(toolbar, 0, wxEXPAND|wxALL); + toolbar_panel->SetSizerAndFit(toolbar_sizer); + + wxBoxSizer* sizer = new wxBoxSizer(wxVERTICAL); + sizer->Add(toolbar_panel, 0, wxEXPAND|wxALL); + sizer->Add(splitter_win, 1, wxEXPAND|wxALL); + SetSizer(sizer); + SetAutoLayout(true); + + SetTitle(template_canvas->GetCanvasTitle()); + + a_coord->registerObserver(this); + + Show(true); + DisplayStatusBar(true); + + LOG_MSG("Exiting AbstractMapFrame::AbstractMapFrame"); +} + +AbstractMapFrame::~AbstractMapFrame() +{ + LOG_MSG("In AbstractMapFrame::~AbstractMapFrame"); + if (a_coord) { + a_coord->removeObserver(this); + a_coord = NULL; + } +} + +void AbstractMapFrame::OnActivate(wxActivateEvent& event) +{ + LOG_MSG("In AbstractMapFrame::OnActivate"); + if (event.GetActive()) { + RegisterAsActive("AbstractMapFrame", GetTitle()); + } + if ( event.GetActive() && template_canvas ) template_canvas->SetFocus(); +} + +void AbstractMapFrame::MapMenus() +{ + LOG_MSG("In AbstractMapFrame::MapMenus"); + wxMenuBar* mb = GdaFrame::GetGdaFrame()->GetMenuBar(); + // Map Options Menus + wxMenu* optMenu = wxXmlResource::Get()->LoadMenu(menu_xrcid); + ((MapCanvas*) template_canvas)-> + AddTimeVariantOptionsToMenu(optMenu); + ((MapCanvas*) template_canvas)->SetCheckMarks(optMenu); + GeneralWxUtils::ReplaceMenu(mb, _("Options"), optMenu); + UpdateOptionMenuItems(); +} + +void AbstractMapFrame::UpdateOptionMenuItems() +{ + TemplateFrame::UpdateOptionMenuItems(); // set common items first + wxMenuBar* mb = GdaFrame::GetGdaFrame()->GetMenuBar(); + int menu = mb->FindMenu(_("Options")); + if (menu == wxNOT_FOUND) { + LOG_MSG("AbstractMapFrame::UpdateOptionMenuItems: " + "Options menu not found"); + } else { + ((AbstractMapCanvas*) template_canvas)->SetCheckMarks(mb->GetMenu(menu)); + } +} + +void AbstractMapFrame::UpdateContextMenuItems(wxMenu* menu) +{ + // Update the checkmarks and enable/disable state for the + // following menu items if they were specified for this particular + // view in the xrc file. Items that cannot be enable/disabled, + // or are not checkable do not appear. + + TemplateFrame::UpdateContextMenuItems(menu); // set common items +} + +void AbstractMapFrame::RanXPer(int permutation) +{ + if (permutation < 9) permutation = 9; + if (permutation > 99999) permutation = 99999; + a_coord->SetNumPermutations(permutation); + a_coord->CalcPseudoP(); + a_coord->notifyObservers(); +} + +void AbstractMapFrame::OnRan99Per(wxCommandEvent& event) +{ + RanXPer(99); +} + +void AbstractMapFrame::OnRan199Per(wxCommandEvent& event) +{ + RanXPer(199); +} + +void AbstractMapFrame::OnRan499Per(wxCommandEvent& event) +{ + RanXPer(499); +} + +void AbstractMapFrame::OnRan999Per(wxCommandEvent& event) +{ + RanXPer(999); +} + +void AbstractMapFrame::OnRanOtherPer(wxCommandEvent& event) +{ + PermutationCounterDlg dlg(this); + if (dlg.ShowModal() == wxID_OK) { + long num; + wxString input = dlg.m_number->GetValue(); + + wxLogMessage(input); + + input.ToLong(&num); + RanXPer(num); + } +} + +void AbstractMapFrame::OnUseSpecifiedSeed(wxCommandEvent& event) +{ + a_coord->SetReuseLastSeed(!a_coord->IsReuseLastSeed()); +} + +void AbstractMapFrame::OnSpecifySeedDlg(wxCommandEvent& event) +{ + uint64_t last_seed = a_coord->GetLastUsedSeed(); + wxString m; + m << "The last seed used by the pseudo random\nnumber "; + m << "generator was " << last_seed << ".\n"; + m << "\nEnter a seed value to use between\n0 and "; + m << std::numeric_limits::max() << "."; + long long unsigned int val; + wxString dlg_val; + wxString cur_val; + cur_val << last_seed; + + wxTextEntryDialog dlg(NULL, m, _("Enter a seed value"), cur_val); + if (dlg.ShowModal() != wxID_OK) return; + dlg_val = dlg.GetValue(); + dlg_val.Trim(true); + dlg_val.Trim(false); + if (dlg_val.IsEmpty()) return; + if (dlg_val.ToULongLong(&val)) { + if (!a_coord->IsReuseLastSeed()) a_coord->SetLastUsedSeed(true); + uint64_t new_seed_val = val; + a_coord->SetLastUsedSeed(new_seed_val); + } else { + wxString m = _("\"%s\" is not a valid seed. Seed unchanged."); + m = wxString::Format(m, dlg_val); + wxMessageDialog dlg(NULL, m, _("Error"), wxOK | wxICON_ERROR); + dlg.ShowModal(); + } +} + +void AbstractMapFrame::SetSigFilterX(int filter) +{ + if (filter == a_coord->GetSignificanceFilter()) return; + a_coord->SetSignificanceFilter(filter); + a_coord->notifyObservers(); + UpdateOptionMenuItems(); +} + +void AbstractMapFrame::OnSigFilter05(wxCommandEvent& event) +{ + SetSigFilterX(1); +} + +void AbstractMapFrame::OnSigFilter01(wxCommandEvent& event) +{ + SetSigFilterX(2); +} + +void AbstractMapFrame::OnSigFilter001(wxCommandEvent& event) +{ + SetSigFilterX(3); +} + +void AbstractMapFrame::OnSigFilter0001(wxCommandEvent& event) +{ + SetSigFilterX(4); +} + +void AbstractMapFrame::OnSigFilterSetup(wxCommandEvent& event) +{ + AbstractMapCanvas* lc = (AbstractMapCanvas*)template_canvas; + int t = template_canvas->cat_data.GetCurrentCanvasTmStep(); + double* p = a_coord->GetLocalSignificanceValues(t); + int n = a_coord->num_obs; + wxString ttl = _("Inference Settings (%d perm)"); + ttl = wxString::Format(ttl, a_coord->GetNumPermutations()); + + double user_sig = a_coord->GetSignificanceCutoff(); + int sig_filter = a_coord->GetSignificanceFilter(); + if (sig_filter < 0) user_sig = a_coord->GetUserCutoff(); + + InferenceSettingsDlg dlg(this, user_sig, p, n, ttl); + if (dlg.ShowModal() == wxID_OK) { + a_coord->SetSignificanceFilter(-1); + a_coord->SetSignificanceCutoff(dlg.GetAlphaLevel()); + a_coord->SetUserCutoff(dlg.GetUserInput()); + + a_coord->notifyObservers(); + + a_coord->SetBO(dlg.GetBO()); + a_coord->SetFDR(dlg.GetFDR()); + UpdateOptionMenuItems(); + } +} + +void AbstractMapFrame::CoreSelectHelper(const std::vector& elem) +{ + HighlightState* highlight_state = project->GetHighlightState(); + std::vector& hs = highlight_state->GetHighlight(); + bool selection_changed = false; + + for (int i=0; inum_obs; i++) { + if (!hs[i] && elem[i]) { + hs[i] = true; + selection_changed = true; + } else if (hs[i] && !elem[i]) { + hs[i] = false; + selection_changed = true; + } + } + if (selection_changed) { + highlight_state->SetEventType(HLStateInt::delta); + highlight_state->notifyObservers(); + } +} + +void AbstractMapFrame::OnSelectCores(wxCommandEvent& event) +{ + wxLogMessage("Entering AbstractMapFrame::OnSelectCores"); + + std::vector elem(a_coord->num_obs, false); + int ts = template_canvas->cat_data.GetCurrentCanvasTmStep(); + int* clust = a_coord->GetClusterIndicators(ts); + double* sig_val = a_coord->GetLocalSignificanceValues(ts); + double user_sig = a_coord->GetSignificanceCutoff(); + + // add all cores to elem list. + for (int i=0; inum_obs; i++) { + if (clust[i] >= 1 && clust[i] <= 4) { + bool cont = true; + if (sig_val[i] < user_sig) cont = false; + if (cont) continue; + elem[i] = true; + } + } + CoreSelectHelper(elem); + + wxLogMessage("Exiting AbstractMapFrame::OnSelectCores"); +} + +void AbstractMapFrame::OnSelectNeighborsOfCores(wxCommandEvent& event) +{ + wxLogMessage("Entering AbstractMapFrame::OnSelectNeighborsOfCores"); + + std::vector elem(a_coord->num_obs, false); + int ts = template_canvas->cat_data.GetCurrentCanvasTmStep(); + int* clust = a_coord->GetClusterIndicators(ts); + double* sig_val = a_coord->GetLocalSignificanceValues(ts); + double user_sig = a_coord->GetSignificanceCutoff(); + const GalElement* W = a_coord->Gal_vecs_orig[ts]->gal; + + // add all cores and neighbors of cores to elem list + for (int i=0; inum_obs; i++) { + if (clust[i] >= 1 && clust[i] <= 4 ) { + bool cont = true; + if (sig_val[i] < user_sig) cont = false; + if (cont) continue; + + elem[i] = true; + const GalElement& e = W[i]; + for (int j=0, jend=e.Size(); jnum_obs; i++) { + if (clust[i] >= 1 && clust[i] <= 4 ) { + bool cont = true; + if (sig_val[i] < user_sig) cont = false; + if (cont) continue; + + elem[i] = false; + } + } + CoreSelectHelper(elem); + + wxLogMessage("Exiting AbstractMapFrame::OnSelectNeighborsOfCores"); +} + +void AbstractMapFrame::OnSelectCoresAndNeighbors(wxCommandEvent& event) +{ + wxLogMessage("Entering AbstractMapFrame::OnSelectCoresAndNeighbors"); + + std::vector elem(a_coord->num_obs, false); + int ts = template_canvas->cat_data.GetCurrentCanvasTmStep(); + int* clust = a_coord->GetClusterIndicators(ts); + double* sig_val = a_coord->GetLocalSignificanceValues(ts); + double user_sig = a_coord->GetSignificanceCutoff(); + const GalElement* W = a_coord->Gal_vecs_orig[ts]->gal; + + // add all cores and neighbors of cores to elem list + for (int i=0; inum_obs; i++) { + if (clust[i] >= 1 && clust[i] <= 4 ) { + bool cont = true; + if (sig_val[i] < user_sig) cont = false; + if (cont) continue; + + + elem[i] = true; + const GalElement& e = W[i]; + for (int j=0, jend=e.Size(); jSyncVarInfoFromCoordinator(); + lc->CreateAndUpdateCategories(); + if (template_legend) template_legend->Recreate(); + SetTitle(lc->GetCanvasTitle()); + lc->Refresh(); + lc->UpdateStatusBar(); +} + +void AbstractMapFrame::closeObserver(AbstractCoordinator* o) +{ + wxLogMessage("In AbstractMapFrame::closeObserver(AbstractCoordinator*)"); + if (a_coord) { + a_coord->removeObserver(this); + a_coord = 0; + } + Close(true); +} + +void AbstractMapFrame::GetVizInfo(std::vector& clusters) +{ + // function called by PublishDlg, not used + if (a_coord) { + /* + if(a_coord->sig_cat_vecs.size()>0) { + for (int i=0; inum_obs;i++) { + clusters.push_back(a_coord->sig_cat_vecs[0][i]); + } + } + */ + } +} diff --git a/Explore/AbstractClusterMap.h b/Explore/AbstractClusterMap.h new file mode 100644 index 000000000..3ceee136d --- /dev/null +++ b/Explore/AbstractClusterMap.h @@ -0,0 +1,133 @@ +/** + * GeoDa TM, Copyright (C) 2011-2015 by Luc Anselin - all rights reserved + * + * This file is part of GeoDa. + * + * GeoDa is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * GeoDa is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#ifndef __GEODA_CENTER_ABSTRACT_CLUSTER_MAP_H__ +#define __GEODA_CENTER_ABSTRACT_CLUSTER_MAP_H__ + +#include "MapNewView.h" +#include "AbstractCoordinator.h" +#include "../GdaConst.h" + +class AbstractMapCanvas : public MapCanvas +{ + DECLARE_CLASS(AbstractMapCanvas) +public: + AbstractMapCanvas(wxWindow *parent, TemplateFrame* t_frame, + Project* project, + AbstractCoordinator* a_coordinator, + CatClassification::CatClassifType theme_type, + bool is_clust, + const wxPoint& pos = wxDefaultPosition, + const wxSize& size = wxDefaultSize); + virtual ~AbstractMapCanvas(); + + virtual void DisplayRightClickMenu(const wxPoint& pos); + virtual wxString GetCanvasTitle(); + virtual wxString GetVariableNames(); + virtual bool ChangeMapType(CatClassification::CatClassifType new_map_theme, + SmoothingType new_map_smoothing); + virtual void SetCheckMarks(wxMenu* menu); + virtual void TimeChange(); + void SyncVarInfoFromCoordinator(); + virtual void CreateAndUpdateCategories(); + virtual void TimeSyncVariableToggle(int var_index); + virtual void UpdateStatusBar(); + virtual void SetWeightsId(boost::uuids::uuid id) { weights_id = id; } + + virtual void SetLabelsAndColorForClusters(int& num_cats, int t, + CatClassifData& cat_data) = 0; + +protected: + AbstractCoordinator* a_coord; + bool is_clust; // true = Cluster Map, false = Significance Map + wxString menu_xrcid; + wxString str_undefined; + wxString str_neighborless; + wxString str_not_sig; + wxString str_p005; + wxString str_p001; + wxString str_p0001; + wxString str_p00001; + + wxColour clr_not_sig_point; + wxColour clr_not_sig_polygon; + + DECLARE_EVENT_TABLE() +}; + +class AbstractMapFrame : public MapFrame, public AbstractCoordinatorObserver +{ + DECLARE_CLASS(AbstractMapFrame) +public: + AbstractMapFrame(wxFrame *parent, Project* project, + AbstractCoordinator* a_coordinator, + const wxPoint& pos = wxDefaultPosition, + const wxSize& size = GdaConst::map_default_size, + const long style = wxDEFAULT_FRAME_STYLE); + virtual ~AbstractMapFrame(); + + void Init(); + + virtual CatClassification::CatClassifType GetThemeType() = 0; + virtual TemplateCanvas* CreateMapCanvas(wxPanel* rpanel) = 0; + virtual void OnSaveResult(wxCommandEvent& event) = 0; + virtual void OnShowAsConditionalMap(wxCommandEvent& event) = 0; + + void OnActivate(wxActivateEvent& event); + virtual void MapMenus(); + virtual void UpdateOptionMenuItems(); + virtual void UpdateContextMenuItems(wxMenu* menu); + virtual void update(WeightsManState* o){} + + void RanXPer(int permutation); + void OnRan99Per(wxCommandEvent& event); + void OnRan199Per(wxCommandEvent& event); + void OnRan499Per(wxCommandEvent& event); + void OnRan999Per(wxCommandEvent& event); + void OnRanOtherPer(wxCommandEvent& event); + + void OnUseSpecifiedSeed(wxCommandEvent& event); + void OnSpecifySeedDlg(wxCommandEvent& event); + + void SetSigFilterX(int filter); + void OnSigFilter05(wxCommandEvent& event); + void OnSigFilter01(wxCommandEvent& event); + void OnSigFilter001(wxCommandEvent& event); + void OnSigFilter0001(wxCommandEvent& event); + void OnSigFilterSetup(wxCommandEvent& event); + + void OnSelectCores(wxCommandEvent& event); + void OnSelectNeighborsOfCores(wxCommandEvent& event); + void OnSelectCoresAndNeighbors(wxCommandEvent& event); + + virtual void update(AbstractCoordinator* o); + virtual void closeObserver(AbstractCoordinator* o); + + virtual void GetVizInfo(std::vector& clusters); + void CoreSelectHelper(const std::vector& elem); + +protected: + CatClassification::CatClassifType theme_type; + AbstractCoordinator* a_coord; + wxString menu_xrcid; + + DECLARE_EVENT_TABLE() +}; + +#endif diff --git a/Explore/AbstractCoordinator.cpp b/Explore/AbstractCoordinator.cpp new file mode 100644 index 000000000..2ba53ec3a --- /dev/null +++ b/Explore/AbstractCoordinator.cpp @@ -0,0 +1,648 @@ +/** + * GeoDa TM, Copyright (C) 2011-2015 by Luc Anselin - all rights reserved + * + * This file is part of GeoDa. + * + * GeoDa is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * GeoDa is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include +#include + +#include +#include +#include +#include +#include +#include "../DataViewer/TableInterface.h" +#include "../ShapeOperations/RateSmoothing.h" +#include "../ShapeOperations/Randik.h" +#include "../ShapeOperations/WeightsManState.h" +#include "../ShapeOperations/WeightUtils.h" +#include "../VarCalc/WeightsManInterface.h" +#include "../logger.h" +#include "../Project.h" +#include "AbstractCoordinator.h" + +AbstractWorkerThread::AbstractWorkerThread(int obs_start_s, + int obs_end_s, + uint64_t seed_start_s, + AbstractCoordinator* a_coord_s, + wxMutex* worker_list_mutex_s, + wxCondition* worker_list_empty_cond_s, + std::list *worker_list_s, + int thread_id_s) +: wxThread(), +obs_start(obs_start_s), +obs_end(obs_end_s), +seed_start(seed_start_s), +a_coord(a_coord_s), +worker_list_mutex(worker_list_mutex_s), +worker_list_empty_cond(worker_list_empty_cond_s), +worker_list(worker_list_s), +thread_id(thread_id_s) +{ +} + +AbstractWorkerThread::~AbstractWorkerThread() +{ +} + +wxThread::ExitCode AbstractWorkerThread::Entry() +{ + // call work for assigned range of observations + a_coord->CalcPseudoP_range(obs_start, obs_end, seed_start); + wxMutexLocker lock(*worker_list_mutex); + // remove ourself from the list + worker_list->remove(this); + // if empty, signal on empty condition since only main thread + // should be waiting on this condition + if (worker_list->empty()) { + worker_list_empty_cond->Signal(); + } + return NULL; +} + +/////////////////////////////////////////////////////////////////////////////// +// +// +/////////////////////////////////////////////////////////////////////////////// +AbstractCoordinator::AbstractCoordinator() +{ + +} + +AbstractCoordinator:: +AbstractCoordinator(boost::uuids::uuid weights_id, + Project* project, + const std::vector& var_info_s, + const std::vector& col_ids, + bool calc_significances_s, + bool row_standardize_s) +: w_man_state(project->GetWManState()), +w_man_int(project->GetWManInt()), +w_id(weights_id), +num_obs(project->GetNumRecords()), +permutations(999), +calc_significances(calc_significances_s), +var_info(var_info_s), +data(var_info_s.size()), +undef_data(var_info_s.size()), +last_seed_used(123456789), +reuse_last_seed(true), +row_standardize(row_standardize_s), +user_sig_cutoff(0) +{ + wxLogMessage("Entering AbstractCoordinator::AbstractCoordinator()."); + reuse_last_seed = GdaConst::use_gda_user_seed; + if ( GdaConst::use_gda_user_seed) { + last_seed_used = GdaConst::gda_user_seed; + } + + TableInterface* table_int = project->GetTableInt(); + for (int i=0; iGetColData(col_ids[i], data[i]); + table_int->GetColUndefined(col_ids[i], undef_data[i]); + } + + undef_tms.resize(var_info_s[0].time_max - var_info_s[0].time_min + 1); + + weight_name = w_man_int->GetLongDispName(w_id); + + weights = w_man_int->GetGal(w_id); + + SetSignificanceFilter(1); + + w_man_state->registerObserver(this); + + wxLogMessage("Exiting AbstractCoordinator::AbstractCoordinator()."); +} + +AbstractCoordinator::~AbstractCoordinator() +{ + wxLogMessage("In AbstractCoordinator::~AbstractCoordinator()."); + if (w_man_state) { + w_man_state->removeObserver(this); + } + DeallocateVectors(); +} + +std::vector AbstractCoordinator::GetDefaultCategories() +{ + std::vector cats; + cats.push_back("p = 0.05"); + cats.push_back("p = 0.01"); + cats.push_back("p = 0.001"); + cats.push_back("p = 0.0001"); + return cats; +} + +std::vector AbstractCoordinator::GetDefaultCutoffs() +{ + std::vector cutoffs; + cutoffs.push_back(0.05); + cutoffs.push_back(0.01); + cutoffs.push_back(0.001); + cutoffs.push_back(0.0001); + return cutoffs; +} + +void AbstractCoordinator::DeallocateVectors() +{ + wxLogMessage("Entering AbstractCoordinator::DeallocateVectors()"); + + for (int i=0; i worker_list; + + // divide up work according to number of observations + // and number of CPUs + int work_chunk = num_obs / nCPUs; + + if (work_chunk == 0) { + work_chunk = 1; + } + + int obs_start = 0; + int obs_end = obs_start + work_chunk; + + bool is_thread_error = false; + int quotient = num_obs / nCPUs; + int remainder = num_obs % nCPUs; + int tot_threads = (quotient > 0) ? nCPUs : remainder; + + //boost::thread_group threadPool; + + if (!reuse_last_seed) last_seed_used = time(0); + + for (int i=0; iCreate() != wxTHREAD_NO_ERROR ) { + delete thread; + is_thread_error = true; + } else { + worker_list.push_front(thread); + } + } + if (is_thread_error) { + // fall back to single thread calculation mode + CalcPseudoP_range(0, num_obs-1, last_seed_used); + } else { + std::list::iterator it; + for (it = worker_list.begin(); it != worker_list.end(); it++) { + (*it)->Run(); + } + while (!worker_list.empty()) { + // wait until thread_list might be empty + worker_list_empty_cond.Wait(); + // We have been woken up. If this was not a false + // alarm (sprious signal), the loop will exit. + } + } + //threadPool.join_all(); + wxLogMessage("Exiting AbstractCoordinator::CalcPseudoP_threaded()"); +} + +void AbstractCoordinator::CalcPseudoP_range(int obs_start, int obs_end, + uint64_t seed_start) +{ + GeoDaSet workPermutation(num_obs); + int max_rand = num_obs-1; + + for (int cnt=obs_start; cnt<=obs_end; cnt++) { + std::vector countLarger(num_time_vals, 0); + + GalElement* w; + + // get full neighbors even if has undefined value + int numNeighbors = 0; + for (int t=0; tgal; + if (w[cnt].Size() > numNeighbors) { + numNeighbors = w[cnt].Size(); + } + int* _sigCat = sig_cat_vecs[t]; + if (w[cnt].Size() == 0) { + _sigCat[cnt] = 5; + } + } + + if (numNeighbors == 0) { + // isolate: don't do permutation + continue; + } + + for (int perm=0; perm0) { + workPermutation.Push(newRandom); + rand++; + } + } + std::vector permNeighbors(numNeighbors); + for (int cp=0; cp0.05 1: 0.05, 2: 0.01, 3: 0.001, 4: 0.0001 + if (filter_id < 1 || filter_id > 4) return; + significance_filter = filter_id; + if (filter_id == 1) significance_cutoff = 0.05; + if (filter_id == 2) significance_cutoff = 0.01; + if (filter_id == 3) significance_cutoff = 0.001; + if (filter_id == 4) significance_cutoff = 0.0001; + wxLogMessage("Exiting AbstractCoordinator::SetSignificanceFilter()"); +} + +void AbstractCoordinator::update(WeightsManState* o) +{ + wxLogMessage("In AbstractCoordinator::update()"); + if (w_man_int) { + weight_name = w_man_int->GetLongDispName(w_id); + } +} + +int AbstractCoordinator::numMustCloseToRemove(boost::uuids::uuid id) const +{ + wxLogMessage("In AbstractCoordinator::numMustCloseToRemove()"); + return id == w_id ? observers.size() : 0; + //return 0; +} + +void AbstractCoordinator::closeObserver(boost::uuids::uuid id) +{ + wxLogMessage("In AbstractCoordinator::closeObserver()"); + if (numMustCloseToRemove(id) == 0) return; + std::list obs_cpy = observers; + for (std::list::iterator i=obs_cpy.begin(); + i != obs_cpy.end(); ++i) { + (*i)->closeObserver(this); + } +} + +void AbstractCoordinator::registerObserver(AbstractCoordinatorObserver* o) +{ + wxLogMessage("In AbstractCoordinator::registerObserver()"); + observers.push_front(o); +} + +void AbstractCoordinator::removeObserver(AbstractCoordinatorObserver* o) +{ + wxLogMessage("Entering AbstractCoordinator::removeObserver"); + observers.remove(o); + LOG(observers.size()); + if (observers.size() == 0) { + delete this; + } + wxLogMessage("Exiting AbstractCoordinator::removeObserver"); +} + +void AbstractCoordinator::notifyObservers() +{ + wxLogMessage("In AbstractCoordinator::notifyObservers"); + for (std::list::iterator it=observers.begin(); + it != observers.end(); ++it) { + (*it)->update(this); + } +} + diff --git a/Explore/AbstractCoordinator.h b/Explore/AbstractCoordinator.h new file mode 100644 index 000000000..dfb2f8467 --- /dev/null +++ b/Explore/AbstractCoordinator.h @@ -0,0 +1,223 @@ +/** + * GeoDa TM, Copyright (C) 2011-2015 by Luc Anselin - all rights reserved + * + * This file is part of GeoDa. + * + * GeoDa is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * GeoDa is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#ifndef __GEODA_CENTER_ABSTRACT_COORDINATOR_H__ +#define __GEODA_CENTER_ABSTRACT_COORDINATOR_H__ + +#include +#include +#include +#include +#include +#include "../VarTools.h" +#include "../ShapeOperations/GeodaWeight.h" +#include "../ShapeOperations/GalWeight.h" +#include "../ShapeOperations/WeightsManStateObserver.h" +#include "../ShapeOperations/OGRDataAdapter.h" + + +class Project; +class WeightsManState; +typedef boost::multi_array d_array_type; +typedef boost::multi_array b_array_type; + + +class AbstractCoordinator; // forward declaration + +class AbstractCoordinatorObserver { +public: + virtual void update(AbstractCoordinator* o) = 0; + /** Request for the Observer to close itself */ + virtual void closeObserver(AbstractCoordinator* o) = 0; +}; + + +class AbstractWorkerThread : public wxThread +{ +public: + AbstractWorkerThread(int obs_start, + int obs_end, + uint64_t seed_start, + AbstractCoordinator* a_coord, + wxMutex* worker_list_mutex, + wxCondition* worker_list_empty_cond, + std::list *worker_list, + int thread_id); + virtual ~AbstractWorkerThread(); + virtual void* Entry(); // thread execution starts here + + int obs_start; + int obs_end; + uint64_t seed_start; + int thread_id; + + AbstractCoordinator* a_coord; + wxMutex* worker_list_mutex; + wxCondition* worker_list_empty_cond; + std::list *worker_list; +}; + +class AbstractCoordinator : public WeightsManStateObserver +{ +public: + AbstractCoordinator(); + AbstractCoordinator(boost::uuids::uuid weights_id, + Project* project, + const std::vector& var_info, + const std::vector& col_ids, + bool calc_significances = true, + bool row_standardize_s = true); + + virtual ~AbstractCoordinator(); + + virtual bool IsOk(); + + virtual wxString GetErrorMessage(); + + virtual void SetSignificanceFilter(int filter_id); + + virtual int GetSignificanceFilter(); + + virtual double GetSignificanceCutoff(); + virtual void SetSignificanceCutoff(double val); + + virtual double GetUserCutoff(); + virtual void SetUserCutoff(double val); + + virtual double GetBO(); + virtual void SetBO(double val); + + virtual double GetFDR(); + virtual void SetFDR(double val); + + virtual int GetNumPermutations(); + virtual void SetNumPermutations(int val); + + virtual uint64_t GetLastUsedSeed(); + + virtual void SetLastUsedSeed(uint64_t seed); + + virtual bool IsReuseLastSeed(); + + virtual void SetReuseLastSeed(bool reuse); + + virtual int numMustCloseToRemove(boost::uuids::uuid id) const; + + virtual void closeObserver(boost::uuids::uuid id); + + virtual bool GetHasIsolates(int time); + + virtual bool GetHasUndefined(int time); + + /** Implementation of WeightsManStateObserver interface */ + virtual void update(WeightsManState* o); + + virtual void registerObserver(AbstractCoordinatorObserver* o); + + virtual void removeObserver(AbstractCoordinatorObserver* o); + + virtual void notifyObservers(); + + virtual void CalcPseudoP_threaded(); + + virtual void Calc() = 0; + + virtual void Init() = 0; + + virtual void CalcPseudoP(); + + virtual void CalcPseudoP_range(int obs_start, int obs_end, + uint64_t seed_start); + + virtual void ComputeLarger(int cnt, std::vector permNeighbors, + std::vector& countLarger) = 0; + + virtual std::vector GetDefaultCategories(); + + virtual std::vector GetDefaultCutoffs(); + + void InitFromVarInfo(); + + void VarInfoAttributeChange(); + + void DeallocateVectors(); + + void AllocateVectors(); + + double* GetLocalSignificanceValues(int t); + + int* GetClusterIndicators(int t); + + int* GetSigCatIndicators(int t); + + boost::uuids::uuid GetWeightsID(); + + wxString GetWeightsName(); + +protected: + int significance_filter; // 0: >0.05 1: 0.05, 2: 0.01, 3: 0.001, 4: 0.0001 + int permutations; // any number from 9 to 99999, 99 will be default + double significance_cutoff; // either 0.05, 0.01, 0.001 or 0.0001 + double bo; //Bonferroni bound + double fdr; //False Discovery Rate + double user_sig_cutoff; // user defined cutoff + std::vector has_undefined; + std::vector has_isolates; + bool row_standardize; + bool calc_significances; // if false, then p-vals will never be needed + uint64_t last_seed_used; + bool reuse_last_seed; + + WeightsManState* w_man_state; + WeightsManInterface* w_man_int; + + GalWeight* weights; + + std::vector sig_local_vecs; + std::vector sig_cat_vecs; + std::vector cluster_vecs; + + boost::uuids::uuid w_id; + wxString weight_name; + +public: + std::vector Gal_vecs; + std::vector Gal_vecs_orig; + + int num_obs; // total # obs including neighborless obs + int num_time_vals; // number of valid time periods based on var_info + + std::vector data; // data[variable][time][obs] + std::vector undef_data; // undef_data[variable][time][obs] + std::vector > undef_tms; + + // All LisaMapCanvas objects synchronize themselves + // from the following 6 variables. + int ref_var_index; + std::vector var_info; + bool is_any_time_variant; + bool is_any_sync_with_global_time; + std::vector map_valid; + std::vector map_error_message; + + /** The list of registered observer objects. */ + std::list observers; +}; + +#endif diff --git a/Explore/Basemap.cpp b/Explore/Basemap.cpp index 0de1c5b9f..7d0773f20 100644 --- a/Explore/Basemap.cpp +++ b/Explore/Basemap.cpp @@ -19,36 +19,130 @@ #include #include - -/* -#ifdef __WIN32__ -#define _USE_MATH_DEFINES -#include -#endif -*/ -#include - #include #include "stdio.h" -#include #include - +#include +#include +#include #include #include #include #include #include - +#include +#include +#include #include +#include #include "../ShapeOperations/OGRDataAdapter.h" #include "Basemap.h" -#include "curl/curl.h" -//#include "MapNewView.h" using namespace std; using namespace GDA; +BasemapItem GetBasemapSelection(int idx) +{ + BasemapItem basemap_item; + + idx = idx - 1; // first item [0] is choice "no basemap" + wxString basemap_sources = GdaConst::gda_basemap_sources; + wxString encoded_str= wxString::FromUTF8((const char*)basemap_sources.mb_str()); + if (encoded_str.IsEmpty() == false) { + basemap_sources = encoded_str; + } + vector keys; + wxString newline; + if (basemap_sources.Find("\r\n") != wxNOT_FOUND) { + newline = "\r\n"; + } else if (basemap_sources.Find("\r") != wxNOT_FOUND) { + newline = "\r"; + } else if (basemap_sources.Find("\n") != wxNOT_FOUND) { + newline = "\n"; + } + if (newline.IsEmpty() == false) { + wxStringTokenizer tokenizer(basemap_sources, newline); + while ( tokenizer.HasMoreTokens() ) { + wxString token = tokenizer.GetNextToken(); + keys.push_back(token.Trim()); + } + if (idx >= 0 && idx < keys.size()) { + wxString basemap_source = keys[idx]; + wxUniChar comma = ','; + int comma_pos = basemap_source.Find(comma); + if ( comma_pos != wxNOT_FOUND ) { + // group.name,url + wxString group_n_name = basemap_source.BeforeFirst(comma); + wxString url = basemap_source.AfterFirst(comma); + wxUniChar dot = '.'; + wxString group = group_n_name.Before(dot); + wxString name = group_n_name.After(dot); + if (!group.IsEmpty() && !name.IsEmpty()) { + basemap_item.group = group; + basemap_item.name = name; + basemap_item.url = url; + } + } + } + } + return basemap_item; +} + +vector ExtractBasemapResources(wxString basemap_sources) { + vector group_names; + map group_dict; + + wxString encoded_str= wxString::FromUTF8((const char*)basemap_sources.mb_str()); + if (encoded_str.IsEmpty() == false) { + basemap_sources = encoded_str; + } + vector keys; + wxString newline; + if (basemap_sources.Find("\r\n") != wxNOT_FOUND) { + newline = "\r\n"; + } else if (basemap_sources.Find("\r") != wxNOT_FOUND) { + newline = "\r"; + } else if (basemap_sources.Find("\n") != wxNOT_FOUND) { + newline = "\n"; + } + if (newline.IsEmpty() == false) { + wxStringTokenizer tokenizer(basemap_sources, newline); + while ( tokenizer.HasMoreTokens() ) { + wxString token = tokenizer.GetNextToken(); + keys.push_back(token.Trim()); + } + for (int i=0; i groups; + for (int i=0; i nokia_user = OGRDataAdapter::GetInstance().GetHistory("nokia_user"); + vector nokia_user = OGRDataAdapter::GetInstance().GetHistory("nokia_user"); if (!nokia_user.empty()) { - string user = nokia_user[0]; + wxString user = nokia_user[0]; if (!user.empty()) { nokia_id = user; } } - vector nokia_key = OGRDataAdapter::GetInstance().GetHistory("nokia_key"); + vector nokia_key = OGRDataAdapter::GetInstance().GetHistory("nokia_key"); if (!nokia_key.empty()) { - string key = nokia_key[0]; + wxString key = nokia_key[0]; if (!key.empty()) { nokia_code = key; } } - - mapType = map_type; - if (mapType == 1) { - basemapUrl = "http://map_positron.basemaps.cartocdn.com/light_all/"; - urlSuffix = ".png"; - imageSuffix = ".png"; - } else if (mapType == 2) { - basemapUrl = "http://map_positron.basemaps.cartocdn.com/dark_all/"; - urlSuffix = ".png"; - imageSuffix = ".png"; - - } else if (mapType == 3) { - basemapUrl = "http://map_positron.basemaps.cartocdn.com/light_nolabels/"; - urlSuffix = ".png"; - imageSuffix = ".png"; - } else if (mapType == 4) { - basemapUrl = "http://map_positron.basemaps.cartocdn.com/dark_nolabels/"; - urlSuffix = ".png"; - imageSuffix = ".png"; - } else if (mapType == 5) { - // nokia day - basemapUrl = "http://1.base.maps.api.here.com/maptile/2.1/maptile/newest/normal.day/"; - urlSuffix = "/256/png8?app_id=" + nokia_id + "&app_code=" + nokia_code; - imageSuffix = ".png"; - } else if (mapType == 6) { - // nokia night - basemapUrl = "http://4.base.maps.api.here.com/maptile/2.1/maptile/newest/normal.night/"; - urlSuffix = "/256/png8?app_id=" + nokia_id + "&app_code=" + nokia_code; - imageSuffix = ".png"; - } else if (mapType == 7) { - // nokia terrian - basemapUrl = "http://3.aerial.maps.api.here.com/maptile/2.1/maptile/newest/hybrid.day/"; - urlSuffix = "/256/png8?app_id=" + nokia_id + "&app_code=" + nokia_code; - imageSuffix = ".png"; - } else if (mapType == 8) { - // nokia hybrid - basemapUrl = "http://4.aerial.maps.api.here.com/maptile/2.1/maptile/newest/satellite.day/"; - urlSuffix = "/256/png8?app_id=" + nokia_id + "&app_code=" + nokia_code; - imageSuffix = ".png"; - } else { - mapType = 1; - basemapUrl = "http://map_positron.basemaps.cartocdn.com/light_all/"; - urlSuffix = ".png"; - imageSuffix = ".png"; - } - isTileDrawn = false; - isTileReady = false; GetTiles(); } @@ -211,7 +270,7 @@ void Basemap::Reset() map->west= origMap->west; map->east= origMap->east; GetEasyZoomLevel(); - SetupMapType(mapType); + SetupMapType(basemap_item); } void Basemap::Reset(int map_type) @@ -220,9 +279,8 @@ void Basemap::Reset(int map_type) map->south= origMap->south; map->west= origMap->west; map->east= origMap->east; - mapType = map_type; GetEasyZoomLevel(); - SetupMapType(mapType); + SetupMapType(basemap_item); } void Basemap::ResizeScreen(int _width, int _height) @@ -232,10 +290,10 @@ void Basemap::ResizeScreen(int _width, int _height) screen->height = _height; } - isTileDrawn = false; + //isTileDrawn = false; GetEasyZoomLevel(); - SetupMapType(mapType); + SetupMapType(basemap_item); } void Basemap::Pan(int x0, int y0, int x1, int y1) @@ -249,15 +307,18 @@ void Basemap::Pan(int x0, int y0, int x1, int y1) double offsetLat = p1->lat - p0->lat; double offsetLon = p1->lng - p0->lng; - map->Pan(-offsetLat, -offsetLon); - - isTileDrawn = false; - isTileReady = false; - GetTiles(); + if (map->Pan(-offsetLat, -offsetLon)) { + isTileDrawn = false; + isTileReady = false; + GetTiles(); + } } -void Basemap::Zoom(bool is_zoomin, int x0, int y0, int x1, int y1) +bool Basemap::Zoom(bool is_zoomin, int x0, int y0, int x1, int y1) { + if (is_zoomin == false && zoom <= 1) + return false; + int left = x0 < x1 ? x0 : x1; int right = x0 < x1 ? x1 : x0; int top = y0 > y1 ? y1 : y0; @@ -287,6 +348,7 @@ void Basemap::Zoom(bool is_zoomin, int x0, int y0, int x1, int y1) isTileReady = false; GetEasyZoomLevel(); GetTiles(); + return true; } void Basemap::ZoomIn(int mouseX, int mouseY) @@ -298,8 +360,8 @@ void Basemap::ZoomIn(int mouseX, int mouseY) int x0 = screen->width / 2.0; int y0 = screen->height / 2.0; - isTileDrawn = false; - isTileReady = false; + //isTileDrawn = false; + //isTileReady = false; Pan(mouseX, mouseY, x0, y0); } @@ -313,8 +375,8 @@ void Basemap::ZoomOut(int mouseX, int mouseY) int x0 = screen->width / 2.0; int y0 = screen->height / 2.0; - isTileDrawn = false; - isTileReady = false; + //isTileDrawn = false; + //isTileReady = false; Pan(mouseX, mouseY, x0, y0); } @@ -343,10 +405,10 @@ int Basemap::GetOptimalZoomLevel(double paddingFactor) int Basemap::GetEasyZoomLevel() { double degreeRatio = 360.0 / map->GetWidth(); - double zoomH = (int)ceil(log2(degreeRatio * screen->width / 256)); + double zoomH = (int)ceil(log2(degreeRatio * screen->width / 256.0)); degreeRatio = 85.0511 * 2.0 / map->GetHeight(); - double zoomV = (int)ceil(log2(degreeRatio * screen->height / 256)); + double zoomV = (int)ceil(log2(degreeRatio * screen->height / 256.0)); if (zoomH > 0 && zoomV > 0) { zoom = min(zoomH, zoomV); @@ -372,6 +434,9 @@ void Basemap::Refresh() void Basemap::GetTiles() { + if (zoom < 1) + return; + // following: http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames // top-left / north-west LatLng nw(map->north, map->west); @@ -397,9 +462,6 @@ void Basemap::GetTiles() widthP = (endX - startX + 1) * 256; heightP = (endY - startY + 1) * 256; - widthP = (endX - startX + 1) * 256; - heightP = (endY - startY + 1) * 256; - if (widthP < screen->width) { int x_addition = (int)ceil((screen->width - widthP)/ 256.0); endX += x_addition; @@ -418,7 +480,8 @@ void Basemap::GetTiles() } else { map_wp = (nn - topleft->x + bottomright->x) * 255; } - int map_offx = (int) ((screen->width - map_wp) / 2.0); + int map_offx = (int)(ceil) ((screen->width - map_wp) / 2.0); + // if offset to left, need to zoom out if (map_offx < 0 && zoom > 0) { zoom = zoom -1; @@ -426,24 +489,30 @@ void Basemap::GetTiles() GetTiles(); return; } + offsetX = topleft->GetXFrac() * 255 - map_offx; // if offset to right, need to patch empty tiles - if (offsetX < 0 && startX >= 0) { - startX = startX -1; - offsetX = offsetX + 256; - widthP = widthP + 256; - leftP = startX * 256; + if (offsetX < 0) { + while (offsetX < 0) { + offsetX += 256; + startX = startX -1; + widthP = widthP + 256; + leftP = startX * 256; + } } double map_hp = (bottomright->y - topleft->y) * 255; int map_offy = (int) ((screen->height - map_hp) / 2.0); offsetY = topleft->GetYFrac() * 255 - map_offy; + // if offset down, need to patch empty tiles - if (offsetY < 0 && startY >= 0) { - startY = startY -1; - offsetY = offsetY + 256; - heightP = heightP + 256; - topP = startY * 256; + if (offsetY < 0 ) { + while (offsetY < 0) { + startY = startY -1; + offsetY = offsetY + 256; + heightP = heightP + 256; + topP = startY * 256; + } } // check tiles again after offset @@ -458,7 +527,10 @@ void Basemap::GetTiles() offsetX = offsetX - panX; offsetY = offsetY - panY; - + + isTileReady = false; + isTileDrawn = false; + if (bDownload && downloadThread) { bDownload = false; downloadThread->join(); @@ -526,13 +598,16 @@ size_t curlCallback(void *ptr, size_t size, size_t nmemb, void* userdata) void Basemap::DownloadTile(int x, int y) { + if (x < 0 || y < 0) + return; + // detect if file exists in temp/ directory wxString filepathStr = GetTilePath(x, y); std::string filepath = GET_ENCODED_FILENAME(filepathStr); if (!wxFileExists(filepathStr)) { // otherwise, download the image - std::string urlStr = GetTileUrl(x, y); + wxString urlStr = GetTileUrl(x, y); char* url = new char[urlStr.length() + 1]; std::strcpy(url, urlStr.c_str()); @@ -549,21 +624,21 @@ void Basemap::DownloadTile(int x, int y) #endif if (fp) { - curl_easy_setopt(image, CURLOPT_URL, url); + curl_easy_setopt(image, CURLOPT_URL, url); curl_easy_setopt(image, CURLOPT_WRITEFUNCTION, curlCallback); curl_easy_setopt(image, CURLOPT_WRITEDATA, fp); //curl_easy_setopt(image, CURLOPT_FOLLOWLOCATION, 1); curl_easy_setopt(image, CURLOPT_CONNECTTIMEOUT, 10L); curl_easy_setopt(image, CURLOPT_NOSIGNAL, 1L); - // Grab image - imgResult = curl_easy_perform(image); + // Grab image + imgResult = curl_easy_perform(image); curl_easy_cleanup(image); fclose(fp); } } - + delete[] url; } @@ -625,13 +700,15 @@ void Basemap::LatLngToXY(double lng, double lat, int &x, int &y) } } -std::string Basemap::GetTileUrl(int x, int y) +wxString Basemap::GetTileUrl(int x, int y) { - std::ostringstream urlBuf; - urlBuf << basemapUrl; - urlBuf << zoom << "/" << x << "/" << y << urlSuffix; - std::string urlStr = urlBuf.str(); - return urlStr; + wxString url = basemapUrl; + url.Replace("{z}", wxString::Format("%d", zoom)); + url.Replace("{x}", wxString::Format("%d", x)); + url.Replace("{y}", wxString::Format("%d", y)); + url.Replace("HERE_APP_ID", nokia_id); + url.Replace("HERE_APP_CODE", nokia_code); + return url; } wxString Basemap::GetTilePath(int x, int y) @@ -639,7 +716,7 @@ wxString Basemap::GetTilePath(int x, int y) //std::ostringstream filepathBuf; wxString filepathBuf; filepathBuf << cachePath << "basemap_cache"<< separator(); - filepathBuf << mapType << "-"; + filepathBuf << basemapName << "-"; filepathBuf << zoom << "-" << x << "-" << y << imageSuffix; wxString newpath; @@ -655,11 +732,12 @@ wxString Basemap::GetTilePath(int x, int y) } return newpath; } + bool Basemap::Draw(wxBitmap* buffer) { // when tiles pngs are ready, draw them on a buffer wxMemoryDC dc(*buffer); - dc.SetBackground( *wxTRANSPARENT_BRUSH ); + dc.SetBackground(*wxWHITE); dc.Clear(); wxGraphicsContext* gc = wxGraphicsContext::Create(dc); if (!gc) @@ -669,7 +747,7 @@ bool Basemap::Draw(wxBitmap* buffer) int x1 = endX; for (int i=x0; i<=x1; i++) { for (int j=startY; j<=endY; j++ ) { - int pos_x =(i-startX) * 256 - offsetX; + int pos_x = (i-startX) * 256 - offsetX; int pos_y = (j-startY) * 256 - offsetY; int idx_x = i; @@ -678,7 +756,8 @@ bool Basemap::Draw(wxBitmap* buffer) else if (i < 0) idx_x = nn + i; - int idx_y = j < 0 ? nn + j : j; + //int idx_y = j < 0 ? nn + j : j; + int idx_y = j; wxString wxFilePath = GetTilePath(idx_x, idx_y); wxFileName fp(wxFilePath); wxBitmap bmp; @@ -689,10 +768,10 @@ bool Basemap::Draw(wxBitmap* buffer) wxImage::AddHandler(jpegLoader); bmp.LoadFile(wxFilePath, wxBITMAP_TYPE_JPEG); } - bool bmpOK = bmp.IsOk(); - if (bmpOK) - gc->DrawBitmap(bmp, pos_x, pos_y, 256,256); - //dc.DrawRectangle((i-startX) * 256 - offsetX, (j-startY) * 256 - offsetY, 256, 256); + if (bmp.IsOk()) { + gc->DrawBitmap(bmp, pos_x, pos_y, 257,257); + //dc.DrawRectangle((i-startX) * 256 - offsetX, (j-startY) * 256 - offsetY, 256, 256); + } } } delete gc; diff --git a/Explore/Basemap.h b/Explore/Basemap.h index cd9f6a038..4e51a79e6 100644 --- a/Explore/Basemap.h +++ b/Explore/Basemap.h @@ -20,300 +20,339 @@ #ifndef GeoDa_Basemap_h #define GeoDa_Basemap_h -/* -#ifdef __WIN32__ -#define _USE_MATH_DEFINES -#include -#endif -*/ +#include #include - +#include #include #include -//#include -//#include - #include #include #include - -//class MapCanvas; - using namespace std; -namespace GDA { - -inline char separator() -{ -#ifdef __WIN32__ - return '\\'; -#else - return '/'; -#endif -} - -inline bool is_file_exist(const char *fileName) -{ - std::ifstream infile(fileName); - return infile.good() && (infile.peek() != std::ifstream::traits_type::eof()); -} - -inline double log2(double n) -{ - return log(n) / log(2.0); -} - - -class LatLng { +class BasemapItem { public: - LatLng() {} - LatLng(double _lat, double _lng) { - lat = _lat; - lng = _lng; + BasemapItem() {} + BasemapItem(wxString _group, wxString _name, wxString _url) { + group = _group; + name = _name; + url = _url; } - ~LatLng(){} - - double lat; - double lng; - - double GetLatDeg() {return lat;} - double GetLngDeg() {return lng;} - double GetLatRad() {return lat * M_PI / 180.0;} - double GetLngRad() {return lng * M_PI / 180.0;} -}; - -class XY { -public: - XY(){} - XY(int _x, int _y) { - x = _x; - y = _y; - xint = _x; - yint = _y; - xfrac = .0; - yfrac = .0; + ~BasemapItem() {} + BasemapItem& operator=(const BasemapItem& other) { + group = other.group; + name = other.name; + url = other.url; + return *this; } - XY(double _x, double _y); - ~XY(){} - - double x; - double y; - double xfrac; - double yfrac; - double xint; - double yint; - - int GetXInt() { return (int)xint;} - int GetYInt() { return (int)yint;} - double GetXFrac() { return xfrac;} - double GetYFrac() { return yfrac;} -}; - -class Screen { -public: - Screen(){} - Screen(int _w, int _h) { width=_w; height= _h;} - ~Screen(){} - - int width; - int height; + bool operator==(const BasemapItem& other) { + return (group == other.group && name == other.name && url == other.url); + } + wxString group; + wxString name; + wxString url; }; -class MapLayer { +class BasemapGroup { public: - MapLayer(){} - MapLayer(MapLayer* _map) { - north = _map->north; - south = _map->south; - west = _map->west; - east = _map->east; - } - MapLayer(double _n, double _w, double _s, double _e){ - north = _n; - south = _s; - west = _w; - east = _e; - } - MapLayer(double _n, double _w, double _s, double _e, - OGRCoordinateTransformation *_poCT){ - north = _n; - south = _s; - west = _w; - east = _e; - poCT = _poCT; - if (poCT!= NULL) { - if (poCT->Transform(1, &_w, &_n)) { - west = _w; - north = _n; - } - if (poCT->Transform(1, &_e, &_s)) { - east = _e; - south = _s; - } - } - } - MapLayer(LatLng& nw, LatLng& se){ - north = nw.lat; - west = nw.lng; - south = se.lat; - east = se.lng; - } - ~MapLayer(){} - - MapLayer* operator=(const MapLayer* other) { - north = other->north; - south = other->south; - west = other->west; - east = other->east; - } - double north; - double south; - double west; - double east; - OGRCoordinateTransformation *poCT; - - double GetWidth() { - if (east >= west) - return east - west; - else - return 180 - east + 180 + west; - } - double GetHeight() { return north - south; } - - bool IsWGS84Valid() { return north < 90 && south > -90 && east > -180 && west < 180;} - - void Pan(double lat, double lng) { - north += lat; - south += lat; - west += lng; - east += lng; - } - - void UpdateExtent(double _w, double _s, double _e, double _n) { - north = _n; - south = _s; - east = _e; - west = _w; + BasemapGroup() {} + BasemapGroup(wxString _name) { + name = _name; } - - void ZoomIn() { - // 2X by default - double w = east - west; - double h = north - south; - double offsetW = w / 4.0; - double offsetH = h / 4.0; - west = west + offsetW; - east = east - offsetW; - north = north - offsetH; - south = south + offsetH; + ~BasemapGroup() {} + BasemapGroup& operator=(const BasemapGroup& other) { + name = other.name; + items = other.items; + return *this; } - - void ZoomOut() { - // 2X by default - double w = east - west; - double h = north - south; - double offsetW = w / 2.0; - double offsetH = h / 2.0; - west = west - offsetW; - east = east + offsetW; - north = north + offsetH; - south = south - offsetH; + void AddItem(BasemapItem item) { + items.push_back(item); } + wxString name; + vector items; }; -// only for Web mercator projection -class Basemap { - -public: - Basemap(){} - Basemap(Screen *_screen, - MapLayer *_map, - int map_type, - wxString _cachePath, - OGRCoordinateTransformation *_poCT ); - ~Basemap(); - - OGRCoordinateTransformation *poCT; - - //MapCanvas* canvas; - int mapType; - std::string basemapUrl; - std::string urlSuffix; // ?a=b&c=d - std::string imageSuffix; - int startX; - int startY; - int endX; - int endY; - int offsetX; - int offsetY; - int widthP; // width of all tiles in pixel - int heightP; // height of all tiles in pixel - int leftP; - int topP; - - bool isTileDrawn; - bool isTileReady; - - bool isPan; - int panX; - int panY; - - int zoom; - Screen* screen; - MapLayer* map; - MapLayer* origMap; - wxString cachePath; - - double Deg2Rad (double degree) { return degree * M_PI / 180.0; } - double Rad2Deg (double radians) { return radians * 180.0 / M_PI;} - XY* LatLngToXY(LatLng &latlng); - LatLng* XYToLatLng(XY &xy, bool isLL=false); - void LatLngToXY(double lng, double lat, int &x, int &y); - - std::string GetTileUrl(int x, int y); - wxString GetTilePath(int x, int y); +BasemapItem GetBasemapSelection(int idx); - bool Draw(wxBitmap* buffer); - - void ResizeScreen(int _width, int _height); - void ZoomIn(int mouseX, int mouseY); - void ZoomOut(int mouseX, int mouseY); - void Zoom(bool is_zoomin, int x0, int y0, int x1, int y1); - void Pan(int x0, int y0, int x1, int y1); - void Reset(int map_type); - void Reset(); - void Refresh(); - bool IsReady(); - - void SetupMapType(int map_type); - - void CleanCache(); - -protected: - std::string nokia_id; - std::string nokia_code; +vector ExtractBasemapResources(wxString basemap_sources) ; + +namespace GDA { + inline char separator() + { +#ifdef __WIN32__ + return '\\'; +#else + return '/'; +#endif + } - int nn; // pow(2.0, zoom) + inline bool is_file_exist(const char *fileName) + { + std::ifstream infile(fileName); + return infile.good() && (infile.peek() != std::ifstream::traits_type::eof()); + } - bool bDownload; - boost::thread* downloadThread; - boost::thread* downloadThread1; + inline double log2(double n) + { + return log(n) / log(2.0); + } - int GetOptimalZoomLevel(double paddingFactor=1.2); - int GetEasyZoomLevel(); - XY* LatLngToRawXY(LatLng &latlng); + class LatLng { + public: + LatLng() {} + LatLng(double _lat, double _lng) { + lat = _lat; + lng = _lng; + } + ~LatLng(){} + + double lat; + double lng; + + double GetLatDeg() {return lat;} + double GetLngDeg() {return lng;} + double GetLatRad() {return lat * M_PI / 180.0;} + double GetLngRad() {return lng * M_PI / 180.0;} + }; - void GetTiles(); - void _GetTiles(int start_x, int start_y, int end_x, int end_y); - void _GetTiles(int x, int start_y, int end_y); + class XY { + public: + XY(){} + XY(int _x, int _y) { + x = _x; + y = _y; + xint = _x; + yint = _y; + xfrac = .0; + yfrac = .0; + } + XY(double _x, double _y); + ~XY(){} + + double x; + double y; + double xfrac; + double yfrac; + double xint; + double yint; + + int GetXInt() { return (int)xint;} + int GetYInt() { return (int)yint;} + double GetXFrac() { return xfrac;} + double GetYFrac() { return yfrac;} + }; - void DownloadTile(int x, int y); + class Screen { + public: + Screen(){} + Screen(int _w, int _h) { width=_w; height= _h;} + ~Screen(){} + + int width; + int height; + }; - bool _HasInternet(); -}; + class MapLayer { + public: + MapLayer(){} + MapLayer(MapLayer* _map) { + north = _map->north; + south = _map->south; + west = _map->west; + east = _map->east; + } + MapLayer(double _n, double _w, double _s, double _e){ + north = _n; + south = _s; + west = _w; + east = _e; + } + MapLayer(double _n, double _w, double _s, double _e, + OGRCoordinateTransformation *_poCT){ + north = _n; + south = _s; + west = _w; + east = _e; + poCT = _poCT; + if (poCT!= NULL) { + if (poCT->Transform(1, &_w, &_n)) { + west = _w; + north = _n; + } + if (poCT->Transform(1, &_e, &_s)) { + east = _e; + south = _s; + } + } + } + MapLayer(LatLng& nw, LatLng& se){ + north = nw.lat; + west = nw.lng; + south = se.lat; + east = se.lng; + } + ~MapLayer(){} + + MapLayer* operator=(const MapLayer* other) { + north = other->north; + south = other->south; + west = other->west; + east = other->east; + return this; + } + double north; + double south; + double west; + double east; + OGRCoordinateTransformation *poCT; + + double GetWidth() { + if (east >= west) + return east - west; + else + return 180 - east + 180 + west; + } + double GetHeight() { return north - south; } + + bool IsWGS84Valid() { return north < 90 && south > -90 && east > -180 && west < 180;} + + bool Pan(double lat, double lng) { + north += lat; + south += lat; + west += lng; + east += lng; + if (north > 90 || south < -90 || east > 180 || west < -180) + return false; + return true; + } + + void UpdateExtent(double _w, double _s, double _e, double _n) { + north = _n; + south = _s; + east = _e; + west = _w; + } + + void ZoomIn() { + // 2X by default + double w = east - west; + double h = north - south; + double offsetW = w / 4.0; + double offsetH = h / 4.0; + west = west + offsetW; + east = east - offsetW; + north = north - offsetH; + south = south + offsetH; + } + + void ZoomOut() { + // 2X by default + double w = east - west; + double h = north - south; + double offsetW = w / 2.0; + double offsetH = h / 2.0; + west = west - offsetW; + east = east + offsetW; + north = north + offsetH; + south = south - offsetH; + } + }; + // only for Web mercator projection + class Basemap { + + public: + Basemap(){} + Basemap(BasemapItem& basemap_item, + Screen *_screen, + MapLayer *_map, + wxString _cachePath, + OGRCoordinateTransformation *_poCT, + double scale_factor = 1.0); + ~Basemap(); + + OGRCoordinateTransformation *poCT; + BasemapItem basemap_item; + wxString basemapName; + wxString basemapUrl; + wxString imageSuffix; + wxString cachePath; + wxString nokia_id; + wxString nokia_code; + + int startX; + int startY; + int endX; + int endY; + int offsetX; + int offsetY; + int widthP; // width of all tiles in pixel + int heightP; // height of all tiles in pixel + int leftP; + int topP; + double scale_factor; + + bool isTileDrawn; + bool isTileReady; + + bool isPan; + int panX; + int panY; + + int zoom; + Screen* screen; + MapLayer* map; + MapLayer* origMap; + + + double Deg2Rad (double degree) { return degree * M_PI / 180.0; } + double Rad2Deg (double radians) { return radians * 180.0 / M_PI;} + XY* LatLngToXY(LatLng &latlng); + LatLng* XYToLatLng(XY &xy, bool isLL=false); + void LatLngToXY(double lng, double lat, int &x, int &y); + + wxString GetTileUrl(int x, int y); + wxString GetTilePath(int x, int y); + + bool Draw(wxBitmap* buffer); + + void ResizeScreen(int _width, int _height); + void ZoomIn(int mouseX, int mouseY); + void ZoomOut(int mouseX, int mouseY); + bool Zoom(bool is_zoomin, int x0, int y0, int x1, int y1); + void Pan(int x0, int y0, int x1, int y1); + void Reset(int map_type); + void Reset(); + void Refresh(); + bool IsReady(); + + void SetupMapType(BasemapItem& basemap_item); + + void CleanCache(); + + protected: + + int nn; // pow(2.0, zoom) + + bool bDownload; + boost::thread* downloadThread; + boost::thread* downloadThread1; + + int GetOptimalZoomLevel(double paddingFactor=1.2); + int GetEasyZoomLevel(); + + XY* LatLngToRawXY(LatLng &latlng); + + void GetTiles(); + void _GetTiles(int start_x, int start_y, int end_x, int end_y); + void _GetTiles(int x, int start_y, int end_y); + + void DownloadTile(int x, int y); + + bool _HasInternet(); + }; } diff --git a/Explore/BoxNewPlotView.cpp b/Explore/BoxNewPlotView.cpp index 69a9ecb1b..9df32a96d 100644 --- a/Explore/BoxNewPlotView.cpp +++ b/Explore/BoxNewPlotView.cpp @@ -37,7 +37,6 @@ #include "../logger.h" #include "../GeoDa.h" #include "../Project.h" -#include "../ShapeOperations/ShapeUtils.h" #include "BoxNewPlotView.h" IMPLEMENT_CLASS(BoxPlotCanvas, TemplateCanvas) @@ -125,7 +124,7 @@ hinge_15(true) } // no more than 100 plots - max_plots = GenUtils::min(MAX_BOX_PLOTS, var_info[0].is_time_variant ? + max_plots = std::min(MAX_BOX_PLOTS, var_info[0].is_time_variant ? project->GetTableInt()->GetTimeSteps() : 1); cur_num_plots = max_plots; cur_first_ind = var_info[0].time_min; @@ -176,8 +175,7 @@ void BoxPlotCanvas::AddTimeVariantOptionsToMenu(wxMenu* menu) if (!var_info[0].is_time_variant) return; wxMenu* menu1 = new wxMenu(wxEmptyString); { - wxString s; - s << "Synchronize " << var_info[0].name << " with Time Control"; + wxString s = wxString::Format(_("Synchronize %s with Time Control"), var_info[0].name); wxMenuItem* mi = menu1->AppendCheckItem(GdaConst::ID_TIME_SYNC_VAR1+0, s, s); mi->Check(var_info[0].sync_with_global_time); @@ -185,8 +183,7 @@ void BoxPlotCanvas::AddTimeVariantOptionsToMenu(wxMenu* menu) wxMenu* menu2 = new wxMenu(wxEmptyString); { - wxString s; - s << "Fixed scale over time"; + wxString s= _("Fixed scale over time"); wxMenuItem* mi = menu2->AppendCheckItem(GdaConst::ID_FIX_SCALE_OVER_TIME_VAR1, s, s); mi->Check(var_info[0].fixed_scale); @@ -195,7 +192,7 @@ void BoxPlotCanvas::AddTimeVariantOptionsToMenu(wxMenu* menu) wxMenu* menu3 = new wxMenu(wxEmptyString); { int mppv = GdaConst::max_plots_per_view_menu_items; - int mp = GenUtils::min(max_plots, mppv); + int mp = std::min(max_plots, mppv); for (int i=0; iCheck(cur_num_plots == max_plots); } - menu->Prepend(wxID_ANY, "Number of Box Plots", menu3, - "Number of Box Plots"); - menu->Prepend(wxID_ANY, "Scale Options", menu2, "Scale Options"); + menu->Prepend(wxID_ANY, _("Number of Box Plots"), menu3, _("Number of Box Plots")); + menu->Prepend(wxID_ANY, _("Scale Options"), menu2, _("Scale Options")); menu->AppendSeparator(); - menu->Append(wxID_ANY, "Time Variable Options", menu1, - "Time Variable Options"); + menu->Append(wxID_ANY, _("Time Variable Options"), menu1, + _("Time Variable Options")); } void BoxPlotCanvas::SetCheckMarks(wxMenu* menu) @@ -255,7 +251,7 @@ void BoxPlotCanvas::SetCheckMarks(wxMenu* menu) GdaConst::ID_FIX_SCALE_OVER_TIME_VAR1, var_info[0].fixed_scale); int mppv = GdaConst::max_plots_per_view_menu_items; - int mp = GenUtils::min(max_plots, mppv); + int mp = std::min(max_plots, mppv); for (int i=0; icenter; - wxPoint& pt1 = pt; - sel_scratch[i] = sel_scratch[i] || - GenUtils::distance_sqrd(pt0, pt1) <= 16.5; + if (selectable_shps[t*num_obs + i]) { + wxPoint& pt0 = selectable_shps[t*num_obs + i]->center; + wxPoint& pt1 = pt; + sel_scratch[i] = sel_scratch[i] || GenUtils::distance_sqrd(pt0, pt1) <= 16.5; + } } } for (int i=0; ipointWithin(sel1); + if (selectable_shps[t*num_obs + i]) { + sel_scratch[i] = sel_scratch[i] || selectable_shps[t*num_obs + i]->pointWithin(sel1); + } } } } else { @@ -313,9 +311,9 @@ void BoxPlotCanvas::UpdateSelection(bool shiftdown, bool pointsel) wxRegion rect(wxRect(sel1, sel2)); for (int t=0; tcenter) != - wxOutRegion); + if (selectable_shps[t*num_obs + i]) { + sel_scratch[i] = sel_scratch[i] || (rect.Contains(selectable_shps[t*num_obs + i]->center) != wxOutRegion); + } } } } @@ -341,16 +339,18 @@ void BoxPlotCanvas::UpdateSelection(bool shiftdown, bool pointsel) } if ( selection_changed ) { - highlight_state->SetEventType(HLStateInt::delta); - highlight_state->notifyObservers(this); + int total_highlighted = 0; // used for MapCanvas::Drawlayer1 + for (int i=0; iSetTotalHighlighted(total_highlighted); + highlight_timer->Start(50); // re-paint highlight layer (layer1_bm) layer1_valid = false; DrawLayers(); - Refresh(); - UpdateStatusBar(); } + Refresh(); + UpdateStatusBar(); } void BoxPlotCanvas::DrawSelectableShapes(wxMemoryDC &dc) @@ -377,8 +377,8 @@ void BoxPlotCanvas::DrawSelectableShapes(wxMemoryDC &dc) int ind = ind_base + idx; dc.DrawCircle(selectable_shps[ind]->center, radius); } - int iqr_s = GenUtils::max(min_IQR, 0); - int iqr_t = GenUtils::min(max_IQR, num_obs-1); + int iqr_s = std::max(min_IQR, 0); + int iqr_t = std::min(max_IQR, num_obs-1); dc.SetPen(GdaConst::boxplot_q1q2q3_color); dc.SetBrush(GdaConst::boxplot_q1q2q3_color); for (int i=iqr_s; i<=iqr_t; i++) { @@ -424,8 +424,8 @@ void BoxPlotCanvas::DrawHighlightedShapes(wxMemoryDC &dc) if (!hs[idx]) continue; dc.DrawCircle(selectable_shps[ind]->center, radius); } - int iqr_s = GenUtils::max(min_IQR, 0); - int iqr_t = GenUtils::min(max_IQR, num_obs-1); + int iqr_s = std::max(min_IQR, 0); + int iqr_t = std::min(max_IQR, num_obs-1); dc.SetPen(GdaConst::boxplot_q1q2q3_color); dc.SetBrush(GdaConst::boxplot_q1q2q3_color); for (int i=iqr_s; i<=iqr_t; i++) { @@ -452,9 +452,10 @@ void BoxPlotCanvas::update(HLStateInt* o) wxString BoxPlotCanvas::GetCanvasTitle() { - wxString s("Box Plot (Hinge="); - if (hinge_15) s << "1.5): "; - else s << "3.0): "; + wxString s = _("Box Plot"); + if (hinge_15) s << " (Hinge=1.5): "; + else s << " (Hinge=3.0): "; + if (cur_first_ind == cur_last_ind) { s << GetNameWithTime(0); } else { @@ -465,6 +466,20 @@ wxString BoxPlotCanvas::GetCanvasTitle() return s; } +wxString BoxPlotCanvas::GetVariableNames() +{ + wxString s; + + if (cur_first_ind == cur_last_ind) { + s << GetNameWithTime(0); + } else { + s << var_info[0].name << " ("; + s << project->GetTableInt()->GetTimeString(cur_first_ind) << "-"; + s << project->GetTableInt()->GetTimeString(cur_last_ind) << ")"; + } + return s; +} + wxString BoxPlotCanvas::GetNameWithTime(int var) { if (var < 0 || var >= var_info.size()) return wxEmptyString; @@ -608,14 +623,46 @@ void BoxPlotCanvas::PopulateCanvas() int cols = 1; int rows = 8; std::vector vals(rows); - vals[0] << GenUtils::DblToStr(hinge_stats[t].min_val, 4); - vals[1] << GenUtils::DblToStr(hinge_stats[t].max_val, 4); - vals[2] << GenUtils::DblToStr(hinge_stats[t].Q1, 4); - vals[3] << GenUtils::DblToStr(hinge_stats[t].Q2, 4); - vals[4] << GenUtils::DblToStr(hinge_stats[t].Q3, 4); - vals[5] << GenUtils::DblToStr(hinge_stats[t].IQR, 4); - vals[6] << GenUtils::DblToStr(data_stats[t].mean, 4); - vals[7] << GenUtils::DblToStr(data_stats[t].sd_with_bessel, 4); + + if ((int)hinge_stats[t].min_val == hinge_stats[t].min_val) + vals[0] << GenUtils::IntToStr(hinge_stats[t].min_val); + else + vals[0] << GenUtils::DblToStr(hinge_stats[t].min_val, 4); + + if ((int)hinge_stats[t].max_val == hinge_stats[t].max_val) + vals[1] << GenUtils::IntToStr(hinge_stats[t].max_val); + else + vals[1] << GenUtils::DblToStr(hinge_stats[t].max_val, 4); + + if ((int)hinge_stats[t].Q1 == hinge_stats[t].Q1) + vals[2] << GenUtils::IntToStr(hinge_stats[t].Q1); + else + vals[2] << GenUtils::DblToStr(hinge_stats[t].Q1, 4); + + if ((int)hinge_stats[t].Q2 == hinge_stats[t].Q2) + vals[3] << GenUtils::IntToStr(hinge_stats[t].Q2); + else + vals[3] << GenUtils::DblToStr(hinge_stats[t].Q2, 4); + + if ((int)hinge_stats[t].Q3 == hinge_stats[t].Q3) + vals[4] << GenUtils::IntToStr(hinge_stats[t].Q3); + else + vals[4] << GenUtils::DblToStr(hinge_stats[t].Q3, 4); + + if ((int)hinge_stats[t].IQR == hinge_stats[t].IQR) + vals[5] << GenUtils::IntToStr(hinge_stats[t].IQR); + else + vals[5] << GenUtils::DblToStr(hinge_stats[t].IQR, 4); + + if ((int)data_stats[t].mean == data_stats[t].mean) + vals[6] << GenUtils::IntToStr(data_stats[t].mean); + else + vals[6] << GenUtils::DblToStr(data_stats[t].mean, 4); + + if ((int)data_stats[t].sd_with_bessel == data_stats[t].sd_with_bessel) + vals[7] << GenUtils::IntToStr(data_stats[t].sd_with_bessel); + else + vals[7] << GenUtils::DblToStr(data_stats[t].sd_with_bessel, 4); std::vector attribs(0); // undefined s = new GdaShapeTable(vals, attribs, rows, cols, @@ -757,8 +804,8 @@ void BoxPlotCanvas::TimeChange() int time_steps = project->GetTableInt()->GetTimeSteps(); int start = var_info[0].time - cur_num_plots/2; if (cur_num_plots % 2 == 0) start++; - start = GenUtils::max(start, 0); - start = GenUtils::min(start, time_steps-cur_num_plots); + start = std::max(start, 0); + start = std::min(start, time_steps-cur_num_plots); if (cur_first_ind == start) return; @@ -818,8 +865,8 @@ void BoxPlotCanvas::PlotsPerView(int plots_per_view) int time_steps = project->GetTableInt()->GetTimeSteps(); int start = var_info[0].time - cur_num_plots/2; if (cur_num_plots % 2 == 0) start++; - start = GenUtils::max(start, 0); - start = GenUtils::min(start, time_steps-cur_num_plots); + start = std::max(start, 0); + start = std::min(start, time_steps-cur_num_plots); cur_first_ind = start; cur_last_ind = cur_first_ind + cur_num_plots - 1; @@ -891,7 +938,7 @@ void BoxPlotCanvas::UpdateStatusBar() wxString s; if (highlight_state->GetTotalHighlighted()> 0) { int n_total_hl = highlight_state->GetTotalHighlighted(); - s << "#selected=" << n_total_hl << " "; + s << _("#selected=") << n_total_hl << " "; if (num_time_vals == 1) { int t = 0; @@ -902,7 +949,7 @@ void BoxPlotCanvas::UpdateStatusBar() } } if (n_undefs> 0) { - s << "(undefined:" << n_undefs << ") "; + s << _("undefined: ") << n_undefs << ") "; } } else { wxString str; @@ -918,22 +965,22 @@ void BoxPlotCanvas::UpdateStatusBar() } } if (!str.IsEmpty()) { - s << "(undefined:" << str << ")"; + s << _("undefined: ") << str << ")"; } } } if (mousemode == select && selectstate == start) { if (total_hover_obs >= 1) { - s << "hover obs " << hover_obs[0]+1; + s << _("#hover obs ") << hover_obs[0]+1; } if (total_hover_obs >= 2) { s << ", "; - s << "obs " << hover_obs[1]+1; + s << _("obs ") << hover_obs[1]+1; } if (total_hover_obs >= 3) { s << ", "; - s << "obs " << hover_obs[2]+1; + s << _("obs ") << hover_obs[2]+1; } if (total_hover_obs >= 4) { s << ", ..."; @@ -994,7 +1041,7 @@ void BoxPlotFrame::MapMenus() ((BoxPlotCanvas*) template_canvas)-> AddTimeVariantOptionsToMenu(optMenu); ((BoxPlotCanvas*) template_canvas)->SetCheckMarks(optMenu); - GeneralWxUtils::ReplaceMenu(mb, "Options", optMenu); + GeneralWxUtils::ReplaceMenu(mb, _("Options"), optMenu); UpdateOptionMenuItems(); } @@ -1002,7 +1049,7 @@ void BoxPlotFrame::UpdateOptionMenuItems() { TemplateFrame::UpdateOptionMenuItems(); // set common items first wxMenuBar* mb = GdaFrame::GetGdaFrame()->GetMenuBar(); - int menu = mb->FindMenu("Options"); + int menu = mb->FindMenu(_("Options")); if (menu == wxNOT_FOUND) { } else { ((BoxPlotCanvas*) template_canvas)->SetCheckMarks(mb->GetMenu(menu)); diff --git a/Explore/BoxNewPlotView.h b/Explore/BoxNewPlotView.h index 37a660b53..db352eb08 100644 --- a/Explore/BoxNewPlotView.h +++ b/Explore/BoxNewPlotView.h @@ -47,6 +47,7 @@ class BoxPlotCanvas : public TemplateCanvas { virtual void AddTimeVariantOptionsToMenu(wxMenu* menu); virtual void update(HLStateInt* o); virtual wxString GetCanvasTitle(); + virtual wxString GetVariableNames(); virtual wxString GetNameWithTime(int var); virtual wxString GetNameWithTime(int var, int time); virtual wxString GetTimeString(int var, int time); @@ -57,12 +58,10 @@ class BoxPlotCanvas : public TemplateCanvas { virtual void DrawSelectableShapes(wxMemoryDC &dc); virtual void DrawHighlightedShapes(wxMemoryDC &dc); -protected: virtual void PopulateCanvas(); virtual void TimeChange(); void VarInfoAttributeChange(); -public: virtual void TimeSyncVariableToggle(int var_index); virtual void FixedScaleVariableToggle(int var_index); virtual void PlotsPerView(int plots_per_view); @@ -74,9 +73,9 @@ class BoxPlotCanvas : public TemplateCanvas { bool IsShowAxes() { return show_axes; } void Hinge15(); void Hinge30(); + virtual void UpdateStatusBar(); protected: - virtual void UpdateStatusBar(); int num_obs; int num_time_vals; @@ -119,7 +118,7 @@ class BoxPlotFrame : public TemplateFrame { BoxPlotFrame(wxFrame *parent, Project* project, const std::vector& var_info, const std::vector& col_ids, - const wxString& title = "Box Plot", + const wxString& title = _("Box Plot"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = GdaConst::boxplot_default_size, const long style = wxDEFAULT_FRAME_STYLE); diff --git a/Explore/CartogramNewView.cpp b/Explore/CartogramNewView.cpp index 57e5a46ce..aef47968d 100644 --- a/Explore/CartogramNewView.cpp +++ b/Explore/CartogramNewView.cpp @@ -36,9 +36,9 @@ #include "../GeoDa.h" #include "../Project.h" #include "../ShapeOperations/GalWeight.h" -#include "../ShapeOperations/ShapeUtils.h" #include "../ShapeOperations/VoronoiUtils.h" #include "CartogramNewView.h" +#include "MapLayoutView.h" using namespace std; @@ -229,8 +229,7 @@ void CartogramNewCanvas::DisplayRightClickMenu(const wxPoint& pos) wxActivateEvent ae(wxEVT_NULL, true, 0, wxActivateEvent::Reason_Mouse); ((CartogramNewFrame*) template_frame)->OnActivate(ae); - wxMenu* optMenu = wxXmlResource::Get()-> - LoadMenu("ID_CARTOGRAM_NEW_VIEW_MENU_OPTIONS"); + wxMenu* optMenu = wxXmlResource::Get()->LoadMenu("ID_CARTOGRAM_NEW_VIEW_MENU_OPTIONS"); AddTimeVariantOptionsToMenu(optMenu); TemplateCanvas::AppendCustomCategories(optMenu, project->GetCatClassifManager()); SetCheckMarks(optMenu); @@ -266,41 +265,25 @@ void CartogramNewCanvas::SetCheckMarks(wxMenu* menu) // following menu items if they were specified for this particular // view in the xrc file. Items that cannot be enable/disabled, // or are not checkable do not appear. - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_MAPANALYSIS_THEMELESS"), GetCcType() == CatClassification::no_theme); - - // since XRCID is a macro, we can't make this into a loop - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_QUANTILE_1"), - (GetCcType() == CatClassification::quantile) - && GetNumCats() == 1); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_QUANTILE_2"), - (GetCcType() == CatClassification::quantile) - && GetNumCats() == 2); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_QUANTILE_3"), - (GetCcType() == CatClassification::quantile) - && GetNumCats() == 3); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_QUANTILE_4"), - (GetCcType() == CatClassification::quantile) - && GetNumCats() == 4); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_QUANTILE_5"), - (GetCcType() == CatClassification::quantile) - && GetNumCats() == 5); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_QUANTILE_6"), - (GetCcType() == CatClassification::quantile) - && GetNumCats() == 6); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_QUANTILE_7"), - (GetCcType() == CatClassification::quantile) - && GetNumCats() == 7); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_QUANTILE_8"), - (GetCcType() == CatClassification::quantile) - && GetNumCats() == 8); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_QUANTILE_9"), - (GetCcType() == CatClassification::quantile) - && GetNumCats() == 9); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_QUANTILE_10"), - (GetCcType() == CatClassification::quantile) - && GetNumCats() == 10); + + for (int i=1; i<=10; i++) { + wxString str_xrcid; + bool flag; + + str_xrcid = wxString::Format("ID_QUANTILE_%d", i); + flag = GetCcType()==CatClassification::quantile && GetNumCats()==i; + GeneralWxUtils::CheckMenuItem(menu, XRCID(str_xrcid), flag); + + str_xrcid = wxString::Format("ID_EQUAL_INTERVALS_%d", i); + flag = GetCcType()==CatClassification::equal_intervals && GetNumCats()==i; + GeneralWxUtils::CheckMenuItem(menu, XRCID(str_xrcid), flag); + + str_xrcid = wxString::Format("ID_NATURAL_BREAKS_%d", i); + flag = GetCcType()==CatClassification::natural_breaks && GetNumCats()==i; + GeneralWxUtils::CheckMenuItem(menu, XRCID(str_xrcid), flag); + } GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_MAPANALYSIS_CHOROPLETH_PERCENTILE"), @@ -315,90 +298,6 @@ void CartogramNewCanvas::SetCheckMarks(wxMenu* menu) GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_MAPANALYSIS_UNIQUE_VALUES"), GetCcType() == CatClassification::unique_values); - // since XRCID is a macro, we can't make this into a loop - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_EQUAL_INTERVALS_1"), - (GetCcType() == - CatClassification::equal_intervals) - && GetNumCats() == 1); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_EQUAL_INTERVALS_2"), - (GetCcType() == - CatClassification::equal_intervals) - && GetNumCats() == 2); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_EQUAL_INTERVALS_3"), - (GetCcType() == - CatClassification::equal_intervals) - && GetNumCats() == 3); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_EQUAL_INTERVALS_4"), - (GetCcType() == - CatClassification::equal_intervals) - && GetNumCats() == 4); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_EQUAL_INTERVALS_5"), - (GetCcType() == - CatClassification::equal_intervals) - && GetNumCats() == 5); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_EQUAL_INTERVALS_6"), - (GetCcType() == - CatClassification::equal_intervals) - && GetNumCats() == 6); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_EQUAL_INTERVALS_7"), - (GetCcType() == - CatClassification::equal_intervals) - && GetNumCats() == 7); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_EQUAL_INTERVALS_8"), - (GetCcType() == - CatClassification::equal_intervals) - && GetNumCats() == 8); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_EQUAL_INTERVALS_9"), - (GetCcType() == - CatClassification::equal_intervals) - && GetNumCats() == 9); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_EQUAL_INTERVALS_10"), - (GetCcType() == - CatClassification::equal_intervals) - && GetNumCats() == 10); - - // since XRCID is a macro, we can't make this into a loop - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_NATURAL_BREAKS_1"), - (GetCcType() == - CatClassification::natural_breaks) - && GetNumCats() == 1); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_NATURAL_BREAKS_2"), - (GetCcType() == - CatClassification::natural_breaks) - && GetNumCats() == 2); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_NATURAL_BREAKS_3"), - (GetCcType() == - CatClassification::natural_breaks) - && GetNumCats() == 3); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_NATURAL_BREAKS_4"), - (GetCcType() == - CatClassification::natural_breaks) - && GetNumCats() == 4); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_NATURAL_BREAKS_5"), - (GetCcType() == - CatClassification::natural_breaks) - && GetNumCats() == 5); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_NATURAL_BREAKS_6"), - (GetCcType() == - CatClassification::natural_breaks) - && GetNumCats() == 6); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_NATURAL_BREAKS_7"), - (GetCcType() == - CatClassification::natural_breaks) - && GetNumCats() == 7); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_NATURAL_BREAKS_8"), - (GetCcType() == - CatClassification::natural_breaks) - && GetNumCats() == 8); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_NATURAL_BREAKS_9"), - (GetCcType() == - CatClassification::natural_breaks) - && GetNumCats() == 9); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_NATURAL_BREAKS_10"), - (GetCcType() == - CatClassification::natural_breaks) - && GetNumCats() == 10); - vector txt(6); for (size_t i=0; i= (int)var_info.size()) return wxEmptyString; @@ -535,7 +442,7 @@ void CartogramNewCanvas::NewCustomCatClassif() if (template_frame) { template_frame->UpdateTitle(); if (template_frame->GetTemplateLegend()) { - template_frame->GetTemplateLegend()->Refresh(); + template_frame->GetTemplateLegend()->Recreate(); } } } @@ -579,7 +486,7 @@ ChangeThemeType(CatClassification::CatClassifType new_cat_theme, if (all_init && template_frame) { template_frame->UpdateTitle(); if (template_frame->GetTemplateLegend()) { - template_frame->GetTemplateLegend()->Refresh(); + template_frame->GetTemplateLegend()->Recreate(); } } } @@ -596,7 +503,7 @@ void CartogramNewCanvas::update(CatClassifState* o) if (template_frame) { template_frame->UpdateTitle(); if (template_frame->GetTemplateLegend()) { - template_frame->GetTemplateLegend()->Refresh(); + template_frame->GetTemplateLegend()->Recreate(); } } } @@ -749,14 +656,14 @@ void CartogramNewCanvas::CreateAndUpdateCategories() for (int t=0; tGetTotalHighlighted()> 0) { - s << "#selected=" << highlight_state->GetTotalHighlighted()<<" "; + s << _("#selected=") << highlight_state->GetTotalHighlighted()<<" "; } if (mousemode == select && selectstate == start) { if (total_hover_obs >= 1) { - s << "hover obs " << hover_obs[0]+1 << " = ("; + s << _("#hover obs ") << hover_obs[0]+1 << " = ("; s << data[RAD_VAR][var_info[RAD_VAR].time][hover_obs[0]] << ", "; s << data[THM_VAR][var_info[THM_VAR].time][hover_obs[0]] << ")"; } if (total_hover_obs >= 2) { s << ", "; - s << "obs " << hover_obs[1]+1 << " = ("; + s << _("obs ") << hover_obs[1]+1 << " = ("; s << data[RAD_VAR][var_info[RAD_VAR].time][hover_obs[1]] << ", "; s << data[THM_VAR][var_info[THM_VAR].time][hover_obs[1]] << ")"; } if (total_hover_obs >= 3) { s << ", "; - s << "obs " << hover_obs[2]+1 << " = ("; + s << _("obs ") << hover_obs[2]+1 << " = ("; s << data[RAD_VAR][var_info[RAD_VAR].time][hover_obs[2]] << ", "; s << data[THM_VAR][var_info[THM_VAR].time][hover_obs[2]] << ")"; } @@ -857,7 +764,7 @@ void CartogramNewCanvas::ImproveAll(double max_seconds, int max_iters) // report actual elapsed time. int update_rounds = 1; // do one round of batches by default - int iters = GenUtils::min(max_iters, EstItersGivenTime(max_seconds)); + int iters = std::min(max_iters, EstItersGivenTime(max_seconds)); int est_secs = EstSecondsGivenIters(iters); int num_batches = GetNumBatches(); if (realtime_updates && est_secs > 2) { @@ -876,7 +783,7 @@ void CartogramNewCanvas::ImproveAll(double max_seconds, int max_iters) int num_carts_rem = GetCurNumCartTms(); int crt_min_tm = var_info[RAD_VAR].time_min; for (int i=0; i 0; i++) { - int num_in_batch = GenUtils::min(num_cpus, num_carts_rem); + int num_in_batch = std::min(num_cpus, num_carts_rem); if (num_in_batch > 1) { // mutext protects access to the worker_list @@ -1078,10 +985,12 @@ CartogramNewFrame::CartogramNewFrame(wxFrame *parent, Project* project, wxPanel* toolbar_panel = new wxPanel(this,-1, wxDefaultPosition); wxBoxSizer* toolbar_sizer= new wxBoxSizer(wxVERTICAL); - wxToolBar* tb = wxXmlResource::Get()->LoadToolBar(toolbar_panel, "ToolBar_MAP"); + toolbar = wxXmlResource::Get()->LoadToolBar(toolbar_panel, "ToolBar_MAP"); SetupToolbar(); - tb->EnableTool(XRCID("ID_TOOLBAR_BASEMAP"), false); - toolbar_sizer->Add(tb, 0, wxEXPAND|wxALL); + toolbar->EnableTool(XRCID("ID_TOOLBAR_BASEMAP"), false); + toolbar->EnableTool(XRCID("ID_ADD_LAYER"), false); + toolbar->EnableTool(XRCID("ID_EDIT_LAYER"), false); + toolbar_sizer->Add(toolbar, 0, wxEXPAND|wxALL); toolbar_panel->SetSizerAndFit(toolbar_sizer); wxBoxSizer* sizer = new wxBoxSizer(wxVERTICAL); @@ -1171,7 +1080,7 @@ void CartogramNewFrame::MapMenus() ((CartogramNewCanvas*) template_canvas)->AddTimeVariantOptionsToMenu(optMenu); TemplateCanvas::AppendCustomCategories(optMenu, project->GetCatClassifManager()); ((CartogramNewCanvas*) template_canvas)->SetCheckMarks(optMenu); - GeneralWxUtils::ReplaceMenu(mb, "Options", optMenu); + GeneralWxUtils::ReplaceMenu(mb, _("Options"), optMenu); UpdateOptionMenuItems(); } @@ -1179,7 +1088,7 @@ void CartogramNewFrame::UpdateOptionMenuItems() { TemplateFrame::UpdateOptionMenuItems(); // set common items first wxMenuBar* mb = GdaFrame::GetGdaFrame()->GetMenuBar(); - int menu = mb->FindMenu("Options"); + int menu = mb->FindMenu(_("Options")); if (menu == wxNOT_FOUND) { } else { ((CartogramNewCanvas*) @@ -1283,3 +1192,25 @@ void CartogramNewFrame::CartogramImproveLevel(int level) ((CartogramNewCanvas*) template_canvas)->CartogramImproveLevel(level); UpdateOptionMenuItems(); } + +void CartogramNewFrame::ExportImage(TemplateCanvas* canvas, const wxString& type) +{ + wxLogMessage("Entering CartogramNewFrame::ExportImage"); + + // main map + wxBitmap* main_map = template_canvas->GetPrintLayer(); + int map_width = main_map->GetWidth(); + int map_height = main_map->GetHeight(); + + // try to keep maplayout dialog fixed size + int dlg_width = 900; + int dlg_height = dlg_width * map_height / (double)map_width + 160; + + CanvasLayoutDialog ml_dlg(project->GetProjectTitle(), + template_legend, template_canvas, + _("Canvas Layout Preview"), + wxDefaultPosition, + wxSize(dlg_width, dlg_height) ); + + ml_dlg.ShowModal(); +} diff --git a/Explore/CartogramNewView.h b/Explore/CartogramNewView.h index 5e8512be5..862f04511 100644 --- a/Explore/CartogramNewView.h +++ b/Explore/CartogramNewView.h @@ -75,6 +75,7 @@ class CartogramNewCanvas : public TemplateCanvas, public CatClassifStateObserver virtual void AddTimeVariantOptionsToMenu(wxMenu* menu); virtual wxString GetCategoriesTitle(); virtual wxString GetCanvasTitle(); + virtual wxString GetVariableNames(); virtual wxString GetNameWithTime(int var); virtual void NewCustomCatClassif(); virtual void ChangeThemeType( @@ -86,17 +87,18 @@ class CartogramNewCanvas : public TemplateCanvas, public CatClassifStateObserver virtual void SetCheckMarks(wxMenu* menu); virtual void TimeChange(); -public: virtual void PopulateCanvas(); virtual void VarInfoAttributeChange(); virtual void CreateAndUpdateCategories(); - -public: virtual void TimeSyncVariableToggle(int var_index); CatClassifDef cat_classif_def; CatClassification::CatClassifType GetCcType(); virtual int GetNumCats() { return num_categories; } + void CartogramImproveLevel(int level); + void UpdateImproveLevelTable(); + virtual void UpdateStatusBar(); + protected: TableInterface* table_int; CatClassifState* custom_classif_state; @@ -139,11 +141,6 @@ class CartogramNewCanvas : public TemplateCanvas, public CatClassifStateObserver int GetNumBatches(); Gda::dbl_int_pair_vec_type improve_table; -public: - void CartogramImproveLevel(int level); - void UpdateImproveLevelTable(); - -protected: bool full_map_redraw_needed; GalWeight* gal_weight; @@ -152,7 +149,6 @@ class CartogramNewCanvas : public TemplateCanvas, public CatClassifStateObserver static const int THM_VAR; // circle color variable bool all_init; - virtual void UpdateStatusBar(); DECLARE_EVENT_TABLE() }; @@ -199,7 +195,7 @@ class CartogramNewFrame : public TemplateFrame { virtual void OnSaveCategories(); virtual void CartogramImproveLevel(int level); - + virtual void ExportImage(TemplateCanvas* canvas, const wxString& type); protected: void SetupToolbar(); void OnMapSelect(wxCommandEvent& e); diff --git a/Explore/CatClassification.cpp b/Explore/CatClassification.cpp index d1ff47288..6ea099721 100644 --- a/Explore/CatClassification.cpp +++ b/Explore/CatClassification.cpp @@ -68,14 +68,14 @@ void create_unique_val_mapping(std::vector& uv_mapping, } /** Assume that b.size() <= N-1 */ -void pick_rand_breaks(std::vector& b, int N) +void pick_rand_breaks(std::vector& b, int N, boost::uniform_01& X) { int num_breaks = b.size(); if (num_breaks > N-1) return; // Mersenne Twister random number generator, randomly seeded // with current time in seconds since Jan 1 1970. - static boost::mt19937 rng(std::time(0)); - static boost::uniform_01 X(rng); + //static boost::mt19937 rng(GdaConst::gda_user_seed); + //static boost::uniform_01 X(rng); std::set s; while (s.size() != num_breaks) s.insert(1 + (N-1)*X()); @@ -132,10 +132,8 @@ void CatClassification::CatLabelsFromBreaks(const std::vector& breaks, bool useScientificNotation) { stringstream s; - if (useScientificNotation) - s << std::setprecision(2) << std::scientific; - else - s << std::setprecision(3); + if (useScientificNotation) s << std::setprecision(3) << std::scientific; + else s << std::setprecision(3) << std::fixed; int num_breaks = breaks.size(); int cur_intervals = num_breaks+1; @@ -171,8 +169,17 @@ void CatClassification::CatLabelsFromBreaks(const std::vector& breaks, a = "("; b = "]"; } - s << a << breaks[ival-1] << ", "; - s << breaks[ival] << b; + s << a ; + if (breaks[ival-1] == (int)breaks[ival-1]) + s << wxString::Format("%d", (int) breaks[ival-1]); + else + s << breaks[ival-1]; + s << ", "; + if (breaks[ival] == (int)breaks[ival]) + s << wxString::Format("%d", (int) breaks[ival]); + else + s << breaks[ival]; + s << b; } cat_labels[ival] = s.str(); } @@ -220,12 +227,12 @@ void CatClassification::SetBreakPoints(std::vector& breaks, breaks[3] = hinge_stats.Q3; breaks[4] = (theme == hinge_15 ? hinge_stats.extreme_upper_val_15 : hinge_stats.extreme_upper_val_30); - cat_labels[0] = "Lower outlier"; + cat_labels[0] = _("Lower outlier"); cat_labels[1] = "< 25%"; cat_labels[2] = "25% - 50%"; cat_labels[3] = "50% - 75%"; cat_labels[4] = "> 75%"; - cat_labels[5] = "Upper outlier"; + cat_labels[5] = _("Upper outlier"); } else if (theme == quantile) { if (num_cats == 1) { @@ -303,7 +310,7 @@ void CatClassification::SetBreakPoints(std::vector& breaks, FindNaturalBreaks(num_cats, var, var_undef, breaks); CatLabelsFromBreaks(breaks, cat_labels, theme, useScientificNotation); - } else if (theme == equal_intervals) { + } else { double min_val = var[0].first; double max_val = var[0].first; for (int i=0; i& breaks, breaks[i] = min_val + (((double) i) + 1.0)*delta; } } - CatLabelsFromBreaks(breaks, cat_labels, theme, useScientificNotation); + if (theme != custom) + CatLabelsFromBreaks(breaks, cat_labels, theme, useScientificNotation); } } +void +CatClassification:: +PopulateCatClassifData(const CatClassifDef& cat_def, + const std::vector& var, + const std::vector >& var_undef, + CatClassifData& cat_data, + std::vector& cats_valid, + std::vector& cats_error_message, + bool useSciNotation, + bool useUndefinedCategory) +{ + // this function is only for string type unique values (categorical classification) + // theme == unique_values) + // The Unique Values theme is somewhat different from the other themes + // in that we calculate the number from the data itself. We support + // at most 20 unique values. + + CatClassifType theme = cat_def.cat_classif_type; + + if (theme != CatClassification::unique_values) + return; + + // number of categories based on number of unique values in data + int num_time_vals = var.size(); + int num_obs = var[0].size(); + cat_data.CreateEmptyCategories(num_time_vals, num_obs); + + // detect if undefined category + std::vector undef_cnts_tms(num_time_vals, 0); + for (int t=0; t num_obs) { + for (int t=0; t > u_vals_map(num_time_vals); + for (int t=0; t dup_dict; + for (int i=0; i max_num_categories) + n_cat = max_num_categories; + bool reversed = false; + cat_data.SetCategoryBrushesAtCanvasTm(CatClassification::unique_color_scheme, + n_cat, reversed, t); + } + cat_data.ResetAllCategoryMinMax(); + for (int t=0; t0 && useUndefinedCategory) + cat_data.AppendUndefCategory(t, undef_cnts_tms[t]); + + for (int cat=0; cat < u_vals_map[t].size(); cat++) { + wxString unique_val = u_vals_map[t][cat]; + for (int i=0; i max_num_categories) + n_cat = max_num_categories; + + std::vector labels(n_cat); + for (int cat=0; cat num_obs) { for (int t=0; t labels(num_cats); - labels[0] << "Lower outlier"; + labels[0] << _("Lower outlier"); labels[1] << "< 25%"; labels[2] << "25% - 50%"; labels[3] << "50% - 75%"; labels[4] << "> 75%"; - labels[5] << "Upper outlier"; + labels[5] << _("Upper outlier"); std::vector labels_ext(num_cats); ss.str(""); if (cat_data.GetNumObsInCategory(t, 0) == 0) { - ss << " [-inf : " << extreme_lower << "]"; + ss << " [-inf : "; + if (extreme_lower == (int)extreme_lower) + ss << (int)extreme_lower; + else + ss << extreme_lower; + ss << "]"; } else { - ss << " [" << p_min << " : " << extreme_lower << "]"; + ss << " ["; + if (p_min == (int)p_min) ss << (int)p_min; + else ss << p_min; + ss << " : "; + if (extreme_lower == (int)extreme_lower) ss << (int)extreme_lower; + else ss << extreme_lower; + ss << "]"; } labels_ext[0] = ss.str(); ss.str(""); cat_data.SetCategoryMinMax(t, 0, p_min, extreme_lower); - ss << " [" << extreme_lower << " : " << hinge_stats[t].Q1 << "]"; + ss << " ["; + if (extreme_lower == (int)extreme_lower) ss << (int)extreme_lower; + else ss << extreme_lower; + ss << " : "; + if (hinge_stats[t].Q1 == (int)hinge_stats[t].Q1) ss << (int)hinge_stats[t].Q1; + else ss << hinge_stats[t].Q1; + ss << "]"; labels_ext[1] = ss.str(); ss.str(""); cat_data.SetCategoryMinMax(t, 1, extreme_lower, hinge_stats[t].Q1); - ss << " [" << hinge_stats[t].Q1 << " : " << hinge_stats[t].Q2 << "]"; + ss << " ["; + if (hinge_stats[t].Q1 == (int)hinge_stats[t].Q1) ss << (int)hinge_stats[t].Q1; + else ss << hinge_stats[t].Q1; + ss << " : "; + if (hinge_stats[t].Q2 == (int)hinge_stats[t].Q2) ss << (int)hinge_stats[t].Q2; + else ss << hinge_stats[t].Q2; + ss << "]"; labels_ext[2] = ss.str(); ss.str(""); cat_data.SetCategoryMinMax(t, 2, hinge_stats[t].Q1, hinge_stats[t].Q2); - ss << " [" << hinge_stats[t].Q2 << " : " << hinge_stats[t].Q3 << "]"; + ss << " ["; + if (hinge_stats[t].Q2 == (int)hinge_stats[t].Q2) ss << (int)hinge_stats[t].Q2; + else ss << hinge_stats[t].Q2; + ss << " : "; + if (hinge_stats[t].Q3 == (int)hinge_stats[t].Q3) ss << (int)hinge_stats[t].Q3; + else ss << hinge_stats[t].Q3; + ss << "]"; labels_ext[3] = ss.str(); ss.str(""); cat_data.SetCategoryMinMax(t, 3, hinge_stats[t].Q2, hinge_stats[t].Q3); - ss << " [" << hinge_stats[t].Q3 << " : " << extreme_upper << "]"; + ss << " ["; + if (hinge_stats[t].Q3 == (int)hinge_stats[t].Q3) ss << (int)hinge_stats[t].Q3; + else ss << hinge_stats[t].Q3; + ss << " : "; + if (extreme_upper == (int)extreme_upper) ss << (int)extreme_upper; + else ss << extreme_upper; + ss << "]"; labels_ext[4] = ss.str(); ss.str(""); cat_data.SetCategoryMinMax(t, 4, hinge_stats[t].Q3, extreme_upper); if (cat_data.GetNumObsInCategory(t, num_cats-1) == 0 && - p_max > extreme_upper) - ss << " [" << extreme_upper << " : " << p_max << "]"; - else - ss << " [" << extreme_upper << " : inf]"; + p_max > extreme_upper) { + ss << " ["; + if (extreme_upper == (int)extreme_upper) ss << (int)extreme_upper; + else ss << extreme_upper; + ss << " : "; + if (p_max == (int)p_max) ss << (int)p_max; + else ss << p_max; + ss << "]"; + } else { + ss << " ["; + if (extreme_upper == (int)extreme_upper) ss << (int)extreme_upper; + else ss << extreme_upper; + ss << " : inf]"; + } labels_ext[5] = ss.str(); cat_data.SetCategoryMinMax(t, 5, extreme_upper, p_max); @@ -648,52 +825,83 @@ PopulateCatClassifData(const CatClassifDef& cat_def, } cat_data.AppendIdToCategory(t, cat, ind); } - - for (int ival=0; ival " << cat_def.breaks[ival-1]; - cat_data.SetCategoryCount(t, ival, - cat_data.GetNumObsInCategory(t, ival)); - } else if (ival == num_cats-1 && num_cats == 2) { - ss << ">= " << cat_def.breaks[ival-1]; - cat_data.SetCategoryCount(t, ival, - cat_data.GetNumObsInCategory(t, ival)); - } else { - int num_breaks = num_cats-1; - int num_breaks_lower = (num_breaks+1)/2; - wxString a; - wxString b; - if (ival < num_breaks_lower) { - a = "["; - b = ")"; - } else if (ival == num_breaks_lower) { - a = "["; - b = "]"; - } else { - a = "("; - b = "]"; - } - ss << a << cat_def.breaks[ival-1] << ", "; - ss << cat_def.breaks[ival] << b; - cat_data.SetCategoryCount(t, ival, - cat_data.GetNumObsInCategory(t, ival)); - } - if (cat_def.names[ival].IsEmpty()) { + + if (cat_def.automatic_labels) { + for (int ival=0; ival "; + if ( cat_def.breaks[ival-1] == (int) cat_def.breaks[ival-1]) + ss << (int)cat_def.breaks[ival-1]; + else + ss << cat_def.breaks[ival-1]; + cat_data.SetCategoryCount(t, ival, cat_data.GetNumObsInCategory(t, ival)); + + } else if (ival == num_cats-1 && num_cats == 2) { + ss << ">= "; + if ( cat_def.breaks[ival-1] == (int) cat_def.breaks[ival-1]) + ss << (int)cat_def.breaks[ival-1]; + else + ss << cat_def.breaks[ival-1]; + cat_data.SetCategoryCount(t, ival, cat_data.GetNumObsInCategory(t, ival)); + + } else { + int num_breaks = num_cats-1; + int num_breaks_lower = (num_breaks+1)/2; + wxString a; + wxString b; + if (ival < num_breaks_lower) { + a = "["; + b = ")"; + } else if (ival == num_breaks_lower) { + a = "["; + b = "]"; + } else { + a = "("; + b = "]"; + } + ss << a; + if (cat_def.breaks[ival-1] == (int)cat_def.breaks[ival-1]) + ss << wxString::Format("%d", (int) cat_def.breaks[ival-1]); + else + ss << cat_def.breaks[ival-1]; + ss << ", "; + if (cat_def.breaks[ival] == (int)cat_def.breaks[ival]) + ss << wxString::Format("%d", (int) cat_def.breaks[ival]); + else + ss << cat_def.breaks[ival]; + ss << b; + cat_data.SetCategoryCount(t, ival, cat_data.GetNumObsInCategory(t, ival)); + + } cat_data.SetCategoryLabel(t, ival, wxString(ss.str())); - } else { + cat_data.SetCategoryMinMax(t, ival, + cat_min[ival], cat_max[ival]); + } + } else { + for (int ival=0; ival labels_ext(num_cats); ss.str(""); - ss << " [" << p_min << " : " << p_1 << "]"; + ss << " ["; + if (p_min==(int)p_min) ss << (int)p_min; else ss << p_min; + ss << " : "; + if (p_1==(int)p_1) ss << (int)p_1; else ss << p_1; + ss<< "]"; labels_ext[0] = ss.str(); ss.str(""); - ss << " [" << p_1 << " : " << p_10 << "]"; + ss << " ["; + if (p_1==(int)p_1) ss << (int)p_1; else ss << p_1; + ss << " : "; + if (p_10==(int)p_10) ss << (int)p_10; else ss << p_10; + ss << "]"; labels_ext[1] = ss.str(); ss.str(""); - ss << " [" << p_10 << " : " << p_50 << "]"; + ss << " ["; + if (p_10==(int)p_10) ss << (int)p_10; else ss << p_10; + ss << " : "; + if (p_50==(int)p_50) ss << (int)p_50; else ss << p_50; + ss << "]"; labels_ext[2] = ss.str(); ss.str(""); - ss << " [" << p_50 << " : " << p_90 << "]"; + ss << " ["; + if (p_50==(int)p_50) ss << (int)p_50; else ss << p_50; + ss << " : "; + if (p_90==(int)p_90) ss << (int)p_90; else ss << p_90; + ss << "]"; labels_ext[3] = ss.str(); ss.str(""); - ss << " [" << p_90 << " : " << p_99 << "]"; + ss << " ["; + if (p_90==(int)p_90) ss << (int)p_90; else ss << p_90; + ss << " : "; + if (p_99==(int)p_99) ss << (int)p_99; else ss << p_99; + ss << "]"; labels_ext[4] = ss.str(); ss.str(""); - ss << " [" << p_99 << " : " << p_max << "]"; + ss << " ["; + if (p_99==(int)p_99) ss << (int)p_99; else ss << p_99; + ss << " : "; + if (p_max==(int)p_max) ss << (int)p_max; else ss << p_max; + ss << "]"; labels_ext[5] = ss.str(); for (int cat=0; cat 2 sd ss.str(""); - ss << "< " << SDm2; + ss << "< "; + if (SDm2 == (int)SDm2) ss << (int)SDm2; else ss << SDm2; labels[0] = ss.str(); ss.str(""); - ss << SDm2 << " - " << SDm1; + if (SDm2 == (int)SDm2) ss << (int)SDm2; else ss << SDm2; + ss << " - "; + if (SDm1 == (int)SDm1) ss << (int)SDm1; else ss << SDm1; labels[1] = ss.str(); ss.str(""); - ss << SDm1 << " - " << mean; + if (SDm1 == (int)SDm1) ss << (int)SDm1; else ss << SDm1; + ss << " - "; + if (mean == (int)mean) ss << (int)mean; else ss << mean; labels[2] = ss.str(); ss.str(""); - ss << mean << " - " << SDp1; + if (mean == (int)mean) ss << (int)mean; else ss << mean; + ss << " - "; + if (SDp1 == (int)SDp1) ss << (int)SDp1; else ss << SDp1; labels[3] = ss.str(); ss.str(""); - ss << SDp1 << " - " << SDp2; + if (SDp1 == (int)SDp1) ss << (int)SDp1; else ss << SDp1; + ss << " - "; + if (SDp2 == (int)SDp2) ss << (int)SDp2; else ss << SDp2; labels[4] = ss.str(); ss.str(""); - ss << "> " << SDp2; + ss << "> "; + if (SDp2 == (int)SDp2) ss << (int)SDp2; else ss << SDp2; labels[5] = ss.str(); for (int cat=0; catGetNumberRows(); CatClassifDef cc; cc = _cc; - + + std::vector user_def_labels = cc.names; + std::sort(cc.breaks.begin(), cc.breaks.end()); if (cc.uniform_dist_min > cc.uniform_dist_max) { double t = cc.uniform_dist_min; @@ -1281,10 +1577,7 @@ bool CatClassification::CorrectCatClassifFromTable(CatClassifDef& _cc, int col = -1, tm = 0; // first ensure that assoc_db_fld_name exists in table - bool field_removed = (cc.assoc_db_fld_name != "" && - (!table_int->DbColNmToColAndTm(cc.assoc_db_fld_name, - col, tm) || - !table_int->IsColNumeric(col))); + bool field_removed = (cc.assoc_db_fld_name != "" && (!table_int->DbColNmToColAndTm(cc.assoc_db_fld_name, col, tm) || !table_int->IsColNumeric(col))); if (field_removed) { // use min/max breaks as min/max for uniform dist @@ -1383,7 +1676,9 @@ bool CatClassification::CorrectCatClassifFromTable(CatClassifDef& _cc, if (!uni_dist_mode) { // ensure that min/max and breaks are consistent with actual min/max double col_min = 0, col_max = 0; - table_int->GetMinMaxVals(col, tm, col_min, col_max); + if (!table_int->GetMinMaxVals(col, tm, col_min, col_max)) { + return false; + } cc.uniform_dist_min = col_min; cc.uniform_dist_max = col_max; for (int i=0, sz=cc.breaks.size(); i uv_mapping; create_unique_val_mapping(uv_mapping, v, v_undef); int num_unique_vals = uv_mapping.size(); - int t_cats = GenUtils::min(num_unique_vals, num_cats); + int t_cats = std::min(num_unique_vals, num_cats); double mean = 0; int valid_obs = 0; @@ -1488,9 +1792,12 @@ void CatClassification::FindNaturalBreaks(int num_cats, int perms = c / ((double) num_obs); if (perms < 10) perms = 10; if (perms > 10000) perms = 10000; - + + boost::mt19937 rng(GdaConst::gda_user_seed); + boost::uniform_01 X(rng); + for (int i=0; i& var, const std::vector >& var_undef, CatClassifData& cat_data, std::vector& cats_valid, - CatClassification::ColorScheme coltype) + CatClassification::ColorScheme coltype, + bool useSciNotation) { int num_time_vals = var.size(); int num_obs = var[0].size(); @@ -1550,7 +1858,7 @@ SetNaturalBreaksCats(int num_cats, create_unique_val_mapping(uv_mapping, v, var_undef[t]); int num_unique_vals = uv_mapping.size(); - int t_cats = GenUtils::min(num_unique_vals, num_cats); + int t_cats = std::min(num_unique_vals, num_cats); double mean = 0; int valid_obs = 0; @@ -1586,9 +1894,12 @@ SetNaturalBreaksCats(int num_cats, int perms = c / ((double) num_time_vals * (double) valid_obs); if (perms < 10) perms = 10; if (perms > 10000) perms = 10000; - + + boost::mt19937 rng(GdaConst::gda_user_seed); + boost::uniform_01 X(rng); + for (int i=0; i0) cat_data.AppendUndefCategory(t, undef_cnts_tms[t]); - + + /* for (int i=0, nb=best_breaks.size(); i<=nb; i++) { int ss = (i == 0) ? 0 : best_breaks[i-1]; int tt = (i == nb) ? v.size() : best_breaks[i]; @@ -1613,14 +1925,95 @@ SetNaturalBreaksCats(int num_cats, int c = var_undef[t][ind] ? t_cats : i; cat_data.AppendIdToCategory(t, c, ind); } + int end = (i == nb) ? tt -1 : tt; wxString l; l << "[" << GenUtils::DblToStr(var[t][ss].first); - l << ":" << GenUtils::DblToStr(var[t][tt-1].first) << "]"; + l << ":" << GenUtils::DblToStr(var[t][end].first) << "]"; cat_data.SetCategoryLabel(t, i, l); - cat_data.SetCategoryCount(t, i, cat_data.GetNumObsInCategory(t, i)); - cat_data.SetCategoryMinMax(t, i, var[t][ss].first, - var[t][tt-1].first); + } + */ + stringstream s; + + if (useSciNotation) s << std::setprecision(3) << std::scientific; + else s << std::setprecision(3) << std::fixed; + + int num_breaks = best_breaks.size(); + int cur_intervals = num_breaks+1; + for (int ival=0; ival "; + if (var[t][ss].first == (int)var[t][ss].first) s << (int)var[t][ss].first; + else s << var[t][ss].first; + offset_ss = 1; + + } else if (ival == cur_intervals-1 && cur_intervals == 2) { + ss = best_breaks[ival-1]; + tt = v.size(); + + s << ">= "; + if (var[t][ss].first == (int)var[t][ss].first) s << (int)var[t][ss].first; + else s << var[t][ss].first; + + } else { + int num_breaks = cur_intervals-1; + int num_breaks_lower = (num_breaks+1)/2; + wxString a; + wxString b; + if (ival < num_breaks_lower) { + a = "["; + b = ")"; + ss = best_breaks[ival-1]; + tt = best_breaks[ival]; + } else if (ival == num_breaks_lower) { + a = "["; + b = "]"; + ss = best_breaks[ival-1]; + tt = best_breaks[ival]; + offset_tt = 1; + } else { + a = "("; + b = "]"; + ss = best_breaks[ival-1]; + tt = best_breaks[ival]; + offset_ss = 1; + offset_tt = 1; + } + s << a; + if (var[t][ss].first == (int)var[t][ss].first) s << (int)var[t][ss].first; + else s << var[t][ss].first; + s << ", "; + if (var[t][tt].first == (int)var[t][tt].first) s << (int)var[t][tt].first; + else s << var[t][tt].first; + s << b; + } + cat_data.SetCategoryLabel(t, ival, s.str()); + for (int j=ss+offset_ss; j& color_vec, int num_color) +{ + for (int i=0; i& color_vec, @@ -2236,6 +2636,8 @@ void CatClassifData::ExchangeLabels(int from, int to) wxBrush to_brush = categories[t].cat_vec[to].brush; wxPen from_pen = categories[t].cat_vec[from].pen; wxPen to_pen = categories[t].cat_vec[to].pen; + wxString from_lbl = categories[t].cat_vec[from].label; + wxString to_lbl = categories[t].cat_vec[to].label; Category tmp = categories[t].cat_vec[from]; categories[t].cat_vec[from] = categories[t].cat_vec[to]; @@ -2245,6 +2647,8 @@ void CatClassifData::ExchangeLabels(int from, int to) categories[t].cat_vec[to].brush = to_brush; categories[t].cat_vec[from].pen = from_pen; categories[t].cat_vec[to].pen = to_pen; + categories[t].cat_vec[from].label = from_lbl; + categories[t].cat_vec[to].label = to_lbl; } } @@ -2348,6 +2752,20 @@ void CatClassifData::SetCategoryColor(int canvas_tm, int cat, wxColour color) GdaColorUtils::ChangeBrightness(color)); } +void CatClassifData::SetCategoryBrushColor(int canvas_tm, int cat, wxColour color) +{ + if (cat <0 || cat >= categories[canvas_tm].cat_vec.size()) + return; + categories[canvas_tm].cat_vec[cat].brush.SetColour(color); +} + +void CatClassifData::SetCategoryPenColor(int canvas_tm, int cat, wxColour color) +{ + if (cat <0 || cat >= categories[canvas_tm].cat_vec.size()) + return; + categories[canvas_tm].cat_vec[cat].pen.SetColour(color); +} + wxColour CatClassifData::GetCategoryColor(int canvas_tm, int cat) { if (cat <0 || cat >= categories[canvas_tm].cat_vec.size()) diff --git a/Explore/CatClassification.h b/Explore/CatClassification.h index f6ce2565e..9b2075905 100644 --- a/Explore/CatClassification.h +++ b/Explore/CatClassification.h @@ -37,11 +37,14 @@ namespace CatClassification { const int max_num_categories = 20; - enum CatClassifType { no_theme, hinge_15, hinge_30, quantile, percentile, - stddev, excess_risk_theme, unique_values, natural_breaks, - equal_intervals, lisa_categories, lisa_significance, + enum CatClassifType { + no_theme, hinge_15, hinge_30, quantile, percentile, + stddev, excess_risk_theme, unique_values, colocation, natural_breaks, equal_intervals, + lisa_categories, lisa_significance, custom, getis_ord_categories, getis_ord_significance, - local_geary_categories, local_geary_significance,custom }; + local_geary_categories, local_geary_significance, + local_join_count_categories, local_join_count_significance + }; /** When CatClassifType != custom, BreakValsType is assumed to be by_cat_classif_type. Otherwise, if CatClassifType == custom, @@ -74,9 +77,18 @@ namespace CatClassification { std::vector& cats_error_message, bool useSciNotation=false, bool useUndefinedCategory=true); + + void PopulateCatClassifData(const CatClassifDef& cat_def, + const std::vector& var, + const std::vector >& var_undef, + CatClassifData& cat_data, std::vector& cats_valid, + std::vector& cats_error_message, + bool useSciNotation=false, + bool useUndefinedCategory=true); bool CorrectCatClassifFromTable(CatClassifDef& cc, - TableInterface* table_int); + TableInterface* table_int, + bool auto_label=true); void FindNaturalBreaks(int num_cats, const Gda::dbl_int_pair_vec_type& var, @@ -87,12 +99,14 @@ namespace CatClassification { const std::vector& var, const std::vector >& var_undef, CatClassifData& cat_data, std::vector& cats_valid, - ColorScheme coltype=CatClassification::sequential_color_scheme); + ColorScheme coltype=CatClassification::sequential_color_scheme, + bool useSciNotation=false); ColorScheme GetColSchmForType(CatClassifType theme_type); wxString CatClassifTypeToString(CatClassifType theme_type); - + + void PickColorSet(std::vector& color_vec, int num_color); void PickColorSet(std::vector& color_vec, ColorScheme coltype, int num_color, bool reversed=false); @@ -188,6 +202,8 @@ struct CatClassifData { int GetNumObsInCategory(int canvas_tm, int cat); std::vector& GetIdsRef(int canvas_tm, int cat); void SetCategoryColor(int canvas_tm, int cat, wxColour color); + void SetCategoryBrushColor(int canvas_tm, int cat, wxColour color); + void SetCategoryPenColor(int canvas_tm, int cat, wxColour color); wxColour GetCategoryColor(int canvas_tm, int cat); wxBrush GetCategoryBrush(int canvas_tm, int cat); wxPen GetCategoryPen(int canvas_tm, int cat); diff --git a/Explore/ColocationMapView.cpp b/Explore/ColocationMapView.cpp new file mode 100644 index 000000000..5684c9be7 --- /dev/null +++ b/Explore/ColocationMapView.cpp @@ -0,0 +1,866 @@ +/** + * GeoDa TM, Copyright (C) 2011-2015 by Luc Anselin - all rights reserved + * + * This file is part of GeoDa. + * + * GeoDa is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * GeoDa is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../DataViewer/TableInterface.h" +#include "../DataViewer/TimeState.h" +#include "../GeneralWxUtils.h" +#include "../GenUtils.h" +#include "../GeoDa.h" +#include "../logger.h" +#include "../Project.h" +#include "../DialogTools/PermutationCounterDlg.h" +#include "../DialogTools/SaveToTableDlg.h" +#include "../DialogTools/VariableSettingsDlg.h" +#include "../DialogTools/RandomizationDlg.h" +#include "../DialogTools/AbstractClusterDlg.h" +#include "../VarCalc/WeightsManInterface.h" + +#include "ConditionalClusterMapView.h" +#include "MapNewView.h" +#include "ColocationMapView.h" + +using namespace std; + +BEGIN_EVENT_TABLE( ColocationSelectDlg, wxDialog ) +EVT_CLOSE( ColocationSelectDlg::OnClose ) +END_EVENT_TABLE() + +ColocationSelectDlg::ColocationSelectDlg(wxFrame* parent_s, Project* project_s) +: AbstractClusterDlg(parent_s, project_s, _("Co-location Settings")) +{ + wxLogMessage("Open ColocationSelectDlg."); + + base_remove_id = XRCID("COL_REMOVE_BTN"); + base_color_id = XRCID("COL_COLOR_BTN"); + base_choice_id = XRCID("COL_CHOICE_BTN"); + + GdaColorUtils::GetUnique20Colors(m_predef_colors); + + CreateControls(); + + +} + +ColocationSelectDlg::~ColocationSelectDlg() +{ + +} + +void ColocationSelectDlg::update(TableState* o) +{ + if (o->GetEventType() != TableState::time_ids_add_remove && + o->GetEventType() != TableState::time_ids_rename && + o->GetEventType() != TableState::time_ids_swap && + o->GetEventType() != TableState::cols_delta) return; + + // update + co_val_dict.clear(); + var_selections.Clear(); + clear_colo_control(); + + InitVariableCombobox(combo_var, true); + wxCommandEvent ev; + OnVarSelect(ev); +} + +wxString ColocationSelectDlg::get_a_label(wxString label) +{ + long idx; + if (label.ToLong(&idx) && idx >=0 && idx < m_predef_labels.size()) { + return m_predef_labels[idx]; + } + return label; +} +wxColour ColocationSelectDlg::get_a_color(wxString label) +{ + long idx; + if (label.ToLong(&idx) && idx >=0 && idx < m_predef_colors.size()) { + return m_predef_colors[idx]; + } + return wxColour(240, 240, 240); // not significant color +} + +void ColocationSelectDlg::CreateControls() +{ + wxScrolledWindow* all_scrl = new wxScrolledWindow(this, wxID_ANY, wxDefaultPosition, wxSize(470,700), wxHSCROLL|wxVSCROLL ); + all_scrl->SetScrollRate( 5, 5 ); + + panel = new wxPanel(all_scrl); + wxBoxSizer *vbox = new wxBoxSizer(wxVERTICAL); + + // Input + AddSimpleInputCtrls(panel, vbox, true); + + // Parameters + wxBoxSizer *vvbox = new wxBoxSizer(wxVERTICAL); + scrl = new wxScrolledWindow(panel, wxID_ANY, wxDefaultPosition, wxSize(260,200), wxHSCROLL|wxVSCROLL ); + scrl->SetBackgroundColour(*wxWHITE); + scrl->SetScrollRate( 5, 5 ); + vvbox->Add(scrl, 1, wxEXPAND); + + gbox = new wxFlexGridSizer(0,2,5,5); + wxBoxSizer *scrl_box = new wxBoxSizer(wxVERTICAL); + scrl_box->Add(gbox, 1, wxEXPAND); + scrl->SetSizer(scrl_box); + + const wxString _schemes[18] = { + "Unique Values", + "LISA Map", + "Local G Map", + "Loal Join Count", + "Local Geary Map", + "Multi-Local Geary", + "Quantile/Natural Breaks Map (2)", + "Quantile/Natural Breaks Map (3)", + "Quantile/Natural Breaks Map (4)", + "Quantile/Natural Breaks Map (5)", + "Quantile/Natural Breaks Map (6)", + "Quantile/Natural Breaks Map (7)", + "Quantile/Natural Breaks Map (8)", + "Quantile/Natural Breaks Map (9)", + "Quantile/Natural Breaks Map (10)", + "Percentile Map", + "Box Map", + "Std-dev Map" + }; + wxStaticText* clrscheme_txt = new wxStaticText(panel, wxID_ANY, _("Select color scheme:")); + clrscheme_choice = new wxChoice(panel, wxID_ANY, wxDefaultPosition, wxDefaultSize, 18, _schemes); + clrscheme_choice->SetSelection(0); + wxBoxSizer *clrscheme_box = new wxBoxSizer(wxHORIZONTAL); + clrscheme_box->Add(clrscheme_txt,0,wxALL, 5); + clrscheme_box->Add(clrscheme_choice, 1, wxEXPAND|wxALL, 5); + vvbox->Add(clrscheme_box, 0, wxALL, 5); + + wxStaticBoxSizer *hbox = new wxStaticBoxSizer(wxHORIZONTAL, panel, _("Setup co-locations:")); + hbox->Add(vvbox, 1, wxEXPAND); + + // Buttons + wxButton *okButton = new wxButton(panel, wxID_OK, _("OK"), wxDefaultPosition, wxSize(70, 30)); + wxButton *closeButton = new wxButton(panel, wxID_EXIT, _("Close"), wxDefaultPosition, wxSize(70, 30)); + wxBoxSizer *hbox2 = new wxBoxSizer(wxHORIZONTAL); + hbox2->Add(okButton, 1, wxALIGN_CENTER | wxALL, 5); + hbox2->Add(closeButton, 1, wxALIGN_CENTER | wxALL, 5); + + // Container + vbox->Add(hbox, 0, wxALIGN_CENTER | wxALL, 10); + //vbox->Add(hbox1, 0, wxEXPAND | wxTOP | wxLEFT | wxRIGHT, 10); + vbox->Add(hbox2, 0, wxALIGN_CENTER | wxALL, 10); + + container = new wxBoxSizer(wxHORIZONTAL); + container->Add(vbox); + + panel->SetAutoLayout(true); + panel->SetSizer(container); + + wxBoxSizer* panelSizer = new wxBoxSizer(wxVERTICAL); + panelSizer->Add(panel, 1, wxEXPAND|wxALL, 0); + + all_scrl->SetSizer(panelSizer); + + wxBoxSizer* sizerAll = new wxBoxSizer(wxVERTICAL); + sizerAll->Add(all_scrl, 1, wxEXPAND|wxALL, 0); + SetSizer(sizerAll); + SetAutoLayout(true); + sizerAll->Fit(this); + + Centre(); + + // Events + scrl->Bind(wxEVT_RIGHT_UP, &ColocationSelectDlg::OnRightUp, this); + clrscheme_choice->Bind(wxEVT_CHOICE, &ColocationSelectDlg::OnSchemeSelect, this); + combo_var->Bind(wxEVT_LISTBOX, &ColocationSelectDlg::OnVarSelect, this); + okButton->Bind(wxEVT_BUTTON, &ColocationSelectDlg::OnOK, this); + closeButton->Bind(wxEVT_BUTTON, &ColocationSelectDlg::OnClickClose, this); +} + +void ColocationSelectDlg::OnRightUp( wxMouseEvent& event) +{ + wxMenu mnu; + mnu.Append(XRCID("CO_SEL_ALL"), "Select All"); + mnu.Append(XRCID("CO_UNSEL_ALL"), "Unselect All"); + mnu.Connect(wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(ColocationSelectDlg::OnPopupClick), NULL, this); + PopupMenu(&mnu); +} + +void ColocationSelectDlg::OnPopupClick( wxCommandEvent& event) +{ + if (event.GetId() == XRCID("CO_SEL_ALL")) { + for (int i=0; iSetValue(true); + } + } + } else if (event.GetId() == XRCID("CO_UNSEL_ALL")) { + for (int i=0; iSetValue(false); + } + } + } +} + +void ColocationSelectDlg::OnSchemeSelect( wxCommandEvent& event) +{ + int idx= clrscheme_choice->GetSelection(); + if (idx < 0) return; + + if (idx == 0) { + GdaColorUtils::GetUnique20Colors(m_predef_colors); + } else if (idx == 1) { + GdaColorUtils::GetLISAColors(m_predef_colors); + GdaColorUtils::GetLISAColorLabels(m_predef_labels); + } else if (idx == 2) { + GdaColorUtils::GetLocalGColors(m_predef_colors); + GdaColorUtils::GetLocalGColorLabels(m_predef_labels); + } else if (idx == 3) { + GdaColorUtils::GetLocalJoinCountColors(m_predef_colors); + GdaColorUtils::GetLocalJoinCountColorLabels(m_predef_labels); + } else if (idx == 4) { + GdaColorUtils::GetLocalGearyColors(m_predef_colors); + GdaColorUtils::GetLocalGearyColorLabels(m_predef_labels); + } else if (idx == 5) { + GdaColorUtils::GetMultiLocalGearyColors(m_predef_colors); + GdaColorUtils::GetMultiLocalGearyColorLabels(m_predef_labels); + } else if (idx == 6) { + GdaColorUtils::GetQuantile2Colors(m_predef_colors); + } else if (idx == 7) { + GdaColorUtils::GetQuantile3Colors(m_predef_colors); + } else if (idx == 8) { + GdaColorUtils::GetQuantile4Colors(m_predef_colors); + } else if (idx == 9) { + GdaColorUtils::GetQuantile5Colors(m_predef_colors); + } else if (idx == 10) { + GdaColorUtils::GetQuantile6Colors(m_predef_colors); + } else if (idx == 11) { + GdaColorUtils::GetQuantile7Colors(m_predef_colors); + } else if (idx == 12) { + GdaColorUtils::GetQuantile8Colors(m_predef_colors); + } else if (idx == 13) { + GdaColorUtils::GetQuantile9Colors(m_predef_colors); + } else if (idx == 14) { + GdaColorUtils::GetQuantile10Colors(m_predef_colors); + } else if (idx == 15) { + GdaColorUtils::GetPercentileColors(m_predef_colors); + } else if (idx == 16) { + GdaColorUtils::GetBoxmapColors(m_predef_colors); + } else if (idx == 17) { + GdaColorUtils::GetStddevColors(m_predef_colors); + } + + m_colors.clear(); + for (int i=0; iGetLabel(); + wxColour sel_clr = get_a_color(sel_val); + m_colors.push_back(sel_clr); + co_bitmaps[i]->SetBackgroundColour(sel_clr); + co_bitmaps[i]->Refresh(); + } + } +} + +void ColocationSelectDlg::OnVarSelect( wxCommandEvent& event) +{ + co_val_dict.clear(); + var_selections.Clear(); + select_vars.clear(); + + clear_colo_control(); + + vector tms; + + combo_var->GetSelections(var_selections); + int num_var = var_selections.size(); + if (num_var >= 2) { + // check selected variables for any co-located values, and add them to choice box + col_ids.resize(num_var); + std::vector col_names; + col_names.resize(num_var); + for (int i=0; iGetString(idx); + select_vars.push_back(sel_str); + + wxString nm = name_to_nm[sel_str]; + col_names.push_back(nm); + + int tm = name_to_tm_id[combo_var->GetString(idx)]; + tms.push_back(tm); + + int col = table_int->FindColId(nm); + if (col == wxNOT_FOUND) { + wxString err_msg = wxString::Format(_("Variable %s is no longer in the Table. Please close and reopen this dialog to synchronize with Table data."), nm); + wxMessageDialog dlg(NULL, err_msg, _("Error"), wxOK | wxICON_ERROR); + dlg.ShowModal(); + return; + } + col_ids[i] = col; + } + rows = project->GetNumRecords(); + columns = 0; + + std::vector data; + std::vector data_undef; + data.resize(col_ids.size()); // data[variable][time][obs] + data_undef.resize(col_ids.size()); // data_undef[variable][time][obs] + for (int i=0; iGetColData(col_ids[i], data[i]); + table_int->GetColUndefined(col_ids[i], data_undef[i]); + } + + vector > same_val_counts(rows); + vector same_undef(rows, false); + for (int i=0; iDestroy(); + co_boxes[i]->Destroy(); + + co_bitmaps[i] = NULL; + co_boxes[i] = NULL; + } + co_boxes.clear(); + co_bitmaps.clear(); + m_colors.clear(); + gbox->SetRows(0); +} + +void ColocationSelectDlg::add_colo_control(bool is_new) +{ + clear_colo_control(); + + // re-fill gbox + int n_rows = co_val_dict.size(); + gbox->SetRows(n_rows); + int cnt = 0; + std::map >::iterator co_it; + for (co_it = co_val_dict.begin(); co_it!=co_val_dict.end(); co_it++) { + wxString tmp; + tmp << co_it->first; + wxCheckBox* chk = new wxCheckBox(scrl, base_choice_id+cnt, tmp); + chk->SetValue(true); + + wxBitmap clr; + wxColour sel_clr = get_a_color(tmp); + wxStaticBitmap* color_btn = new wxStaticBitmap(scrl, base_color_id+cnt, clr, wxDefaultPosition, wxSize(16,16)); + color_btn->SetBackgroundColour(sel_clr); + + color_btn->Bind(wxEVT_LEFT_UP, &ColocationSelectDlg::OnClickColor, this); + + co_boxes.push_back(chk); + co_bitmaps.push_back(color_btn); + m_colors.push_back(sel_clr); + + gbox->Add(chk, 1, wxEXPAND); + gbox->Add(color_btn, 0, wxALIGN_CENTER | wxRIGHT, 5); + cnt ++; + } + + container->Layout(); +} + +wxString ColocationSelectDlg::_printConfiguration() +{ + return ""; +} + +void ColocationSelectDlg::OnClickColor( wxMouseEvent& event) +{ + int obj_id = -1; + wxStaticBitmap* obj = (wxStaticBitmap*) event.GetEventObject(); + for (int i=0, iend=co_bitmaps.size(); iSetBackgroundColour(sel_clr); + co_bitmaps[obj_id]->Refresh(); + m_colors[obj_id] = sel_clr; +} + + +void ColocationSelectDlg::OnOK( wxCommandEvent& event) +{ + if (check_colocations()==false) + return; + + int n_co = co_boxes.size(); + + vector sel_vals; + vector sel_clrs; + vector sel_lbls; + vector > sel_ids; + + for (int i=0; iIsChecked()) { + wxString sel_val = co_boxes[i]->GetLabel(); + wxColour sel_clr = m_colors[i]; + wxString sel_lbl = get_a_label(sel_val); + + long l_sel_val; + if (sel_val.ToLong(&l_sel_val)) { + sel_ids.push_back( co_val_dict[l_sel_val] ); + sel_vals.push_back(sel_val); + sel_clrs.push_back(sel_clr); + sel_lbls.push_back(sel_lbl); + } + } + } + } + + if (sel_vals.empty()) { + wxString err_msg = _("Please setup co-locations first."); + wxMessageDialog dlg(NULL, err_msg, _("Error"), wxOK | wxICON_ERROR); + dlg.ShowModal(); + return; + } + + boost::uuids::uuid w_id = boost::uuids::nil_uuid(); + if (project) { + WeightsManInterface* w_int = project->GetWManInt(); + if (w_int) { + w_id = w_int->GetDefault(); + } + } + + wxString ttl = _("Co-location Map"); + ttl << ": "; + for (int i=0; i& _select_vars,vector& _co_vals, vector& _co_clrs, vector& _co_lbls, vector >& _co_ids, CatClassification::CatClassifType theme_type_s, boost::uuids::uuid weights_id_s, const wxPoint& pos, const wxSize& size) +:MapCanvas(parent, t_frame, project, vector(0), vector(0), CatClassification::no_theme, no_smoothing, 1, weights_id_s, pos, size), +select_vars(_select_vars), co_vals(_co_vals), co_clrs(_co_clrs), co_ids(_co_ids), co_lbls(_co_lbls) +{ + wxLogMessage("Entering ColocationMapCanvas::ColocationMapCanvas"); + + cat_classif_def.cat_classif_type = theme_type_s; + + CreateAndUpdateCategories(); + UpdateStatusBar(); + + wxLogMessage("Exiting ColocationMapCanvas::ColocationMapCanvas"); +} + +ColocationMapCanvas::~ColocationMapCanvas() +{ + wxLogMessage("In ColocationMapCanvas::~ColocationMapCanvas"); +} + +void ColocationMapCanvas::DisplayRightClickMenu(const wxPoint& pos) +{ + wxLogMessage("Entering ColocationMapCanvas::DisplayRightClickMenu"); + // Workaround for right-click not changing window focus in OSX / wxW 3.0 + wxActivateEvent ae(wxEVT_NULL, true, 0, wxActivateEvent::Reason_Mouse); + ((ColocationMapFrame*) template_frame)->OnActivate(ae); + + wxMenu* optMenu = wxXmlResource::Get()-> + LoadMenu("ID_COLOCATION_VIEW_MENU_OPTIONS"); + AddTimeVariantOptionsToMenu(optMenu); + SetCheckMarks(optMenu); + + template_frame->UpdateContextMenuItems(optMenu); + template_frame->PopupMenu(optMenu, pos + GetPosition()); + template_frame->UpdateOptionMenuItems(); + wxLogMessage("Exiting ColocationMapCanvas::DisplayRightClickMenu"); +} + +wxString ColocationMapCanvas::GetCanvasTitle() +{ + wxString ttl; + ttl = _("Co-location Map: "); + for (int i=0; i sig_dict; + for (int i=0; iGetStatusBar(); + } + if (!sb) + return; + wxString s; + s << _("#obs=") << project->GetNumRecords() <<" "; + + if ( highlight_state->GetTotalHighlighted() > 0) { + // for highlight from other windows + s << _("#selected=") << highlight_state->GetTotalHighlighted()<< " "; + } + if (mousemode == select && selectstate == start) { + if (total_hover_obs >= 1) { + s << _("#hover obs ") << hover_obs[0]+1; + } + if (total_hover_obs >= 2) { + s << ", "; + s << _("obs ") << hover_obs[1]+1; + } + if (total_hover_obs >= 3) { + s << ", "; + s << _("obs ") << hover_obs[2]+1; + } + if (total_hover_obs >= 4) { + s << ", ..."; + } + } + sb->SetStatusText(s); +} + +///////////////////////////////////////////////////////////////////////////////////////////// +// +// +// +///////////////////////////////////////////////////////////////////////////////////////////// +IMPLEMENT_CLASS(ColocationMapFrame, MapFrame) + BEGIN_EVENT_TABLE(ColocationMapFrame, MapFrame) + EVT_ACTIVATE(ColocationMapFrame::OnActivate) +END_EVENT_TABLE() + +ColocationMapFrame::ColocationMapFrame(wxFrame *parent, Project* project, vector& select_vars, vector& co_vals, vector& co_clrs, vector& co_lbls, vector >& co_ids, boost::uuids::uuid weights_id_s, const wxString title, const wxPoint& pos, const wxSize& size, const long style) +: MapFrame(parent, project, pos, size, style) +{ + wxLogMessage("Entering ColocationMapFrame::ColocationMapFrame"); + + int width, height; + GetClientSize(&width, &height); + + wxSplitterWindow* splitter_win = new wxSplitterWindow(this,-1, wxDefaultPosition, wxDefaultSize, wxSP_3D|wxSP_LIVE_UPDATE|wxCLIP_CHILDREN); + splitter_win->SetMinimumPaneSize(10); + + CatClassification::CatClassifType theme_type_s = CatClassification::colocation; + + wxPanel* rpanel = new wxPanel(splitter_win); + template_canvas = new ColocationMapCanvas(rpanel, this, project, select_vars, co_vals, co_clrs, co_lbls, co_ids, theme_type_s, weights_id_s); + template_canvas->SetScrollRate(1,1); + wxBoxSizer* rbox = new wxBoxSizer(wxVERTICAL); + rbox->Add(template_canvas, 1, wxEXPAND); + rpanel->SetSizer(rbox); + + wxPanel* lpanel = new wxPanel(splitter_win); + template_legend = new MapNewLegend(lpanel, template_canvas, + wxPoint(0,0), wxSize(0,0)); + wxBoxSizer* lbox = new wxBoxSizer(wxVERTICAL); + template_legend->GetContainingSizer()->Detach(template_legend); + lbox->Add(template_legend, 1, wxEXPAND); + lpanel->SetSizer(lbox); + + splitter_win->SplitVertically(lpanel, rpanel, GdaConst::map_default_legend_width); + + wxPanel* toolbar_panel = new wxPanel(this,-1, wxDefaultPosition); + wxBoxSizer* toolbar_sizer= new wxBoxSizer(wxVERTICAL); + toolbar = wxXmlResource::Get()->LoadToolBar(toolbar_panel, "ToolBar_MAP"); + SetupToolbar(); + toolbar_sizer->Add(toolbar, 0, wxEXPAND|wxALL); + toolbar_panel->SetSizerAndFit(toolbar_sizer); + + wxBoxSizer* sizer = new wxBoxSizer(wxVERTICAL); + sizer->Add(toolbar_panel, 0, wxEXPAND|wxALL); + sizer->Add(splitter_win, 1, wxEXPAND|wxALL); + SetSizer(sizer); + //splitter_win->SetSize(wxSize(width,height)); + + SetAutoLayout(true); + SetTitle(title); + DisplayStatusBar(true); + + Show(true); + wxLogMessage("Exiting ColocationMapFrame::ColocationMapFrame"); +} + +ColocationMapFrame::~ColocationMapFrame() +{ + wxLogMessage("In ColocationMapFrame::~ColocationMapFrame"); +} + +void ColocationMapFrame::OnActivate(wxActivateEvent& event) +{ + wxLogMessage("In ColocationMapFrame::OnActivate"); + if (event.GetActive()) { + RegisterAsActive("ColocationMapFrame", GetTitle()); + } + if ( event.GetActive() && template_canvas ) template_canvas->SetFocus(); +} + +void ColocationMapFrame::MapMenus() +{ + wxLogMessage("In ColocationMapFrame::MapMenus"); + wxMenuBar* mb = GdaFrame::GetGdaFrame()->GetMenuBar(); + // Map Options Menus + wxMenu* optMenu = wxXmlResource::Get()->LoadMenu("ID_COLOCATION_VIEW_MENU_OPTIONS"); + ((MapCanvas*) template_canvas)->AddTimeVariantOptionsToMenu(optMenu); + ((MapCanvas*) template_canvas)->SetCheckMarks(optMenu); + GeneralWxUtils::ReplaceMenu(mb, _("Options"), optMenu); + UpdateOptionMenuItems(); +} + +void ColocationMapFrame::UpdateOptionMenuItems() +{ + TemplateFrame::UpdateOptionMenuItems(); // set common items first + wxMenuBar* mb = GdaFrame::GetGdaFrame()->GetMenuBar(); + int menu = mb->FindMenu(_("Options")); + if (menu == wxNOT_FOUND) { + wxLogMessage("ColocationMapFrame::UpdateOptionMenuItems: " + "Options menu not found"); + } else { + ((ColocationMapCanvas*) template_canvas)->SetCheckMarks(mb->GetMenu(menu)); + } +} + +void ColocationMapFrame::UpdateContextMenuItems(wxMenu* menu) +{ + TemplateFrame::UpdateContextMenuItems(menu); // set common items +} + +void ColocationMapFrame::OnSave(wxCommandEvent& event) +{ + int t = this->GetCurrentCanvasTimeStep(); + ColocationMapCanvas* lc = (ColocationMapCanvas*)template_canvas; + int num_obs = lc->num_obs; + + std::vector data(1); + std::vector undefs(num_obs, true); + std::vector dt(num_obs); + + for (int i=0; ico_vals.size(); i++) { + wxString tmp = lc->co_vals[i]; + long l_tmp; + if (tmp.ToLong(&l_tmp)) { + for (int j=0; jco_ids[i].size(); j++) { + undefs[ lc->co_ids[i][j] ] = false; + dt[ lc->co_ids[i][j] ] = l_tmp; + } + } + } + + data[0].l_val = &dt; + data[0].label = "Coloc Indices"; + data[0].field_default = "CO_I"; + data[0].type = GdaConst::long64_type; + data[0].undefined = &undefs; + + SaveToTableDlg dlg(project, this, data, + "Save Results: Co-locations", + wxDefaultPosition, wxSize(400,400)); + dlg.ShowModal(); +} + +void ColocationMapFrame::OnShowAsConditionalMap(wxCommandEvent& event) +{ + VariableSettingsDlg dlg(project, VariableSettingsDlg::bivariate, + false, false, + _("Conditional Co-location Map Variables"), + _("Horizontal Cells"), _("Vertical Cells"), + "", "", false, false, false, // default + true, true, false, false); + + if (dlg.ShowModal() != wxID_OK) { + return; + } + + ColocationMapCanvas* lc = (ColocationMapCanvas*) template_canvas; + wxString title = lc->GetCanvasTitle(); + //ConditionalClusterMapFrame* subframe = new ConditionalClusterMapFrame(this, project, dlg.var_info, dlg.col_ids, lisa_coord, title, wxDefaultPosition, GdaConst::cond_view_default_size); +} + +void ColocationMapFrame::closeObserver(LisaCoordinator* o) +{ + wxLogMessage("In ColocationMapFrame::closeObserver(LisaCoordinator*)"); + Close(true); +} diff --git a/Explore/ColocationMapView.h b/Explore/ColocationMapView.h new file mode 100644 index 000000000..552f172ed --- /dev/null +++ b/Explore/ColocationMapView.h @@ -0,0 +1,155 @@ +/** + * GeoDa TM, Copyright (C) 2011-2015 by Luc Anselin - all rights reserved + * + * This file is part of GeoDa. + * + * GeoDa is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * GeoDa is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#ifndef __GEODA_CENTER_COLOCATION_MAP_VIEW_H__ +#define __GEODA_CENTER_COLOCATION_MAP_VIEW_H__ + +#include +#include "MapNewView.h" +#include "../GdaConst.h" + +using namespace std; + +class ColocationSelectDlg : public AbstractClusterDlg +{ +public: + ColocationSelectDlg(wxFrame *parent, Project* project); + virtual ~ColocationSelectDlg(); + + void CreateControls(); + + virtual void update(TableState* o); + + void OnVarSelect( wxCommandEvent& event ); + void OnOK( wxCommandEvent& event ); + void OnClickClose( wxCommandEvent& event ); + void OnClose(wxCloseEvent& ev); + void OnClickColor(wxMouseEvent& ev); + void OnRightUp(wxMouseEvent& ev); + void OnPopupClick( wxCommandEvent& event ); + void OnSchemeSelect( wxCommandEvent& event ); + + virtual wxString _printConfiguration(); + void clear_colo_control(); + void add_colo_control(bool is_new=false); + wxColour get_a_color(wxString label); + wxString get_a_label(wxString label); + bool check_colocations(); + + void update_grid(); + +protected: + wxPanel *panel; + wxFlexGridSizer *gbox; + wxBoxSizer *container; + wxScrolledWindow* scrl; + wxChoice* clrscheme_choice; + + std::vector co_bitmaps; + std::vector co_boxes; + + wxArrayInt var_selections; + std::vector co_values; + + int base_remove_id; + int base_color_id; + int base_choice_id; + + std::vector m_colors; + std::vector m_labels; + std::vector m_predef_colors; + std::vector m_predef_labels; + + std::map > co_val_dict; + + DECLARE_EVENT_TABLE() +}; + +class ColocationMapCanvas : public MapCanvas +{ + DECLARE_CLASS(ColocationMapCanvas) +public: + ColocationMapCanvas(wxWindow *parent, + TemplateFrame* t_frame, + Project* project, + vector& select_vars, + vector& co_vals, + vector& co_clrs, + vector& co_lbls, + vector >& co_ids, + CatClassification::CatClassifType theme_type, + boost::uuids::uuid weights_id_s, + const wxPoint& pos = wxDefaultPosition, + const wxSize& size = wxDefaultSize); + virtual ~ColocationMapCanvas(); + + virtual void DisplayRightClickMenu(const wxPoint& pos); + virtual wxString GetCanvasTitle(); + virtual wxString GetVariableNames(); + virtual bool ChangeMapType(CatClassification::CatClassifType new_map_theme, + SmoothingType new_map_smoothing); + virtual void SetCheckMarks(wxMenu* menu); + virtual void TimeChange(); + virtual void CreateAndUpdateCategories(); + virtual void TimeSyncVariableToggle(int var_index); + virtual void UpdateStatusBar(); + + vector& select_vars; + vector co_vals; + vector co_clrs; + vector co_lbls; + vector > co_ids; + + DECLARE_EVENT_TABLE() +}; + + +class ColocationMapFrame : public MapFrame +{ + DECLARE_CLASS(ColocationMapFrame) +public: + ColocationMapFrame(wxFrame *parent, + Project* project, + vector& select_vars, + vector& co_vals, + vector& co_clrs, + vector& co_lbls, + vector >& co_ids, + boost::uuids::uuid weights_id_s, + const wxString title, + const wxPoint& pos = wxDefaultPosition, + const wxSize& size = GdaConst::map_default_size, + const long style = wxDEFAULT_FRAME_STYLE); + virtual ~ColocationMapFrame(); + + void OnActivate(wxActivateEvent& event); + virtual void MapMenus(); + virtual void UpdateOptionMenuItems(); + virtual void UpdateContextMenuItems(wxMenu* menu); + + void OnSave(wxCommandEvent& event); + + void OnShowAsConditionalMap(wxCommandEvent& event); + + virtual void closeObserver(LisaCoordinator* o); + + DECLARE_EVENT_TABLE() +}; + +#endif diff --git a/Explore/ConditionalClusterMapView.cpp b/Explore/ConditionalClusterMapView.cpp index df848ce7b..a309c834f 100644 --- a/Explore/ConditionalClusterMapView.cpp +++ b/Explore/ConditionalClusterMapView.cpp @@ -36,13 +36,13 @@ #include "../GeneralWxUtils.h" #include "../GeoDa.h" #include "../Project.h" -#include "../ShapeOperations/ShapeUtils.h" #include "CatClassifState.h" #include "CatClassifManager.h" #include "LisaCoordinator.h" #include "GStatCoordinator.h" #include "LocalGearyCoordinator.h" +#include "MLJCCoordinator.h" #include "ConditionalClusterMapView.h" using namespace std; @@ -151,13 +151,20 @@ wxString ConditionalClusterMapCanvas::GetCategoriesTitle() wxString ConditionalClusterMapCanvas::GetCanvasTitle() { wxString v; - v << "Conditional Map - "; + v << _("Conditional Map") << " - "; v << "x: " << GetNameWithTime(HOR_VAR); v << ", y: " << GetNameWithTime(VERT_VAR); v << ", " << title; return v; } +wxString ConditionalClusterMapCanvas::GetVariableNames() +{ + wxString v; + v << GetNameWithTime(HOR_VAR); + v << ", " << GetNameWithTime(VERT_VAR); + return v; +} void ConditionalClusterMapCanvas::SetCheckMarks(wxMenu* menu) { @@ -170,38 +177,24 @@ void ConditionalClusterMapCanvas::SetCheckMarks(wxMenu* menu) GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_MAPANALYSIS_THEMELESS"), GetCatType() == CatClassification::no_theme); - // since XRCID is a macro, we can't make this into a loop - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_QUANTILE_1"), - (GetCatType() == CatClassification::quantile) - && GetNumCats() == 1); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_QUANTILE_2"), - (GetCatType() == CatClassification::quantile) - && GetNumCats() == 2); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_QUANTILE_3"), - (GetCatType() == CatClassification::quantile) - && GetNumCats() == 3); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_QUANTILE_4"), - (GetCatType() == CatClassification::quantile) - && GetNumCats() == 4); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_QUANTILE_5"), - (GetCatType() == CatClassification::quantile) - && GetNumCats() == 5); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_QUANTILE_6"), - (GetCatType() == CatClassification::quantile) - && GetNumCats() == 6); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_QUANTILE_7"), - (GetCatType() == CatClassification::quantile) - && GetNumCats() == 7); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_QUANTILE_8"), - (GetCatType() == CatClassification::quantile) - && GetNumCats() == 8); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_QUANTILE_9"), - (GetCatType() == CatClassification::quantile) - && GetNumCats() == 9); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_QUANTILE_10"), - (GetCatType() == CatClassification::quantile) - && GetNumCats() == 10); - + + for (int i=1; i<=10; i++) { + wxString str_xrcid; + bool flag; + + str_xrcid = wxString::Format("ID_QUANTILE_%d", i); + flag = GetCatType()==CatClassification::quantile && GetNumCats()==i; + GeneralWxUtils::CheckMenuItem(menu, XRCID(str_xrcid), flag); + + str_xrcid = wxString::Format("ID_EQUAL_INTERVALS_%d", i); + flag = GetCatType()==CatClassification::equal_intervals && GetNumCats()==i; + GeneralWxUtils::CheckMenuItem(menu, XRCID(str_xrcid), flag); + + str_xrcid = wxString::Format("ID_NATURAL_BREAKS_%d", i); + flag = GetCatType()==CatClassification::natural_breaks && GetNumCats()==i; + GeneralWxUtils::CheckMenuItem(menu, XRCID(str_xrcid), flag); + } + GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_MAPANALYSIS_CHOROPLETH_PERCENTILE"), GetCatType() == CatClassification::percentile); @@ -214,91 +207,6 @@ void ConditionalClusterMapCanvas::SetCheckMarks(wxMenu* menu) GetCatType() == CatClassification::stddev); GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_MAPANALYSIS_UNIQUE_VALUES"), GetCatType() == CatClassification::unique_values); - - // since XRCID is a macro, we can't make this into a loop - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_EQUAL_INTERVALS_1"), - (GetCatType() == - CatClassification::equal_intervals) - && GetNumCats() == 1); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_EQUAL_INTERVALS_2"), - (GetCatType() == - CatClassification::equal_intervals) - && GetNumCats() == 2); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_EQUAL_INTERVALS_3"), - (GetCatType() == - CatClassification::equal_intervals) - && GetNumCats() == 3); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_EQUAL_INTERVALS_4"), - (GetCatType() == - CatClassification::equal_intervals) - && GetNumCats() == 4); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_EQUAL_INTERVALS_5"), - (GetCatType() == - CatClassification::equal_intervals) - && GetNumCats() == 5); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_EQUAL_INTERVALS_6"), - (GetCatType() == - CatClassification::equal_intervals) - && GetNumCats() == 6); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_EQUAL_INTERVALS_7"), - (GetCatType() == - CatClassification::equal_intervals) - && GetNumCats() == 7); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_EQUAL_INTERVALS_8"), - (GetCatType() == - CatClassification::equal_intervals) - && GetNumCats() == 8); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_EQUAL_INTERVALS_9"), - (GetCatType() == - CatClassification::equal_intervals) - && GetNumCats() == 9); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_EQUAL_INTERVALS_10"), - (GetCatType() == - CatClassification::equal_intervals) - && GetNumCats() == 10); - - // since XRCID is a macro, we can't make this into a loop - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_NATURAL_BREAKS_1"), - (GetCatType() == - CatClassification::natural_breaks) - && GetNumCats() == 1); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_NATURAL_BREAKS_2"), - (GetCatType() == - CatClassification::natural_breaks) - && GetNumCats() == 2); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_NATURAL_BREAKS_3"), - (GetCatType() == - CatClassification::natural_breaks) - && GetNumCats() == 3); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_NATURAL_BREAKS_4"), - (GetCatType() == - CatClassification::natural_breaks) - && GetNumCats() == 4); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_NATURAL_BREAKS_5"), - (GetCatType() == - CatClassification::natural_breaks) - && GetNumCats() == 5); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_NATURAL_BREAKS_6"), - (GetCatType() == - CatClassification::natural_breaks) - && GetNumCats() == 6); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_NATURAL_BREAKS_7"), - (GetCatType() == - CatClassification::natural_breaks) - && GetNumCats() == 7); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_NATURAL_BREAKS_8"), - (GetCatType() == - CatClassification::natural_breaks) - && GetNumCats() == 8); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_NATURAL_BREAKS_9"), - (GetCatType() == - CatClassification::natural_breaks) - && GetNumCats() == 9); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_NATURAL_BREAKS_10"), - (GetCatType() == - CatClassification::natural_breaks) - && GetNumCats() == 10); - } void ConditionalClusterMapCanvas::OnSaveCategories() @@ -354,7 +262,7 @@ ChangeCatThemeType(CatClassification::CatClassifType new_cat_theme, if (all_init && template_frame) { template_frame->UpdateTitle(); if (template_frame->GetTemplateLegend()) { - template_frame->GetTemplateLegend()->Refresh(); + template_frame->GetTemplateLegend()->Recreate(); } } } @@ -369,7 +277,7 @@ void ConditionalClusterMapCanvas::update(CatClassifState* o) if (template_frame) { template_frame->UpdateTitle(); if (template_frame->GetTemplateLegend()) { - template_frame->GetTemplateLegend()->Refresh(); + template_frame->GetTemplateLegend()->Recreate(); } } } else { @@ -414,7 +322,7 @@ void ConditionalClusterMapCanvas::ResizeSelectableShps(int virtual_scrn_w, if (pad_h < 1) pad_h = 1; - double pad = GenUtils::min(pad_w, pad_h); + double pad = std::min(pad_w, pad_h); double marg_top = last_scale_trans.top_margin; double marg_bottom = last_scale_trans.bottom_margin; @@ -518,37 +426,47 @@ void ConditionalClusterMapCanvas::ResizeSelectableShps(int virtual_scrn_w, double bg_xmax = scn_w-marg_right; double bg_ymin = marg_bottom; double bg_ymax = scn_h-marg_top; - - vector v_brk_ref(vert_num_cats-1); - vector h_brk_ref(horiz_num_cats-1); - - for (int row=0; row v_brk_ref(n_rows); + vector h_brk_ref(n_cols); + + for (int row=0; row& var_info, + const vector& col_ids, + JCCoordinator* local_jc_coord, + const wxString& title, const wxPoint& pos, + const wxSize& size, const long style) +: ConditionalNewFrame(parent, project, var_info, col_ids, title, pos,size, style) +{ + + wxLogMessage("Open ConditionalNewFrame -- Local Join Count."); + int width, height; + GetClientSize(&width, &height); + + + wxSplitterWindow* splitter_win = new wxSplitterWindow(this,-1, + wxDefaultPosition, wxDefaultSize, + wxSP_3D|wxSP_LIVE_UPDATE|wxCLIP_CHILDREN); + splitter_win->SetMinimumPaneSize(10); + + wxPanel* rpanel = new wxPanel(splitter_win); + template_canvas = new ConditionalLocalJoinCountClusterMapCanvas(rpanel, this, project, + var_info, col_ids, + local_jc_coord, + title, + wxDefaultPosition, + wxDefaultSize); + SetTitle(template_canvas->GetCanvasTitle()); + template_canvas->SetScrollRate(1,1); + wxBoxSizer* rbox = new wxBoxSizer(wxVERTICAL); + rbox->Add(template_canvas, 1, wxEXPAND); + rpanel->SetSizer(rbox); + + wxPanel* lpanel = new wxPanel(splitter_win); + template_legend = new ConditionalClusterMapLegend(lpanel, template_canvas, + wxPoint(0,0), wxSize(0,0)); + wxBoxSizer* lbox = new wxBoxSizer(wxVERTICAL); + template_legend->GetContainingSizer()->Detach(template_legend); + lbox->Add(template_legend, 1, wxEXPAND); + lpanel->SetSizer(lbox); + + splitter_win->SplitVertically(lpanel, rpanel, + GdaConst::map_default_legend_width); + wxBoxSizer* sizer = new wxBoxSizer(wxVERTICAL); + sizer->Add(splitter_win, 1, wxEXPAND|wxALL); + SetSizer(sizer); + splitter_win->SetSize(wxSize(width,height)); + SetAutoLayout(true); + DisplayStatusBar(true); + Show(true); +} + ConditionalClusterMapFrame::~ConditionalClusterMapFrame() { DeregisterAsActive(); @@ -949,7 +925,7 @@ void ConditionalClusterMapFrame::MapMenus() ((ConditionalClusterMapCanvas*) template_canvas)->AddTimeVariantOptionsToMenu(optMenu); TemplateCanvas::AppendCustomCategories(optMenu, project->GetCatClassifManager()); ((ConditionalClusterMapCanvas*) template_canvas)->SetCheckMarks(optMenu); - GeneralWxUtils::ReplaceMenu(mb, "Options", optMenu); + GeneralWxUtils::ReplaceMenu(mb, _("Options"), optMenu); UpdateOptionMenuItems(); } @@ -957,7 +933,7 @@ void ConditionalClusterMapFrame::UpdateOptionMenuItems() { TemplateFrame::UpdateOptionMenuItems(); // set common items first wxMenuBar* mb = GdaFrame::GetGdaFrame()->GetMenuBar(); - int menu = mb->FindMenu("Options"); + int menu = mb->FindMenu(_("Options")); if (menu == wxNOT_FOUND) { } else { ((ConditionalClusterMapCanvas*) @@ -1105,8 +1081,9 @@ void ConditionalLISAClusterMapCanvas::CreateAndUpdateCategories() cat_var_sorted[t].resize(num_obs); cat_var_undef[t].resize(num_obs); + int* clst = lisa_coord->GetClusterIndicators(t); for (int i=0; icluster_vecs[t][i]; + cat_var_sorted[t][i].first = clst[i]; cat_var_sorted[t][i].second = i; cat_var_undef[t][i] = lisa_coord->undef_data[0][t][i]; @@ -1153,7 +1130,7 @@ void ConditionalLISAClusterMapCanvas::CreateAndUpdateCategories() Shapefile::Header& hdr = project->main_data.header; - cat_data.SetCategoryLabel(t, 0, "Not Significant"); + cat_data.SetCategoryLabel(t, 0, _("Not Significant")); if (hdr.shape_type == Shapefile::POINT_TYP) { cat_data.SetCategoryColor(t, 0, wxColour(190, 190, 190)); @@ -1187,10 +1164,10 @@ void ConditionalLISAClusterMapCanvas::CreateAndUpdateCategories() cat_data.SetCategoryColor(t, isolates_cat, wxColour(140, 140, 140)); } - double cuttoff = lisa_coord->significance_cutoff; - double* p = lisa_coord->sig_local_moran_vecs[t]; - int* cluster = lisa_coord->cluster_vecs[t]; - int* sigCat = lisa_coord->sig_cat_vecs[t]; + double cuttoff = lisa_coord->GetSignificanceCutoff(); + double* p = lisa_coord->GetLocalSignificanceValues(t); + int* cluster = lisa_coord->GetClusterIndicators(t); + //int* sigCat = lisa_coord->sig_cat_vecs[t]; for (int i=0, iend=lisa_coord->num_obs; i cuttoff && cluster[i] != 5 && cluster[i] != 6) { @@ -1237,7 +1214,7 @@ void ConditionalLISAClusterMapCanvas::UpdateStatusBar() wxString s; if (highlight_state->GetTotalHighlighted()> 0) { int n_total_hl = highlight_state->GetTotalHighlighted(); - s << "#selected=" << n_total_hl << " "; + s << _("#selected=") << n_total_hl << " "; int n_undefs = 0; for (int i=0; i 0) { - s << "(undefined:" << n_undefs << ") "; + s << _("undefined: ") << n_undefs << ") "; } } if (mousemode == select && selectstate == start) { + int* clst = lisa_coord->GetClusterIndicators(t); if (total_hover_obs >= 1) { - s << "hover obs " << hover_obs[0]+1 << " = "; - s << lisa_coord->cluster_vecs[t][hover_obs[0]]; + s << _("#hover obs ") << hover_obs[0]+1 << " = "; + s << clst[hover_obs[0]]; } if (total_hover_obs >= 2) { s << ", "; - s << "obs " << hover_obs[1]+1 << " = "; - s << lisa_coord->cluster_vecs[t][hover_obs[1]]; + s << _("obs ") << hover_obs[1]+1 << " = "; + s << clst[hover_obs[1]]; } if (total_hover_obs >= 3) { s << ", "; - s << "obs " << hover_obs[2]+1 << " = "; - s << lisa_coord->cluster_vecs[t][hover_obs[2]]; + s << _("obs ") << hover_obs[2]+1 << " = "; + s << clst[hover_obs[2]]; } if (total_hover_obs >= 4) { s << ", ..."; @@ -1371,13 +1349,13 @@ void ConditionalGClusterMapCanvas::CreateAndUpdateCategories() Shapefile::Header& hdr = project->main_data.header; - cat_data.SetCategoryLabel(t, 0, "Not Significant"); + cat_data.SetCategoryLabel(t, 0, _("Not Significant")); - cat_data.SetCategoryLabel(t, 0, "Not Significant"); + cat_data.SetCategoryLabel(t, 0, _("Not Significant")); cat_data.SetCategoryColor(t, 0, wxColour(240, 240, 240)); - cat_data.SetCategoryLabel(t, 1, "High"); + cat_data.SetCategoryLabel(t, 1, _("High")); cat_data.SetCategoryColor(t, 1, wxColour(255, 0, 0)); - cat_data.SetCategoryLabel(t, 2, "Low"); + cat_data.SetCategoryLabel(t, 2, _("Low")); cat_data.SetCategoryColor(t, 2, wxColour(0, 0, 255)); if (g_coord->GetHasIsolates(t) && @@ -1392,11 +1370,11 @@ void ConditionalGClusterMapCanvas::CreateAndUpdateCategories() } if (undefined_cat != -1) { - cat_data.SetCategoryLabel(t, undefined_cat, "Undefined"); + cat_data.SetCategoryLabel(t, undefined_cat, _("Undefined")); cat_data.SetCategoryColor(t, undefined_cat, wxColour(70, 70, 70)); } if (isolates_cat != -1) { - cat_data.SetCategoryLabel(t, isolates_cat, "Neighborless"); + cat_data.SetCategoryLabel(t, isolates_cat, _("Neighborless")); cat_data.SetCategoryColor(t, isolates_cat, wxColour(140, 140, 140)); } @@ -1449,7 +1427,7 @@ void ConditionalGClusterMapCanvas::UpdateStatusBar() wxString s; if (highlight_state->GetTotalHighlighted()> 0) { int n_total_hl = highlight_state->GetTotalHighlighted(); - s << "#selected=" << n_total_hl << " "; + s << _("#selected=") << n_total_hl << " "; int n_undefs = 0; for (int i=0; i 0) { - s << "(undefined:" << n_undefs << ") "; + s << _("undefined: ") << n_undefs << ") "; } } /* if (mousemode == select && selectstate == start) { if (total_hover_obs >= 1) { - s << "hover obs " << hover_obs[0]+1 << " = "; + s << _("#hover obs ") << hover_obs[0]+1 << " = "; s << g_coord->cluster_vecs[t][hover_obs[0]]; } if (total_hover_obs >= 2) { s << ", "; - s << "obs " << hover_obs[1]+1 << " = "; + s << _("obs ") << hover_obs[1]+1 << " = "; s << g_coord->cluster_vecs[t][hover_obs[1]]; } if (total_hover_obs >= 3) { s << ", "; - s << "obs " << hover_obs[2]+1 << " = "; + s << _("obs ") << hover_obs[2]+1 << " = "; s << g_coord->cluster_vecs[t][hover_obs[2]]; } if (total_hover_obs >= 4) { @@ -1581,20 +1559,20 @@ void ConditionalLocalGearyClusterMapCanvas::CreateAndUpdateCategories() Shapefile::Header& hdr = project->main_data.header; - cat_data.SetCategoryLabel(t, 0, "Not Significant"); + cat_data.SetCategoryLabel(t, 0, _("Not Significant")); if (hdr.shape_type == Shapefile::POINT_TYP) { cat_data.SetCategoryColor(t, 0, wxColour(190, 190, 190)); } else { cat_data.SetCategoryColor(t, 0, wxColour(240, 240, 240)); } - cat_data.SetCategoryLabel(t, 1, "High-High"); + cat_data.SetCategoryLabel(t, 1, _("High-High")); cat_data.SetCategoryColor(t, 1, wxColour(178,24,43)); - cat_data.SetCategoryLabel(t, 2, "Low-Low"); + cat_data.SetCategoryLabel(t, 2, _("Low-Low")); cat_data.SetCategoryColor(t, 2, wxColour(239,138,98)); - cat_data.SetCategoryLabel(t, 3, "Other Pos"); + cat_data.SetCategoryLabel(t, 3, _("Other Pos")); cat_data.SetCategoryColor(t, 3, wxColour(253,219,199)); - cat_data.SetCategoryLabel(t, 4, "Negative"); + cat_data.SetCategoryLabel(t, 4, _("Negative")); cat_data.SetCategoryColor(t, 4, wxColour(103,173,199)); if (local_geary_coord->GetHasIsolates(t) && local_geary_coord->GetHasUndefined(t)) { @@ -1607,11 +1585,11 @@ void ConditionalLocalGearyClusterMapCanvas::CreateAndUpdateCategories() } if (undefined_cat != -1) { - cat_data.SetCategoryLabel(t, undefined_cat, "Undefined"); + cat_data.SetCategoryLabel(t, undefined_cat, _("Undefined")); cat_data.SetCategoryColor(t, undefined_cat, wxColour(70, 70, 70)); } if (isolates_cat != -1) { - cat_data.SetCategoryLabel(t, isolates_cat, "Neighborless"); + cat_data.SetCategoryLabel(t, isolates_cat, _("Neighborless")); cat_data.SetCategoryColor(t, isolates_cat, wxColour(140, 140, 140)); } @@ -1665,7 +1643,7 @@ void ConditionalLocalGearyClusterMapCanvas::UpdateStatusBar() wxString s; if (highlight_state->GetTotalHighlighted()> 0) { int n_total_hl = highlight_state->GetTotalHighlighted(); - s << "#selected=" << n_total_hl << " "; + s << _("#selected=") << n_total_hl << " "; int n_undefs = 0; for (int i=0; i 0) { - s << "(undefined:" << n_undefs << ") "; + s << _("undefined: ") << n_undefs << ") "; } } if (mousemode == select && selectstate == start) { if (total_hover_obs >= 1) { - s << "hover obs " << hover_obs[0]+1 << " = "; + s << _("#hover obs ") << hover_obs[0]+1 << " = "; s << local_geary_coord->cluster_vecs[t][hover_obs[0]]; } if (total_hover_obs >= 2) { s << ", "; - s << "obs " << hover_obs[1]+1 << " = "; + s << _("obs ") << hover_obs[1]+1 << " = "; s << local_geary_coord->cluster_vecs[t][hover_obs[1]]; } if (total_hover_obs >= 3) { s << ", "; - s << "obs " << hover_obs[2]+1 << " = "; + s << _("obs ") << hover_obs[2]+1 << " = "; s << local_geary_coord->cluster_vecs[t][hover_obs[2]]; } if (total_hover_obs >= 4) { @@ -1698,3 +1676,219 @@ void ConditionalLocalGearyClusterMapCanvas::UpdateStatusBar() } sb->SetStatusText(s); } + +/////////////////////////////////////////////////////////////////////////////// +// +// Local Join Count Cluster +// +/////////////////////////////////////////////////////////////////////////////// +ConditionalLocalJoinCountClusterMapCanvas:: +ConditionalLocalJoinCountClusterMapCanvas(wxWindow *parent, TemplateFrame* t_frame, + Project* project, + const vector& var_info, + const vector& col_ids, + JCCoordinator* local_jc_coordinator, + const wxString& title, + const wxPoint& pos, + const wxSize& size) +: ConditionalClusterMapCanvas(parent, t_frame, project, var_info, col_ids, title, pos, size), +local_jc_coord(local_jc_coordinator) +{ + Init(size); +} + +ConditionalLocalJoinCountClusterMapCanvas::~ConditionalLocalJoinCountClusterMapCanvas() +{ + +} + +void ConditionalLocalJoinCountClusterMapCanvas::CreateAndUpdateCategories() +{ + cat_var_sorted.clear(); + map_valid.resize(num_time_vals); + for (int t=0; tlocal_jc_vecs[t][i]; + cat_var_sorted[t][i].second = i; + + cat_var_undef[t][i] = local_jc_coord->undef_tms[t][i]; + } + } + + // Sort each vector in ascending order + sort(cat_var_sorted[0].begin(), + cat_var_sorted[0].end(), Gda::dbl_int_pair_cmp_less); + + if (is_any_sync_with_global_time) { + for (int t=1; tnum_time_vals; + int num_obs = local_jc_coord->num_obs; + cat_data.CreateEmptyCategories(num_time, num_obs); + + for (int t=0; tGetHasIsolates(t)) + num_cats++; + if (local_jc_coord->GetHasUndefined(t)) + num_cats++; + + num_cats += 5; + + cat_data.CreateCategoriesAtCanvasTm(num_cats, t); + + Shapefile::Header& hdr = project->main_data.header; + + cat_data.SetCategoryLabel(t, 0, _("Not Significant")); + + if (hdr.shape_type == Shapefile::POINT_TYP) { + cat_data.SetCategoryColor(t, 0, wxColour(190, 190, 190)); + } else { + cat_data.SetCategoryColor(t, 0, wxColour(240, 240, 240)); + } + cat_data.SetCategoryLabel(t, 1, _("No Colocation")); + cat_data.SetCategoryColor(t, 1, wxColour(0, 0, 255)); + cat_data.SetCategoryLabel(t, 2, _("Has Colocation")); + cat_data.SetCategoryColor(t, 2, wxColour(0, 255, 0)); + cat_data.SetCategoryLabel(t, 3, _("Colocation Cluster")); + cat_data.SetCategoryColor(t, 3, wxColour(255,0,0)); + if (local_jc_coord->GetHasIsolates(t) && + local_jc_coord->GetHasUndefined(t)) { + isolates_cat = 4; + undefined_cat = 5; + } else if (local_jc_coord->GetHasUndefined(t)) { + undefined_cat = 4; + } else if (local_jc_coord->GetHasIsolates(t)) { + isolates_cat = 4; + } + + if (undefined_cat != -1) { + cat_data.SetCategoryLabel(t, undefined_cat, _("Undefined")); + cat_data.SetCategoryColor(t, undefined_cat, wxColour(70, 70, 70)); + } + if (isolates_cat != -1) { + cat_data.SetCategoryLabel(t, isolates_cat, _("Neighborless")); + cat_data.SetCategoryColor(t, isolates_cat, wxColour(140, 140, 140)); + } + + double cuttoff = local_jc_coord->significance_cutoff; + double* p = local_jc_coord->sig_local_jc_vecs[t]; + std::vector cluster; + local_jc_coord->FillClusterCats(t,cluster); + + for (int i=0, iend=local_jc_coord->num_obs; i cuttoff && cluster[i] != 4 && cluster[i] != 5) { + cat_data.AppendIdToCategory(t, 0, i); // not significant + } else if (cluster[i] == 4) { + cat_data.AppendIdToCategory(t, isolates_cat, i); + } else if (cluster[i] == 5) { + cat_data.AppendIdToCategory(t, undefined_cat, i); + } else { + cat_data.AppendIdToCategory(t, cluster[i], i); + } + } + for (int cat=0; catvar_info[0].sync_with_global_time = !local_jc_coord->var_info[0].sync_with_global_time; + + VarInfoAttributeChange(); + CreateAndUpdateCategories(); + PopulateCanvas(); +} + +void ConditionalLocalJoinCountClusterMapCanvas::UpdateStatusBar() +{ + wxStatusBar* sb = template_frame->GetStatusBar(); + if (!sb) return; + + //int t = var_info[CAT_VAR].time; + int t = 0; + + const vector& hl = highlight_state->GetHighlight(); + wxString s; + if (highlight_state->GetTotalHighlighted()> 0) { + int n_total_hl = highlight_state->GetTotalHighlighted(); + s << _("#selected=") << n_total_hl << " "; + + int n_undefs = 0; + for (int i=0; i 0) { + s << _("undefined: ") << n_undefs << ") "; + } + } + + if (mousemode == select && selectstate == start) { + std::vector cluster; + local_jc_coord->FillClusterCats(t,cluster); + + if (total_hover_obs >= 1) { + s << _("#hover obs ") << hover_obs[0]+1 << " = "; + s << cluster[hover_obs[0]]; + } + if (total_hover_obs >= 2) { + s << ", "; + s << _("obs ") << hover_obs[1]+1 << " = "; + s << cluster[hover_obs[1]]; + } + if (total_hover_obs >= 3) { + s << ", "; + s << _("obs ") << hover_obs[2]+1 << " = "; + s << cluster[hover_obs[2]]; + } + if (total_hover_obs >= 4) { + s << ", ..."; + } + } + sb->SetStatusText(s); +} diff --git a/Explore/ConditionalClusterMapView.h b/Explore/ConditionalClusterMapView.h index b2e99c31a..93884975d 100644 --- a/Explore/ConditionalClusterMapView.h +++ b/Explore/ConditionalClusterMapView.h @@ -29,7 +29,7 @@ using namespace std; class LisaCoordinator; class GStatCoordinator; class LocalGearyCoordinator; - +class JCCoordinator; class ConditionalClusterMapFrame; class ConditionalClusterMapCanvas; class ConditionalClusterMapLegend; @@ -54,6 +54,7 @@ class ConditionalClusterMapCanvas : public ConditionalNewCanvas { virtual wxString GetCategoriesTitle(); virtual wxString GetCanvasTitle(); + virtual wxString GetVariableNames(); void Init(const wxSize& size); virtual void DisplayRightClickMenu(const wxPoint& pos); @@ -83,10 +84,11 @@ class ConditionalClusterMapCanvas : public ConditionalNewCanvas { CatClassifDef cat_classif_def_map; CatClassification::CatClassifType GetCatType(); -protected: virtual void UpdateStatusBar() = 0; virtual void PopulateCanvas(); +protected: + wxString title; CatClassifState* cc_state_map; int num_categories; // current number of categories @@ -144,6 +146,14 @@ class ConditionalClusterMapFrame : public ConditionalNewFrame { const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, const long style = wxDEFAULT_FRAME_STYLE); + ConditionalClusterMapFrame(wxFrame *parent, Project* project, + const vector& var_info, + const vector& col_ids, + JCCoordinator* local_jc_coord, + const wxString& title = _("Conditional Local Join Count Map"), + const wxPoint& pos = wxDefaultPosition, + const wxSize& size = wxDefaultSize, + const long style = wxDEFAULT_FRAME_STYLE); virtual ~ConditionalClusterMapFrame(); void OnActivate(wxActivateEvent& event); @@ -263,4 +273,33 @@ class ConditionalLocalGearyClusterMapCanvas : public ConditionalClusterMapCanvas LocalGearyCoordinator* local_geary_coord; virtual void UpdateStatusBar(); }; + +//////////////////////////////////////////////////////////////////////////////// +// +// LocalJoinCount Cluster Conditional map +// +//////////////////////////////////////////////////////////////////////////////// +class ConditionalLocalJoinCountClusterMapCanvas : public ConditionalClusterMapCanvas { + //DECLARE_CLASS(ConditionalLocalGearyClusterMapCanvas) +public: + + ConditionalLocalJoinCountClusterMapCanvas(wxWindow *parent, TemplateFrame* t_frame, + Project* project, + const vector& var_info, + const vector& col_ids, + JCCoordinator* local_jc_coordinator, + const wxString& title, + const wxPoint& pos = wxDefaultPosition, + const wxSize& size = wxDefaultSize); + + virtual ~ConditionalLocalJoinCountClusterMapCanvas(); + + virtual void CreateAndUpdateCategories(); + virtual void TimeSyncVariableToggle(int var_index); + +protected: + JCCoordinator* local_jc_coord; + virtual void UpdateStatusBar(); +}; + #endif diff --git a/Explore/ConditionalHistogramView.cpp b/Explore/ConditionalHistogramView.cpp index ca359e438..d9060066e 100644 --- a/Explore/ConditionalHistogramView.cpp +++ b/Explore/ConditionalHistogramView.cpp @@ -36,7 +36,7 @@ #include "../FramesManager.h" #include "../GeoDa.h" #include "../Project.h" -#include "../ShapeOperations/ShapeUtils.h" + #include "ConditionalHistogramView.h" @@ -102,12 +102,12 @@ show_axes(true), scale_x_over_time(true), scale_y_over_time(true) } } - max_intervals = GenUtils::min(MAX_INTERVALS, num_obs); - cur_intervals = GenUtils::min(max_intervals, default_intervals); + max_intervals = std::min(MAX_INTERVALS, num_obs); + cur_intervals = std::min(max_intervals, default_intervals); if (num_obs > 49) { int c = sqrt((double) num_obs); - cur_intervals = GenUtils::min(max_intervals, c); - cur_intervals = GenUtils::min(cur_intervals, 7); + cur_intervals = std::min(max_intervals, c); + cur_intervals = std::min(cur_intervals, 7); } highlight_color = GdaConst::highlight_color; @@ -178,6 +178,13 @@ wxString ConditionalHistogramCanvas::GetCanvasTitle() return v; } +wxString ConditionalHistogramCanvas::GetVariableNames() +{ + wxString v; + v << GetNameWithTime(HIST_VAR); + return v; +} + void ConditionalHistogramCanvas::ResizeSelectableShps(int virtual_scrn_w, int virtual_scrn_h) { @@ -219,7 +226,7 @@ void ConditionalHistogramCanvas::ResizeSelectableShps(int virtual_scrn_w, double pad_h = scn_h * fac; if (pad_w < 1) pad_w = 0; if (pad_h < 1) pad_h = 0; - double pad_bump = GenUtils::min(pad_w, pad_h); + double pad_bump = std::min(pad_w, pad_h); double pad = min_pad + pad_bump; double marg_top = last_scale_trans.top_margin; @@ -295,20 +302,25 @@ void ConditionalHistogramCanvas::ResizeSelectableShps(int virtual_scrn_w, double bg_xmax = scn_w-marg_right; double bg_ymin = marg_bottom; double bg_ymax = scn_h-marg_top; + int n_rows = VERT_VAR_NUM ? vert_num_cats-1 : vert_num_cats; + int n_cols = HOR_VAR_NUM ? horiz_num_cats-1 : horiz_num_cats; + vector v_brk_ref(n_rows); + vector h_brk_ref(n_cols); - std::vector v_brk_ref(vert_num_cats-1); - std::vector h_brk_ref(horiz_num_cats-1); - - for (int row=0; rowlower_left, rec->upper_right, lower_left, upper_right))); - bool all_sel = (cell_data[t][r][c].ival_obs_cnt[ival] == - cell_data[t][r][c].ival_obs_sel_cnt[ival]); + bool all_sel = (cell_data[0][r][c].ival_obs_cnt[ival] == + cell_data[0][r][c].ival_obs_sel_cnt[ival]); if (pointsel && all_sel && selected) { // unselect all in ival for (std::list::iterator it = - cell_data[t][r][c].ival_to_obs_ids[ival].begin(); - it != cell_data[t][r][c].ival_to_obs_ids[ival].end(); it++) { + cell_data[0][r][c].ival_to_obs_ids[ival].begin(); + it != cell_data[0][r][c].ival_to_obs_ids[ival].end(); it++) { hs[(*it)]= false; selection_changed = true; } } else if (!all_sel && selected) { // select currently unselected in ival for (std::list::iterator it = - cell_data[t][r][c].ival_to_obs_ids[ival].begin(); - it != cell_data[t][r][c].ival_to_obs_ids[ival].end(); it++) { + cell_data[0][r][c].ival_to_obs_ids[ival].begin(); + it != cell_data[0][r][c].ival_to_obs_ids[ival].end(); it++) { if (hs[*it]) continue; hs[(*it)]= true; selection_changed = true; @@ -595,8 +618,8 @@ void ConditionalHistogramCanvas::UpdateSelection(bool shiftdown, bool pointsel) } else if (!selected && !shiftdown) { // unselect all selected in ival for (std::list::iterator it = - cell_data[t][r][c].ival_to_obs_ids[ival].begin(); - it != cell_data[t][r][c].ival_to_obs_ids[ival].end(); it++) { + cell_data[0][r][c].ival_to_obs_ids[ival].begin(); + it != cell_data[0][r][c].ival_to_obs_ids[ival].end(); it++) { if (!hs[*it]) continue; hs[(*it)]= false; selection_changed = true; @@ -629,7 +652,7 @@ void ConditionalHistogramCanvas::DrawSelectableShapes(wxMemoryDC &dc) for (int r=0; rpaintSelf(dc); } i++; @@ -646,9 +669,9 @@ void ConditionalHistogramCanvas::DrawHighlightedShapes(wxMemoryDC &dc) for (int r=0; rgetPen()); @@ -726,7 +749,7 @@ void ConditionalHistogramCanvas::InitIntervals() double ival_size = range/((double) cur_intervals); for (int i=0; i= ival_breaks[t][cur_ival]) + data_sorted[dt][i].first >= ival_breaks[0][cur_ival]) { cur_ival++; } @@ -783,22 +806,21 @@ void ConditionalHistogramCanvas::InitIntervals() obs_id_to_sel_shp[t][id] = cell_to_sel_shp_gen(r, c, cur_ival, cols, cur_intervals); - cell_data[t][r][c].ival_to_obs_ids[cur_ival].push_front(id); + cell_data[0][r][c].ival_to_obs_ids[cur_ival].push_front(id); - cell_data[t][r][c].ival_obs_cnt[cur_ival]++; + cell_data[0][r][c].ival_obs_cnt[cur_ival]++; - if (cell_data[t][r][c].ival_obs_cnt[cur_ival] > - max_num_obs_in_ival[t]) + if (cell_data[0][r][c].ival_obs_cnt[cur_ival] > max_num_obs_in_ival[t]) { max_num_obs_in_ival[t] = - cell_data[t][r][c].ival_obs_cnt[cur_ival]; + cell_data[0][r][c].ival_obs_cnt[cur_ival]; if (max_num_obs_in_ival[t] > overall_max_num_obs_in_ival) { overall_max_num_obs_in_ival = max_num_obs_in_ival[t]; } } if (hs[data_sorted[dt][i].second]) { - cell_data[t][r][c].ival_obs_sel_cnt[cur_ival]++; + cell_data[0][r][c].ival_obs_sel_cnt[cur_ival]++; } } } @@ -821,7 +843,7 @@ void ConditionalHistogramCanvas::UpdateIvalSelCnts() for (int r=0; rGetTotalHighlighted()> 0) { int n_total_hl = highlight_state->GetTotalHighlighted(); - s << "#selected=" << n_total_hl << " "; + s << _("#selected=") << n_total_hl << " "; int n_undefs = 0; for (int i=0; i 0) { - s << "(undefined:" << n_undefs << ") "; + s << _("undefined: ") << n_undefs << ") "; } } sb->SetStatusText(s); @@ -918,13 +940,12 @@ void ConditionalHistogramCanvas::UpdateStatusBar() } int r, c, ival; sel_shp_to_cell(hover_obs[0], r, c, ival); - double ival_min = (ival == 0) ? min_ival_val[t] : ival_breaks[t][ival-1]; - double ival_max = ((ival == cur_intervals-1) ? - max_ival_val[t] : ival_breaks[t][ival]); + double ival_min = (ival == 0) ? min_ival_val[0] : ival_breaks[0][ival-1]; + double ival_max = (ival == cur_intervals-1) ? max_ival_val[0] : ival_breaks[0][ival]; s << "bin: " << ival+1 << ", range: [" << ival_min << ", " << ival_max; s << (ival == cur_intervals-1 ? "]" : ")"); - s << ", #obs: " << cell_data[t][r][c].ival_obs_cnt[ival]; - s << ", #sel: " << cell_data[t][r][c].ival_obs_sel_cnt[ival]; + s << ", #obs: " << cell_data[0][r][c].ival_obs_cnt[ival]; + s << ", #sel: " << cell_data[0][r][c].ival_obs_sel_cnt[ival]; sb->SetStatusText(s); } @@ -1014,7 +1035,7 @@ void ConditionalHistogramFrame::MapMenus() TemplateCanvas::AppendCustomCategories(optMenu, project->GetCatClassifManager()); ((ConditionalHistogramCanvas*) template_canvas)->SetCheckMarks(optMenu); - GeneralWxUtils::ReplaceMenu(mb, "Options", optMenu); + GeneralWxUtils::ReplaceMenu(mb, _("Options"), optMenu); UpdateOptionMenuItems(); } @@ -1022,7 +1043,7 @@ void ConditionalHistogramFrame::UpdateOptionMenuItems() { TemplateFrame::UpdateOptionMenuItems(); // set common items first wxMenuBar* mb = GdaFrame::GetGdaFrame()->GetMenuBar(); - int menu = mb->FindMenu("Options"); + int menu = mb->FindMenu(_("Options")); if (menu == wxNOT_FOUND) { } else { ((ConditionalHistogramCanvas*) @@ -1063,3 +1084,10 @@ void ConditionalHistogramFrame::OnHistogramIntervals(wxCommandEvent& ev) (ConditionalHistogramCanvas*) template_canvas; t->HistogramIntervals(); } + +void ConditionalHistogramFrame::OnSaveCanvasImageAs(wxCommandEvent& event) +{ + if (!template_canvas) return; + wxString title = project->GetProjectTitle(); + GeneralWxUtils::SaveWindowAsImage(template_canvas, title); +} diff --git a/Explore/ConditionalHistogramView.h b/Explore/ConditionalHistogramView.h index 276f424c6..c307abc29 100644 --- a/Explore/ConditionalHistogramView.h +++ b/Explore/ConditionalHistogramView.h @@ -54,7 +54,7 @@ class ConditionalHistogramCanvas : public ConditionalNewCanvas { virtual void SetCheckMarks(wxMenu* menu); virtual void update(HLStateInt* o); virtual wxString GetCanvasTitle(); - + virtual wxString GetVariableNames(); virtual void DetermineMouseHoverObjects(wxPoint pt); virtual void UpdateSelection(bool shiftdown = false, bool pointsel = false); @@ -64,10 +64,9 @@ class ConditionalHistogramCanvas : public ConditionalNewCanvas { virtual void ResizeSelectableShps(int virtual_scrn_w = 0, int virtual_scrn_h = 0); -protected: virtual void PopulateCanvas(); + virtual void UpdateStatusBar(); -public: virtual void TimeSyncVariableToggle(int var_index); void ShowAxes(bool show_axes); @@ -78,7 +77,6 @@ class ConditionalHistogramCanvas : public ConditionalNewCanvas { void UpdateIvalSelCnts(); virtual void UserChangedCellCategories(); protected: - virtual void UpdateStatusBar(); void sel_shp_to_cell_gen(int i, int& r, int& c, int& ival, int cols, int ivals); void sel_shp_to_cell(int i, int& r, int& c, int& ival); @@ -145,7 +143,7 @@ class ConditionalHistogramFrame : public ConditionalNewFrame { virtual void MapMenus(); virtual void UpdateOptionMenuItems(); virtual void UpdateContextMenuItems(wxMenu* menu); - + virtual void OnSaveCanvasImageAs(wxCommandEvent& event); /** Implementation of TimeStateObserver interface */ virtual void update(TimeState* o); diff --git a/Explore/ConditionalMapView.cpp b/Explore/ConditionalMapView.cpp index 6a6381142..67184268b 100644 --- a/Explore/ConditionalMapView.cpp +++ b/Explore/ConditionalMapView.cpp @@ -37,7 +37,7 @@ #include "../GeneralWxUtils.h" #include "../GeoDa.h" #include "../Project.h" -#include "../ShapeOperations/ShapeUtils.h" + #include "ConditionalMapView.h" using namespace std; @@ -110,12 +110,10 @@ void ConditionalMapCanvas::DisplayRightClickMenu(const wxPoint& pos) wxActivateEvent ae(wxEVT_NULL, true, 0, wxActivateEvent::Reason_Mouse); ((ConditionalMapFrame*) template_frame)->OnActivate(ae); - wxMenu* optMenu = wxXmlResource::Get()-> - LoadMenu("ID_COND_MAP_VIEW_MENU_OPTIONS"); + wxMenu* optMenu = wxXmlResource::Get()->LoadMenu("ID_COND_MAP_VIEW_MENU_OPTIONS"); AddTimeVariantOptionsToMenu(optMenu); - TemplateCanvas::AppendCustomCategories(optMenu, - project->GetCatClassifManager()); + TemplateCanvas::AppendCustomCategories(optMenu, project->GetCatClassifManager()); SetCheckMarks(optMenu); template_frame->UpdateContextMenuItems(optMenu); @@ -131,7 +129,6 @@ void ConditionalMapCanvas::OnScrollChanged(wxScrollWinEvent& event) event.Skip(); } - void ConditionalMapCanvas::SetCheckMarks(wxMenu* menu) { // Update the checkmarks and enable/disable state for the @@ -143,37 +140,23 @@ void ConditionalMapCanvas::SetCheckMarks(wxMenu* menu) GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_MAPANALYSIS_THEMELESS"), GetCatType() == CatClassification::no_theme); - // since XRCID is a macro, we can't make this into a loop - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_QUANTILE_1"), - (GetCatType() == CatClassification::quantile) - && GetNumCats() == 1); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_QUANTILE_2"), - (GetCatType() == CatClassification::quantile) - && GetNumCats() == 2); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_QUANTILE_3"), - (GetCatType() == CatClassification::quantile) - && GetNumCats() == 3); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_QUANTILE_4"), - (GetCatType() == CatClassification::quantile) - && GetNumCats() == 4); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_QUANTILE_5"), - (GetCatType() == CatClassification::quantile) - && GetNumCats() == 5); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_QUANTILE_6"), - (GetCatType() == CatClassification::quantile) - && GetNumCats() == 6); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_QUANTILE_7"), - (GetCatType() == CatClassification::quantile) - && GetNumCats() == 7); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_QUANTILE_8"), - (GetCatType() == CatClassification::quantile) - && GetNumCats() == 8); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_QUANTILE_9"), - (GetCatType() == CatClassification::quantile) - && GetNumCats() == 9); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_QUANTILE_10"), - (GetCatType() == CatClassification::quantile) - && GetNumCats() == 10); + + for (int i=1; i<=10; i++) { + wxString str_xrcid; + bool flag; + + str_xrcid = wxString::Format("ID_QUANTILE_%d", i); + flag = GetCatType()==CatClassification::quantile && GetNumCats()==i; + GeneralWxUtils::CheckMenuItem(menu, XRCID(str_xrcid), flag); + + str_xrcid = wxString::Format("ID_EQUAL_INTERVALS_%d", i); + flag = GetCatType()==CatClassification::equal_intervals && GetNumCats()==i; + GeneralWxUtils::CheckMenuItem(menu, XRCID(str_xrcid), flag); + + str_xrcid = wxString::Format("ID_NATURAL_BREAKS_%d", i); + flag = GetCatType()==CatClassification::natural_breaks && GetNumCats()==i; + GeneralWxUtils::CheckMenuItem(menu, XRCID(str_xrcid), flag); + } GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_MAPANALYSIS_CHOROPLETH_PERCENTILE"), @@ -187,91 +170,6 @@ void ConditionalMapCanvas::SetCheckMarks(wxMenu* menu) GetCatType() == CatClassification::stddev); GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_MAPANALYSIS_UNIQUE_VALUES"), GetCatType() == CatClassification::unique_values); - - // since XRCID is a macro, we can't make this into a loop - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_EQUAL_INTERVALS_1"), - (GetCatType() == - CatClassification::equal_intervals) - && GetNumCats() == 1); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_EQUAL_INTERVALS_2"), - (GetCatType() == - CatClassification::equal_intervals) - && GetNumCats() == 2); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_EQUAL_INTERVALS_3"), - (GetCatType() == - CatClassification::equal_intervals) - && GetNumCats() == 3); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_EQUAL_INTERVALS_4"), - (GetCatType() == - CatClassification::equal_intervals) - && GetNumCats() == 4); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_EQUAL_INTERVALS_5"), - (GetCatType() == - CatClassification::equal_intervals) - && GetNumCats() == 5); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_EQUAL_INTERVALS_6"), - (GetCatType() == - CatClassification::equal_intervals) - && GetNumCats() == 6); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_EQUAL_INTERVALS_7"), - (GetCatType() == - CatClassification::equal_intervals) - && GetNumCats() == 7); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_EQUAL_INTERVALS_8"), - (GetCatType() == - CatClassification::equal_intervals) - && GetNumCats() == 8); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_EQUAL_INTERVALS_9"), - (GetCatType() == - CatClassification::equal_intervals) - && GetNumCats() == 9); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_EQUAL_INTERVALS_10"), - (GetCatType() == - CatClassification::equal_intervals) - && GetNumCats() == 10); - - // since XRCID is a macro, we can't make this into a loop - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_NATURAL_BREAKS_1"), - (GetCatType() == - CatClassification::natural_breaks) - && GetNumCats() == 1); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_NATURAL_BREAKS_2"), - (GetCatType() == - CatClassification::natural_breaks) - && GetNumCats() == 2); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_NATURAL_BREAKS_3"), - (GetCatType() == - CatClassification::natural_breaks) - && GetNumCats() == 3); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_NATURAL_BREAKS_4"), - (GetCatType() == - CatClassification::natural_breaks) - && GetNumCats() == 4); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_NATURAL_BREAKS_5"), - (GetCatType() == - CatClassification::natural_breaks) - && GetNumCats() == 5); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_NATURAL_BREAKS_6"), - (GetCatType() == - CatClassification::natural_breaks) - && GetNumCats() == 6); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_NATURAL_BREAKS_7"), - (GetCatType() == - CatClassification::natural_breaks) - && GetNumCats() == 7); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_NATURAL_BREAKS_8"), - (GetCatType() == - CatClassification::natural_breaks) - && GetNumCats() == 8); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_NATURAL_BREAKS_9"), - (GetCatType() == - CatClassification::natural_breaks) - && GetNumCats() == 9); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_NATURAL_BREAKS_10"), - (GetCatType() == - CatClassification::natural_breaks) - && GetNumCats() == 10); - } wxString ConditionalMapCanvas::GetCategoriesTitle() @@ -281,7 +179,7 @@ wxString ConditionalMapCanvas::GetCategoriesTitle() v << cat_classif_def_map.title; v << ": " << GetNameWithTime(CAT_VAR); } else if (GetCatType() == CatClassification::no_theme) { - v << "Themeless"; + v << _("Themeless"); } else { v << CatClassification::CatClassifTypeToString(GetCatType()); v << ": " << GetNameWithTime(CAT_VAR); @@ -292,7 +190,7 @@ wxString ConditionalMapCanvas::GetCategoriesTitle() wxString ConditionalMapCanvas::GetCanvasTitle() { wxString v; - v << "Conditional Map - "; + v << _("Conditional Map") << " - "; v << "x: " << GetNameWithTime(HOR_VAR); v << ", y: " << GetNameWithTime(VERT_VAR); if (GetCatType() == CatClassification::custom) { @@ -305,6 +203,13 @@ wxString ConditionalMapCanvas::GetCanvasTitle() return v; } +wxString ConditionalMapCanvas::GetVariableNames() +{ + wxString v; + v << GetNameWithTime(CAT_VAR); + return v; +} + void ConditionalMapCanvas::OnSaveCategories() { wxString t_name = CatClassification::CatClassifTypeToString(GetCatType()); @@ -374,7 +279,7 @@ void ConditionalMapCanvas::NewCustomCatClassifMap() if (template_frame) { template_frame->UpdateTitle(); if (template_frame->GetTemplateLegend()) { - template_frame->GetTemplateLegend()->Refresh(); + template_frame->GetTemplateLegend()->Recreate(); } } } @@ -418,7 +323,7 @@ void ConditionalMapCanvas::ChangeCatThemeType( if (all_init && template_frame) { template_frame->UpdateTitle(); if (template_frame->GetTemplateLegend()) { - template_frame->GetTemplateLegend()->Refresh(); + template_frame->GetTemplateLegend()->Recreate(); } } } @@ -433,7 +338,7 @@ void ConditionalMapCanvas::update(CatClassifState* o) if (template_frame) { template_frame->UpdateTitle(); if (template_frame->GetTemplateLegend()) { - template_frame->GetTemplateLegend()->Refresh(); + template_frame->GetTemplateLegend()->Recreate(); } } } else { @@ -480,7 +385,7 @@ void ConditionalMapCanvas::ResizeSelectableShps(int virtual_scrn_w, if (pad_h < 1) pad_h = 1; - double pad = GenUtils::min(pad_w, pad_h); + double pad = std::min(pad_w, pad_h); double marg_top = last_scale_trans.top_margin; double marg_bottom = last_scale_trans.bottom_margin; @@ -584,49 +489,35 @@ void ConditionalMapCanvas::ResizeSelectableShps(int virtual_scrn_w, double bg_xmax = scn_w-marg_right; double bg_ymin = marg_bottom; double bg_ymax = scn_h-marg_top; - - vector v_brk_ref(vert_num_cats-1); - vector h_brk_ref(horiz_num_cats-1); + int n_rows = VERT_VAR_NUM ? vert_num_cats-1 : vert_num_cats; + int n_cols = HOR_VAR_NUM ? horiz_num_cats-1 : horiz_num_cats; + vector v_brk_ref(n_rows); + vector h_brk_ref(n_cols); - for (int row=0; rowGetStatusBar(); if (!sb) return; + if (var_info.empty()) return; + if (cat_var_undef.empty()) return; int t = var_info[CAT_VAR].time; @@ -952,31 +827,33 @@ void ConditionalMapCanvas::UpdateStatusBar() wxString s; if (highlight_state->GetTotalHighlighted()> 0) { int n_total_hl = highlight_state->GetTotalHighlighted(); - s << "#selected=" << n_total_hl << " "; + s << _("#selected=") << n_total_hl << " "; int n_undefs = 0; for (int i=0; i 0) { - s << "(undefined:" << n_undefs << ") "; + s << _("undefined: ") << n_undefs << ") "; } } if (mousemode == select && selectstate == start) { if (total_hover_obs >= 1) { - s << "hover obs " << hover_obs[0]+1 << " = "; + s << _("#hover obs ") << hover_obs[0]+1 << " = "; s << data[CAT_VAR][t][hover_obs[0]]; } if (total_hover_obs >= 2) { s << ", "; - s << "obs " << hover_obs[1]+1 << " = "; + s << _("obs ") << hover_obs[1]+1 << " = "; s << data[CAT_VAR][t][hover_obs[1]]; } if (total_hover_obs >= 3) { s << ", "; - s << "obs " << hover_obs[2]+1 << " = "; + s << _("obs ") << hover_obs[2]+1 << " = "; s << data[CAT_VAR][t][hover_obs[2]]; } if (total_hover_obs >= 4) { @@ -1079,7 +956,7 @@ void ConditionalMapFrame::MapMenus() TemplateCanvas::AppendCustomCategories(optMenu, project->GetCatClassifManager()); ((ConditionalMapCanvas*) template_canvas)->SetCheckMarks(optMenu); - GeneralWxUtils::ReplaceMenu(mb, "Options", optMenu); + GeneralWxUtils::ReplaceMenu(mb, _("Options"), optMenu); UpdateOptionMenuItems(); } @@ -1087,7 +964,7 @@ void ConditionalMapFrame::UpdateOptionMenuItems() { TemplateFrame::UpdateOptionMenuItems(); // set common items first wxMenuBar* mb = GdaFrame::GetGdaFrame()->GetMenuBar(); - int menu = mb->FindMenu("Options"); + int menu = mb->FindMenu(_("Options")); if (menu == wxNOT_FOUND) { } else { ((ConditionalMapCanvas*) diff --git a/Explore/ConditionalMapView.h b/Explore/ConditionalMapView.h index f66c58857..008d577dc 100644 --- a/Explore/ConditionalMapView.h +++ b/Explore/ConditionalMapView.h @@ -46,7 +46,7 @@ class ConditionalMapCanvas : public ConditionalNewCanvas { virtual void DisplayRightClickMenu(const wxPoint& pos); virtual wxString GetCategoriesTitle(); virtual wxString GetCanvasTitle(); - + virtual wxString GetVariableNames(); virtual void NewCustomCatClassifMap(); virtual void ChangeCatThemeType( CatClassification::CatClassifType new_theme, @@ -66,10 +66,8 @@ class ConditionalMapCanvas : public ConditionalNewCanvas { //virtual void OnMouseEvent(wxMouseEvent& event); virtual void OnScrollChanged(wxScrollWinEvent& event); -protected: virtual void PopulateCanvas(); -public: virtual void CreateAndUpdateCategories(); virtual void TimeSyncVariableToggle(int var_index); @@ -78,6 +76,8 @@ class ConditionalMapCanvas : public ConditionalNewCanvas { void SetCatType(CatClassification::CatClassifType cc_type); int GetNumCats() { return num_categories; } + virtual void UpdateStatusBar(); + protected: CatClassifState* cc_state_map; int num_categories; // current number of categories @@ -96,7 +96,6 @@ class ConditionalMapCanvas : public ConditionalNewCanvas { static const int CAT_VAR; // theme variable - virtual void UpdateStatusBar(); DECLARE_EVENT_TABLE() }; diff --git a/Explore/ConditionalNewView.cpp b/Explore/ConditionalNewView.cpp index 9b3b585d6..333fea5ab 100644 --- a/Explore/ConditionalNewView.cpp +++ b/Explore/ConditionalNewView.cpp @@ -37,7 +37,7 @@ #include "../GeoDa.h" #include "../Project.h" #include "../TemplateLegend.h" -#include "../ShapeOperations/ShapeUtils.h" + #include "ConditionalNewView.h" @@ -60,7 +60,8 @@ ConditionalNewCanvas(wxWindow *parent, const std::vector& col_ids, bool fixed_aspect_ratio_mode, bool fit_to_window_mode, - const wxPoint& pos, const wxSize& size) + const wxPoint& pos, + const wxSize& size) :TemplateCanvas(parent, t_frame, project_s, project_s->GetHighlightState(), pos, size, fixed_aspect_ratio_mode, fit_to_window_mode), num_obs(project_s->GetNumRecords()), num_time_vals(1), @@ -68,61 +69,93 @@ vert_num_time_vals(1), horiz_num_time_vals(1), horiz_num_cats(3), vert_num_cats(3), bin_extents(boost::extents[3][3]), bin_w(0), bin_h(0), data(v_info.size()), +s_data(v_info.size()), data_undef(v_info.size()), var_info(v_info), table_int(project_s->GetTableInt()), -is_any_time_variant(false), is_any_sync_with_global_time(false), -cc_state_vert(0), cc_state_horiz(0), all_init(false) +is_any_time_variant(false), +is_any_sync_with_global_time(false), +cc_state_vert(0), +cc_state_horiz(0), +all_init(false) { axis_display_precision = 1; - SetCatType(VERT_VAR, CatClassification::quantile, 3); - SetCatType(HOR_VAR, CatClassification::quantile, 3); template_frame->ClearAllGroupDependencies(); + + GdaConst::FieldType hor_ftype = table_int->GetColType(col_ids[HOR_VAR]); + GdaConst::FieldType vert_ftype = table_int->GetColType(col_ids[VERT_VAR]); + + HOR_VAR_NUM = hor_ftype != GdaConst::string_type; + VERT_VAR_NUM = vert_ftype != GdaConst::string_type; + + if (HOR_VAR_NUM) table_int->GetColData(col_ids[HOR_VAR], data[HOR_VAR]); + else table_int->GetColData(col_ids[HOR_VAR], s_data[HOR_VAR]); + + if (VERT_VAR_NUM) table_int->GetColData(col_ids[VERT_VAR], data[VERT_VAR]); + else table_int->GetColData(col_ids[VERT_VAR], s_data[VERT_VAR]); + for (size_t i=0; iGetColData(col_ids[i], data[i]); + if (i != HOR_VAR && i != VERT_VAR) + table_int->GetColData(col_ids[i], data[i]); table_int->GetColUndefined(col_ids[i], data_undef[i]); template_frame->AddGroupDependancy(var_info[i].name); } - horiz_num_time_vals = data[HOR_VAR].size(); - vert_num_time_vals = data[VERT_VAR].size(); - + //setup horizontal data + horiz_num_time_vals = HOR_VAR_NUM ? data[HOR_VAR].size() : s_data[HOR_VAR].size(); horiz_undef_tms.resize(horiz_num_time_vals); - vert_undef_tms.resize(vert_num_time_vals); + horiz_cats_valid.resize(horiz_num_time_vals); + horiz_cats_error_message.resize(horiz_num_time_vals); - horiz_var_sorted.resize(horiz_num_time_vals); - horiz_cats_valid.resize(horiz_num_time_vals); - horiz_cats_error_message.resize(horiz_num_time_vals); + if (HOR_VAR_NUM) { + SetCatType(HOR_VAR, CatClassification::quantile, 3); + horiz_var_sorted.resize(horiz_num_time_vals); + } else { + SetCatType(HOR_VAR, CatClassification::unique_values, 3); + horiz_str_var_sorted.resize(horiz_num_time_vals); + } for (int t=0; tAppendCheckItem(GdaConst::ID_TIME_SYNC_VAR1+i, s, s); + wxMenuItem* mi = menu1->AppendCheckItem(GdaConst::ID_TIME_SYNC_VAR1+i, s, s); mi->Check(var_info[i].sync_with_global_time); } } @@ -183,51 +213,69 @@ void ConditionalNewCanvas::SetCheckMarks(wxMenu* menu) // following menu items if they were specified for this particular // view in the xrc file. Items that cannot be enable/disabled, // or are not checkable do not appear. - + CatClassifManager* ccm = project->GetCatClassifManager(); + vector titles; + ccm->GetTitles(titles); + GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_COND_VERT_THEMELESS"), GetCatType(VERT_VAR) == CatClassification::no_theme); - // since XRCID is a macro, we can't make this into a loop - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_COND_VERT_QUANT_1"), - (GetCatType(VERT_VAR) == - CatClassification::quantile) - && GetVertNumCats() == 1); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_COND_VERT_QUANT_2"), - (GetCatType(VERT_VAR) == - CatClassification::quantile) - && GetVertNumCats() == 2); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_COND_VERT_QUANT_3"), - (GetCatType(VERT_VAR) == - CatClassification::quantile) - && GetVertNumCats() == 3); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_COND_VERT_QUANT_4"), - (GetCatType(VERT_VAR) == - CatClassification::quantile) - && GetVertNumCats() == 4); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_COND_VERT_QUANT_5"), - (GetCatType(VERT_VAR) == - CatClassification::quantile) - && GetVertNumCats() == 5); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_COND_VERT_QUANT_6"), - (GetCatType(VERT_VAR) == - CatClassification::quantile) - && GetVertNumCats() == 6); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_COND_VERT_QUANT_7"), - (GetCatType(VERT_VAR) == - CatClassification::quantile) - && GetVertNumCats() == 7); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_COND_VERT_QUANT_8"), - (GetCatType(VERT_VAR) == - CatClassification::quantile) - && GetVertNumCats() == 8); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_COND_VERT_QUANT_9"), - (GetCatType(VERT_VAR) == - CatClassification::quantile) - && GetVertNumCats() == 9); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_COND_VERT_QUANT_10"), - (GetCatType(VERT_VAR) == - CatClassification::quantile) - && GetVertNumCats() == 10); + GeneralWxUtils::EnableMenuItem(menu, XRCID("ID_COND_VERT_THEMELESS"), VERT_VAR_NUM); + GeneralWxUtils::EnableMenuItem(menu, XRCID("ID_COND_VERT_QUANT_SUBMENU"), VERT_VAR_NUM); + GeneralWxUtils::EnableMenuItem(menu, XRCID("ID_COND_VERT_CHOROPLETH_PERCENTILE"), VERT_VAR_NUM); + GeneralWxUtils::EnableMenuItem(menu, XRCID("ID_COND_VERT_HINGE_15"), VERT_VAR_NUM); + GeneralWxUtils::EnableMenuItem(menu, XRCID("ID_COND_VERT_HINGE_30"), VERT_VAR_NUM); + GeneralWxUtils::EnableMenuItem(menu, XRCID("ID_COND_VERT_CHOROPLETH_STDDEV"), VERT_VAR_NUM); + //GeneralWxUtils::EnableMenuItem(menu, XRCID("ID_COND_VERT_UNIQUE_VALUES"), VERT_VAR_NUM); + GeneralWxUtils::EnableMenuItem(menu, XRCID("ID_COND_VERT_EQU_INTS_SUBMENU"), VERT_VAR_NUM); + GeneralWxUtils::EnableMenuItem(menu, XRCID("ID_COND_VERT_NAT_BRKS_SUBMENU"), VERT_VAR_NUM); + GeneralWxUtils::EnableMenuItem(menu, XRCID("ID_NEW_CUSTOM_CAT_CLASSIF_B"), VERT_VAR_NUM); + for (size_t j=0; jPromptNew(cat_classif_def_vert, "", var.name, var.time); + + if (!ccs) + return; + if (cc_state_vert) cc_state_vert->removeObserver(this); @@ -552,7 +392,7 @@ void ConditionalNewCanvas::NewCustomCatClassifVert() if (template_frame) { template_frame->UpdateTitle(); if (template_frame->GetTemplateLegend()) { - template_frame->GetTemplateLegend()->Refresh(); + template_frame->GetTemplateLegend()->Recreate(); } } } @@ -594,6 +434,10 @@ void ConditionalNewCanvas::NewCustomCatClassifHoriz() CatClassifState* ccs = ccf->PromptNew(cat_classif_def_horiz, "", var.name, var.time); + + if (!ccs) + return; + if (cc_state_horiz) cc_state_horiz->removeObserver(this); @@ -607,7 +451,7 @@ void ConditionalNewCanvas::NewCustomCatClassifHoriz() if (template_frame) { template_frame->UpdateTitle(); if (template_frame->GetTemplateLegend()) { - template_frame->GetTemplateLegend()->Refresh(); + template_frame->GetTemplateLegend()->Recreate(); } } } @@ -653,7 +497,7 @@ ChangeThemeType(int var_id, if (template_frame) { template_frame->UpdateTitle(); if (template_frame->GetTemplateLegend()) { - template_frame->GetTemplateLegend()->Refresh(); + template_frame->GetTemplateLegend()->Recreate(); } } } @@ -677,7 +521,7 @@ void ConditionalNewCanvas::update(CatClassifState* o) if (template_frame) { template_frame->UpdateTitle(); if (template_frame->GetTemplateLegend()) { - template_frame->GetTemplateLegend()->Refresh(); + template_frame->GetTemplateLegend()->Recreate(); } } } @@ -764,7 +608,8 @@ void ConditionalNewCanvas::CreateAndUpdateCategories(int var_id) bool useUndefinedCategory = false; - CatClassification::PopulateCatClassifData(cat_classif_def_vert, + if (VERT_VAR_NUM) + CatClassification::PopulateCatClassifData(cat_classif_def_vert, vert_var_sorted, vert_undef_tms, vert_cat_data, @@ -772,9 +617,19 @@ void ConditionalNewCanvas::CreateAndUpdateCategories(int var_id) vert_cats_error_message, this->useScientificNotation, useUndefinedCategory); + else + CatClassification::PopulateCatClassifData(cat_classif_def_vert, + vert_str_var_sorted, + vert_undef_tms, + vert_cat_data, + vert_cats_valid, + vert_cats_error_message, + this->useScientificNotation, + useUndefinedCategory); int vt = var_info[var_id].time; vert_num_cats = vert_cat_data.categories[vt].cat_vec.size(); CatClassification::ChangeNumCats(vert_num_cats, cat_classif_def_vert); + } else { for (int t=0; tuseScientificNotation, useUndefinedCategory); + else + CatClassification::PopulateCatClassifData(cat_classif_def_horiz, + horiz_str_var_sorted, // could be wxString + horiz_undef_tms, + horiz_cat_data, + horiz_cats_valid, + horiz_cats_error_message, + this->useScientificNotation, + useUndefinedCategory); int ht = var_info[var_id].time; horiz_num_cats = horiz_cat_data.categories[ht].cat_vec.size(); CatClassification::ChangeNumCats(horiz_num_cats, cat_classif_def_horiz); @@ -832,7 +697,7 @@ void ConditionalNewCanvas::UpdateStatusBar() wxString s; if (mousemode == select && (selectstate == dragging || selectstate == brushing)) { - s << "#selected=" << highlight_state->GetTotalHighlighted(); + s << _("#selected=") << highlight_state->GetTotalHighlighted(); } sb->SetStatusText(s); } @@ -890,7 +755,7 @@ void ConditionalNewFrame::UpdateOptionMenuItems() { TemplateFrame::UpdateOptionMenuItems(); // set common items first wxMenuBar* mb = GdaFrame::GetGdaFrame()->GetMenuBar(); - int menu = mb->FindMenu("Options"); + int menu = mb->FindMenu(_("Options")); if (menu == wxNOT_FOUND) { } else { ((ConditionalNewCanvas*) diff --git a/Explore/ConditionalNewView.h b/Explore/ConditionalNewView.h index de45a072d..6bafc0459 100644 --- a/Explore/ConditionalNewView.h +++ b/Explore/ConditionalNewView.h @@ -35,17 +35,17 @@ class ConditionalNewCanvas; class ConditionalNewLegend; class TableInterface; -typedef boost::multi_array d_array_type; typedef boost::multi_array b_array_type; - +typedef boost::multi_array d_array_type; +typedef boost::multi_array s_array_type; typedef boost::multi_array rec_array_type; class ConditionalNewCanvas : public TemplateCanvas, public CatClassifStateObserver { DECLARE_CLASS(ConditionalNewCanvas) + public: - ConditionalNewCanvas(wxWindow *parent, TemplateFrame* t_frame, Project* project, const std::vector& var_info, @@ -54,7 +54,9 @@ class ConditionalNewCanvas bool fit_to_window_mode = true, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize); + virtual ~ConditionalNewCanvas(); + virtual void DisplayRightClickMenu(const wxPoint& pos); virtual void AddTimeVariantOptionsToMenu(wxMenu* menu); virtual wxString GetCategoriesTitle(int var_id); @@ -73,11 +75,9 @@ class ConditionalNewCanvas virtual void SetCheckMarks(wxMenu* menu); virtual void TimeChange(); -protected: virtual void PopulateCanvas(); virtual void VarInfoAttributeChange(); -public: virtual void CreateAndUpdateCategories(int var_id); virtual void UpdateNumVertHorizCats(); virtual void UserChangedCellCategories() {} @@ -86,12 +86,18 @@ class ConditionalNewCanvas CatClassifDef cat_classif_def_horiz; CatClassifDef cat_classif_def_vert; + CatClassification::CatClassifType GetCatType(int var_id); - void SetCatType(int var_id, CatClassification::CatClassifType cc_type, + + void SetCatType(int var_id, + CatClassification::CatClassifType cc_type, int num_categories); + int GetHorizNumCats() { return horiz_num_cats; } int GetVertNumCats() { return vert_num_cats; } + virtual void UpdateStatusBar(); + protected: TableInterface* table_int; CatClassifState* cc_state_vert; @@ -102,8 +108,13 @@ class ConditionalNewCanvas int vert_num_time_vals; int horiz_num_time_vals; int ref_var_index; + + bool HOR_VAR_NUM; + bool VERT_VAR_NUM; + std::vector var_info; std::vector data; + std::vector s_data; std::vector data_undef; bool is_any_time_variant; @@ -114,6 +125,9 @@ class ConditionalNewCanvas std::vector horiz_var_sorted; std::vector vert_var_sorted; + std::vector horiz_str_var_sorted; + std::vector vert_str_var_sorted; + std::vector > horiz_undef_tms; // undef tms std::vector > vert_undef_tms; // undef tms @@ -128,9 +142,8 @@ class ConditionalNewCanvas rec_array_type bin_extents; int bin_w; int bin_h; - bool all_init; - virtual void UpdateStatusBar(); + DECLARE_EVENT_TABLE() }; @@ -141,7 +154,7 @@ class ConditionalNewFrame : public TemplateFrame { ConditionalNewFrame(wxFrame *parent, Project* project, const std::vector& var_info, const std::vector& col_ids, - const wxString& title = "Conditional Map", + const wxString& title = _("Conditional Map"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, const long style = wxDEFAULT_FRAME_STYLE); diff --git a/Explore/ConditionalScatterPlotView.cpp b/Explore/ConditionalScatterPlotView.cpp index 9352c1314..c42d7481a 100644 --- a/Explore/ConditionalScatterPlotView.cpp +++ b/Explore/ConditionalScatterPlotView.cpp @@ -35,7 +35,7 @@ #include "../logger.h" #include "../GeoDa.h" #include "../Project.h" -#include "../ShapeOperations/ShapeUtils.h" + #include "ConditionalScatterPlotView.h" @@ -173,6 +173,13 @@ wxString ConditionalScatterPlotCanvas::GetCanvasTitle() return v; } +wxString ConditionalScatterPlotCanvas::GetVariableNames() +{ + wxString v; + v << GetNameWithTime(IND_VAR); + v << ", " << GetNameWithTime(DEP_VAR); + return v; +} void ConditionalScatterPlotCanvas::ResizeSelectableShps(int virtual_scrn_w, int virtual_scrn_h) @@ -214,7 +221,7 @@ void ConditionalScatterPlotCanvas::ResizeSelectableShps(int virtual_scrn_w, double pad_h = scn_h * fac; if (pad_w < 1) pad_w = 0; if (pad_h < 1) pad_h = 0; - double pad_bump = GenUtils::min(pad_w, pad_h); + double pad_bump = std::min(pad_w, pad_h); double pad = min_pad + pad_bump; double marg_top = last_scale_trans.top_margin; @@ -290,18 +297,23 @@ void ConditionalScatterPlotCanvas::ResizeSelectableShps(int virtual_scrn_w, GdaShape* s; int vt = var_info[VERT_VAR].time; for (int row=0; rowGetTotalHighlighted()> 0) { int n_total_hl = highlight_state->GetTotalHighlighted(); - s << "#selected=" << n_total_hl << " "; + s << _("#selected=") << n_total_hl << " "; int n_undefs = 0; for (int i=0; i 0) { - s << "(undefined:" << n_undefs << ") "; + s << _("undefined: ") << n_undefs << ") "; } } if (mousemode == select && selectstate == start) { if (total_hover_obs >= 1) { - s << "hover obs " << hover_obs[0]+1 << " = ("; + s << _("#hover obs ") << hover_obs[0]+1 << " = ("; s << data[IND_VAR][var_info[IND_VAR].time][hover_obs[0]] << ","; s << data[DEP_VAR][var_info[DEP_VAR].time][hover_obs[0]] << ")"; } if (total_hover_obs >= 2) { s << ", "; - s << "obs " << hover_obs[1]+1 << " = ("; + s << _("obs ") << hover_obs[1]+1 << " = ("; s << data[IND_VAR][var_info[IND_VAR].time][hover_obs[1]] << ","; s << data[DEP_VAR][var_info[DEP_VAR].time][hover_obs[1]] << ")"; } if (total_hover_obs >= 3) { s << ", "; - s << "obs " << hover_obs[2]+1 << " = ("; + s << _("obs ") << hover_obs[2]+1 << " = ("; s << data[IND_VAR][var_info[IND_VAR].time][hover_obs[2]] << ","; s << data[DEP_VAR][var_info[DEP_VAR].time][hover_obs[2]] << ")"; } @@ -821,7 +849,7 @@ void ConditionalScatterPlotFrame::MapMenus() TemplateCanvas::AppendCustomCategories(optMenu, project->GetCatClassifManager()); ((ConditionalScatterPlotCanvas*) template_canvas)->SetCheckMarks(optMenu); - GeneralWxUtils::ReplaceMenu(mb, "Options", optMenu); + GeneralWxUtils::ReplaceMenu(mb, _("Options"), optMenu); UpdateOptionMenuItems(); } @@ -829,7 +857,7 @@ void ConditionalScatterPlotFrame::UpdateOptionMenuItems() { TemplateFrame::UpdateOptionMenuItems(); // set common items first wxMenuBar* mb = GdaFrame::GetGdaFrame()->GetMenuBar(); - int menu = mb->FindMenu("Options"); + int menu = mb->FindMenu(_("Options")); if (menu == wxNOT_FOUND) { } else { ((ConditionalScatterPlotCanvas*) @@ -914,3 +942,11 @@ void ConditionalScatterPlotFrame::OnDisplaySlopeValues(wxCommandEvent& ev) c->DisplaySlopeValues(!c->IsDisplaySlopeValues()); UpdateOptionMenuItems(); } + +void ConditionalScatterPlotFrame::OnSaveCanvasImageAs(wxCommandEvent& event) +{ + if (!template_canvas) return; + wxString title = project->GetProjectTitle(); + GeneralWxUtils::SaveWindowAsImage(template_canvas, title); +} + diff --git a/Explore/ConditionalScatterPlotView.h b/Explore/ConditionalScatterPlotView.h index 60b66a207..7771b81eb 100644 --- a/Explore/ConditionalScatterPlotView.h +++ b/Explore/ConditionalScatterPlotView.h @@ -48,7 +48,7 @@ class ConditionalScatterPlotCanvas : public ConditionalNewCanvas { virtual ~ConditionalScatterPlotCanvas(); virtual void DisplayRightClickMenu(const wxPoint& pos); virtual wxString GetCanvasTitle(); - + virtual wxString GetVariableNames(); virtual void SetCheckMarks(wxMenu* menu); virtual void ResizeSelectableShps(int virtual_scrn_w = 0, @@ -75,6 +75,8 @@ class ConditionalScatterPlotCanvas : public ConditionalNewCanvas { /// Override from TemplateCanvas virtual void SetSelectableOutlineColor(wxColour color); + virtual void UpdateStatusBar(); + protected: bool full_map_redraw_needed; std::vector X; @@ -102,7 +104,6 @@ class ConditionalScatterPlotCanvas : public ConditionalNewCanvas { void EmptyLowessCache(); Lowess lowess; - virtual void UpdateStatusBar(); DECLARE_EVENT_TABLE() }; @@ -133,7 +134,9 @@ class ConditionalScatterPlotFrame : public ConditionalNewFrame, /** Implementation of LowessParamObserver interface */ virtual void update(LowessParamObservable* o); virtual void notifyOfClosing(LowessParamObservable* o); - + + virtual void OnSaveCanvasImageAs(wxCommandEvent& event); + void OnViewLinearSmoother(wxCommandEvent& event); void OnViewLowessSmoother(wxCommandEvent& event); void OnEditLowessParams(wxCommandEvent& event); diff --git a/Explore/ConnectivityHistView.cpp b/Explore/ConnectivityHistView.cpp index 92e9bc2e0..a5f133063 100644 --- a/Explore/ConnectivityHistView.cpp +++ b/Explore/ConnectivityHistView.cpp @@ -41,7 +41,7 @@ #include "../logger.h" #include "../GeoDa.h" #include "../Project.h" -#include "../ShapeOperations/ShapeUtils.h" + #include "../ShapeOperations/WeightsManState.h" #include "ConnectivityHistView.h" @@ -279,6 +279,13 @@ wxString ConnectivityHistCanvas::GetCanvasTitle() return s; } +wxString ConnectivityHistCanvas::GetVariableNames() +{ + wxString s; + s << w_man_int->GetLongDispName(w_uuid); + return s; +} + void ConnectivityHistCanvas::PopulateCanvas() { BOOST_FOREACH( GdaShape* shp, background_shps ) { delete shp; } @@ -368,11 +375,11 @@ void ConnectivityHistCanvas::PopulateCanvas() int cols = 1; int rows = 5; std::vector vals(rows); - vals[0] << "from"; - vals[1] << "to"; - vals[2] << "#obs"; - vals[3] << "% of total"; - vals[4] << "sd from mean"; + vals[0] << _("from"); + vals[1] << _("to"); + vals[2] << _("#obs"); + vals[3] << _("% of total"); + vals[4] << _("sd from mean"); std::vector attribs(0); // undefined s = new GdaShapeTable(vals, attribs, rows, cols, *GdaConst::small_font, wxRealPoint(0, 0), GdaShapeText::h_center, @@ -380,10 +387,15 @@ void ConnectivityHistCanvas::PopulateCanvas() GdaShapeText::right, GdaShapeText::v_center, 3, 10, -62, 53+y_d); foreground_shps.push_back(s); - { - wxClientDC dc(this); - ((GdaShapeTable*) s)->GetSize(dc, table_w, table_h); - } + + wxClientDC dc(this); + ((GdaShapeTable*) s)->GetSize(dc, table_w, table_h); + + // get row gap in multi-language case + wxSize sz_0 = dc.GetTextExtent(vals[0]); + wxSize sz_1 = dc.GetTextExtent("0.0"); + int row_gap = 3 + sz_0.GetHeight() - sz_1.GetHeight(); + for (int i=0; i vals(rows); double ival_min = (i == 0) ? min_ival_val : ival_breaks[i-1]; @@ -398,8 +410,8 @@ void ConnectivityHistCanvas::PopulateCanvas() } else if (ival_min > mean && sd > 0) { sd_d = (ival_min - mean)/sd; } - vals[0] << GenUtils::DblToStr(ival_min, 3); - vals[1] << GenUtils::DblToStr(ival_max, 3); + vals[0] << GenUtils::DblToStr(ival_min, 0); + vals[1] << GenUtils::DblToStr(ival_max, 0); vals[2] << ival_obs_cnt[i]; vals[3] << GenUtils::DblToStr(p, 3); vals[4] << GenUtils::DblToStr(sd_d, 3); @@ -410,18 +422,18 @@ void ConnectivityHistCanvas::PopulateCanvas() wxRealPoint(orig_x_pos[i], 0), GdaShapeText::h_center, GdaShapeText::top, GdaShapeText::h_center, GdaShapeText::v_center, - 3, 10, 0, + row_gap, 10, 0, 53+y_d); foreground_shps.push_back(s); } - wxString sts; - sts << "min: " << data_stats.min; - sts << ", max: " << data_stats.max; - sts << ", median: " << hinge_stats.Q2; - sts << ", mean: " << data_stats.mean; - sts << ", s.d.: " << data_stats.sd_with_bessel; - sts << ", #obs: " << num_obs; + wxString sts; + sts << _("min:") << " " << data_stats.min; + sts << ", " << _("max:") << " " << data_stats.max; + sts << ", " << _("median:") << " " << hinge_stats.Q2; + sts << ", " << _("mean:") << " " << data_stats.mean; + sts << ", " << _("s.d.:") << " " << data_stats.sd_with_bessel; + sts << ", " << _("#obs:") << " " << num_obs; s = new GdaShapeText(sts, *GdaConst::small_font, wxRealPoint(x_max/2.0, 0), 0, @@ -558,12 +570,12 @@ void ConnectivityHistCanvas::InitData() range = 1; default_intervals = 1; } else { - default_intervals = GenUtils::min(MAX_INTERVALS, range+1); + default_intervals = std::min(MAX_INTERVALS, range+1); } obs_id_to_ival.resize(num_obs); - max_intervals = GenUtils::min(MAX_INTERVALS, num_obs); - cur_intervals = GenUtils::min(max_intervals, default_intervals); + max_intervals = std::min(MAX_INTERVALS, num_obs); + cur_intervals = std::min(max_intervals, default_intervals); } /** based on cur_intervals, calculate interval breaks and populate @@ -748,7 +760,7 @@ void ConnectivityHistFrame::MapMenus() wxMenu* optMenu = wxXmlResource::Get()-> LoadMenu("ID_CONNECTIVITY_HIST_VIEW_MENU_OPTIONS"); ((ConnectivityHistCanvas*) template_canvas)->SetCheckMarks(optMenu); - GeneralWxUtils::ReplaceMenu(mb, "Options", optMenu); + GeneralWxUtils::ReplaceMenu(mb, _("Options"), optMenu); UpdateOptionMenuItems(); } @@ -756,7 +768,7 @@ void ConnectivityHistFrame::UpdateOptionMenuItems() { TemplateFrame::UpdateOptionMenuItems(); // set common items first wxMenuBar* mb = GdaFrame::GetGdaFrame()->GetMenuBar(); - int menu = mb->FindMenu("Options"); + int menu = mb->FindMenu(_("Options")); if (menu == wxNOT_FOUND) { } else { ((ConnectivityHistCanvas*) template_canvas)-> diff --git a/Explore/ConnectivityHistView.h b/Explore/ConnectivityHistView.h index ea14ff11c..5e1a156b5 100644 --- a/Explore/ConnectivityHistView.h +++ b/Explore/ConnectivityHistView.h @@ -45,6 +45,7 @@ class ConnectivityHistCanvas : public TemplateCanvas { virtual void DisplayRightClickMenu(const wxPoint& pos); virtual void update(HLStateInt* o); virtual wxString GetCanvasTitle(); + virtual wxString GetVariableNames(); virtual void SetCheckMarks(wxMenu* menu); virtual void DetermineMouseHoverObjects(wxPoint pt); virtual void UpdateSelection(bool shiftdown = false, @@ -52,10 +53,8 @@ class ConnectivityHistCanvas : public TemplateCanvas { virtual void DrawSelectableShapes(wxMemoryDC &dc); virtual void DrawHighlightedShapes(wxMemoryDC &dc); -protected: virtual void PopulateCanvas(); -public: void ChangeWeights(boost::uuids::uuid new_id); void DisplayStatistics(bool display_stats); @@ -71,8 +70,9 @@ class ConnectivityHistCanvas : public TemplateCanvas { void InitData(); void InitIntervals(); void UpdateIvalSelCnts(); -protected: virtual void UpdateStatusBar(); + +protected: int num_obs; bool has_isolates; diff --git a/Explore/ConnectivityMapView.cpp b/Explore/ConnectivityMapView.cpp index 431defe02..5c3986ef5 100644 --- a/Explore/ConnectivityMapView.cpp +++ b/Explore/ConnectivityMapView.cpp @@ -95,103 +95,149 @@ ConnectivityMapCanvas::~ConnectivityMapCanvas() void ConnectivityMapCanvas::OnMouseEvent(wxMouseEvent& event) { - // Capture the mouse when left mouse button is down. - if (event.LeftIsDown() && !HasCapture()) CaptureMouse(); - if (event.LeftUp() && HasCapture()) ReleaseMouse(); - - if (mousemode == select) { - if (selectstate == start) { - if (event.LeftDown()) { - prev = GetActualPos(event); - sel1 = prev; - selectstate = leftdown; - } else if (event.RightDown()) { - DisplayRightClickMenu(event.GetPosition()); - } else { - if (template_frame && template_frame->IsStatusBarVisible()) { - prev = GetActualPos(event); - sel1 = prev; // sel1 now has current mouse position - - // The following two lines will make this operate in - // continuous selection mode - UpdateSelectRegion(); - UpdateSelection(event.ShiftDown(), true); - - selectstate = start; - DetermineMouseHoverObjects(prev); - UpdateStatusBar(); - } - } - } else if (selectstate == leftdown) { - if (event.Moving() || event.Dragging()) { - wxPoint act_pos = GetActualPos(event); - if (fabs((double) (prev.x - act_pos.x)) + - fabs((double) (prev.y - act_pos.y)) > 2) { - sel1 = prev; - sel2 = GetActualPos(event); - selectstate = dragging; - remember_shiftdown = event.ShiftDown(); - UpdateSelectRegion(); - UpdateSelection(remember_shiftdown); - UpdateStatusBar(); - Refresh(); - } - } else if (event.LeftUp()) { - UpdateSelectRegion(); - UpdateSelection(event.ShiftDown(), true); - selectstate = start; - Refresh(); - } else if (event.RightDown()) { - selectstate = start; - } - } else if (selectstate == dragging) { - if (event.Dragging()) { // mouse moved while buttons still down - sel2 = GetActualPos(event); - UpdateSelectRegion(); - UpdateSelection(remember_shiftdown); - UpdateStatusBar(); - Refresh(); - } else if (event.LeftUp() && !event.CmdDown()) { - sel2 = GetActualPos(event); - UpdateSelectRegion(); - UpdateSelection(remember_shiftdown); - remember_shiftdown = false; - selectstate = start; - Refresh(); - } else if (event.LeftUp() && event.CmdDown()) { - selectstate = brushing; - sel2 = GetActualPos(event); - wxPoint diff = wxPoint(0,0); - UpdateSelectRegion(false, diff); - UpdateSelection(remember_shiftdown); - remember_shiftdown = false; - Refresh(); - } else if (event.RightDown()) { - DisplayRightClickMenu(event.GetPosition()); - } - } else if (selectstate == brushing) { - if (event.LeftIsDown()) { - } else if (event.LeftUp()) { - selectstate = start; - Refresh(); - } - else if (event.RightDown()) { - selectstate = start; - Refresh(); - } else if (event.Moving()) { - wxPoint diff = GetActualPos(event) - sel2; - sel1 += diff; - sel2 = GetActualPos(event); - UpdateStatusBar(); - UpdateSelectRegion(true, diff); - UpdateSelection(); - Refresh(); - } - } else { // unknown state - } - } else { - TemplateCanvas::OnMouseEvent(event); - } + // Capture the mouse when left mouse button is down. + if (event.LeftIsDown() && !HasCapture()) + CaptureMouse(); + + if (event.LeftUp() && HasCapture()) + ReleaseMouse(); + + if (mousemode == select) { + is_showing_brush = true; + if (selectstate == start) { + if (event.LeftDown()) { + prev = GetActualPos(event); + + if (sel1.x > 0 && sel1.y > 0 && sel2.x > 0 && sel2.y >0) { + // already has selection then + // detect if click inside brush_shape + GdaShape* brush_shape = NULL; + if (brushtype == rectangle) { + brush_shape = new GdaRectangle(sel1, sel2); + } else if (brushtype == circle) { + brush_shape = new GdaCircle(sel1, sel2); + } else if (brushtype == line) { + brush_shape = new GdaPolyLine(sel1, sel2); + } + if (brush_shape->Contains(prev)) { + // brushing + is_brushing = true; + remember_shiftdown = false; // brush will cancel shift + selectstate = brushing; + } else { + // cancel brushing since click outside, restore leftdown + ResetBrushing(); + sel1 = prev; + selectstate = leftdown; + } + delete brush_shape; + + } else { + sel1 = prev; + selectstate = leftdown; + } + + } else if (event.RightDown()) { + ResetBrushing(); + DisplayRightClickMenu(event.GetPosition()); + + } else { + // hover + if (template_frame && template_frame->IsStatusBarVisible()) { + prev = GetActualPos(event); + + DetermineMouseHoverObjects(prev); + UpdateStatusBar(); + + if (sel1.x > 0 && sel1.y > 0 && sel2.x > 0 && sel2.y >0) { + // already has selection then + return; + } + std::vector& hs = shared_core_hs->GetHighlight(); + for (size_t i=0, sz=hs.size(); iSetEventType(HLStateInt::unhighlight_all); + } else { + hs[ hover_obs[0] ] = true; + shared_core_hs->SetEventType(HLStateInt::delta); + } + shared_core_hs->notifyObservers(); + } + } + + } else if (selectstate == leftdown) { + if (event.Moving() || event.Dragging()) { + wxPoint act_pos = GetActualPos(event); + if (fabs((double) (sel1.x - act_pos.x)) + + fabs((double) (sel1.y - act_pos.y)) > 2) { + sel2 = GetActualPos(event); + selectstate = dragging; + remember_shiftdown = event.ShiftDown(); + UpdateSelection(remember_shiftdown); + //UpdateStatusBar(); + //Refresh(false); + } + } else if (event.LeftUp()) { + wxPoint act_pos = GetActualPos(event); + if (act_pos == sel1 ) { + sel2 = sel1; + } + UpdateSelection(event.ShiftDown(), true); + selectstate = start; + ResetBrushing(); + + } else if (event.RightDown()) { + selectstate = start; + } + + } else if (selectstate == dragging) { + if (event.Dragging()) { // mouse moved while buttons still down + sel2 = GetActualPos(event); + + UpdateSelection(remember_shiftdown); + //UpdateStatusBar(); + //Refresh(false); + + } else if (event.LeftUp()) { + sel2 = GetActualPos(event); + + UpdateSelection(remember_shiftdown); + remember_shiftdown = false; + selectstate = start; + //Refresh(false); + + } else if (event.RightDown()) { + DisplayRightClickMenu(event.GetPosition()); + } + + } else if (selectstate == brushing) { + if (event.LeftUp()) { + is_brushing = false; // will check again if brushing when mouse down again + selectstate = start; + + } else if (event.RightDown()) { + is_brushing = false; + selectstate = start; + Refresh(); + + } else if (is_brushing && (event.Moving() || event.Dragging())) { + wxPoint cur = GetActualPos(event); + wxPoint diff = cur - prev; + sel1 += diff; + sel2 += diff; + //UpdateStatusBar(); + + UpdateSelection(); + //Refresh(false); // keep painting the select rect + prev = cur; + } + } + + } else{ + TemplateCanvas::OnMouseEvent(event); + } } // The following function assumes that the set of selectable objects @@ -282,6 +328,10 @@ void ConnectivityMapCanvas::UpdateSelection(bool shiftdown, bool pointsel) shared_core_hs->SetEventType(HLStateInt::delta); shared_core_hs->notifyObservers(); } + + //UpdateFromSharedCore(); + + UpdateStatusBar(); } void ConnectivityMapCanvas::UpdateFromSharedCore() @@ -289,7 +339,8 @@ void ConnectivityMapCanvas::UpdateFromSharedCore() sel_cores.clear(); std::vector& sc_hs = shared_core_hs->GetHighlight(); for (int i=0, sz=sc_hs.size(); i& hs = highlight_state->GetHighlight(); @@ -320,9 +371,9 @@ void ConnectivityMapCanvas::UpdateFromSharedCore() } /** Don't draw selection outline */ -//void ConnectivityMapCanvas::PaintSelectionOutline(wxDC& dc) -//{ -//} +void ConnectivityMapCanvas::PaintSelectionOutline(wxMemoryDC& dc) +{ +} void ConnectivityMapCanvas::DisplayRightClickMenu(const wxPoint& pos) { @@ -348,10 +399,17 @@ void ConnectivityMapCanvas::DisplayRightClickMenu(const wxPoint& pos) wxString ConnectivityMapCanvas::GetCanvasTitle() { wxString s; - s << "Connectivity Map - " << w_man_int->GetLongDispName(weights_id); + s << _("Connectivity Map - ") << w_man_int->GetLongDispName(weights_id); return s; } +wxString ConnectivityMapCanvas::GetVariableNames() +{ + wxString s; + s << w_man_int->GetLongDispName(weights_id); + return s; +} + /** This method definition is empty. It is here to override any call to the parent-class method since smoothing and theme changes are not supported by connectivity maps */ @@ -420,7 +478,26 @@ void ConnectivityMapCanvas::update(HLStateInt* o) { if (o == proj_hs) { } else if (o == highlight_state) { - TemplateCanvas::update(o); + //TemplateCanvas::update(o); + if (layer2_bm) { + if (draw_sel_shps_by_z_val) { + // force a full redraw + layer0_valid = false; + return; + } + + HLStateInt::EventType type = o->GetEventType(); + if (type == HLStateInt::transparency) { + ResetFadedLayer(); + } + // re-paint highlight layer (layer1_bm) + layer1_valid = false; + DrawLayers(); + Refresh(); + + UpdateStatusBar(); + //ResetBrushing(); + } } else { // o == shared_core_hs UpdateFromSharedCore(); } @@ -438,7 +515,7 @@ void ConnectivityMapCanvas::UpdateStatusBar() if (mousemode == select) { if (sel_cores.size() == 1) { long cid = *sel_cores.begin(); - s << "obs " << w_man_int->RecNumToId(GetWeightsId(), cid); + s << _("obs ") << w_man_int->RecNumToId(GetWeightsId(), cid); s << " has " << core_nbrs.size() << " neighbor"; if (core_nbrs.size() != 1) s << "s"; if (core_nbrs.size() > 0) { @@ -493,10 +570,10 @@ ConnectivityMapFrame::ConnectivityMapFrame(wxFrame *parent, Project* project, wxPanel* toolbar_panel = new wxPanel(this,-1, wxDefaultPosition); wxBoxSizer* toolbar_sizer= new wxBoxSizer(wxVERTICAL); - wxToolBar* tb = wxXmlResource::Get()->LoadToolBar(toolbar_panel, "ToolBar_MAP"); - tb->EnableTool(XRCID("ID_SELECT_INVERT"), false); + toolbar = wxXmlResource::Get()->LoadToolBar(toolbar_panel, "ToolBar_MAP"); + toolbar->EnableTool(XRCID("ID_SELECT_INVERT"), false); SetupToolbar(); - toolbar_sizer->Add(tb, 0, wxEXPAND|wxALL); + toolbar_sizer->Add(toolbar, 0, wxEXPAND|wxALL); toolbar_panel->SetSizerAndFit(toolbar_sizer); @@ -536,7 +613,7 @@ void ConnectivityMapFrame::MapMenus() ((MapCanvas*) template_canvas)-> AddTimeVariantOptionsToMenu(optMenu); ((MapCanvas*) template_canvas)->SetCheckMarks(optMenu); - GeneralWxUtils::ReplaceMenu(mb, "Options", optMenu); + GeneralWxUtils::ReplaceMenu(mb, _("Options"), optMenu); UpdateOptionMenuItems(); } @@ -544,7 +621,7 @@ void ConnectivityMapFrame::UpdateOptionMenuItems() { TemplateFrame::UpdateOptionMenuItems(); // set common items first wxMenuBar* mb = GdaFrame::GetGdaFrame()->GetMenuBar(); - int menu = mb->FindMenu("Options"); + int menu = mb->FindMenu(_("Options")); if (menu == wxNOT_FOUND) { } else { ((ConnectivityMapCanvas*) template_canvas)-> diff --git a/Explore/ConnectivityMapView.h b/Explore/ConnectivityMapView.h index cdbc349e1..92bcdfd31 100644 --- a/Explore/ConnectivityMapView.h +++ b/Explore/ConnectivityMapView.h @@ -42,10 +42,11 @@ class ConnectivityMapCanvas : public MapCanvas virtual void UpdateSelection(bool shiftdown = false, bool pointsel = false); void UpdateFromSharedCore(); - //virtual void PaintSelectionOutline(wxDC& dc); + virtual void PaintSelectionOutline(wxMemoryDC& dc); virtual void DisplayRightClickMenu(const wxPoint& pos); virtual wxString GetCanvasTitle(); + virtual wxString GetVariableNames(); virtual bool ChangeMapType(CatClassification::CatClassifType new_map_theme, SmoothingType new_map_smoothing); virtual void SetCheckMarks(wxMenu* menu); @@ -54,6 +55,8 @@ class ConnectivityMapCanvas : public MapCanvas void ChangeWeights(boost::uuids::uuid new_id); virtual void update(HLStateInt* o); + virtual void UpdateStatusBar(); + protected: WeightsManInterface* w_man_int; @@ -64,7 +67,6 @@ class ConnectivityMapCanvas : public MapCanvas std::set sel_cores; // set of cores under current selection std::set core_nbrs; // set of nbrs of cores, excl cores - virtual void UpdateStatusBar(); DECLARE_EVENT_TABLE() }; diff --git a/Explore/CorrelParamsDlg.cpp b/Explore/CorrelParamsDlg.cpp index 0daa89f40..48db3f221 100644 --- a/Explore/CorrelParamsDlg.cpp +++ b/Explore/CorrelParamsDlg.cpp @@ -18,6 +18,7 @@ */ #include +#include #include #include #include @@ -27,13 +28,14 @@ #include "../logger.h" #include "../Project.h" #include "../DialogTools/WebViewHelpWin.h" +#include "../ShapeOperations/OGRDataAdapter.h" #include "../rc/GeoDaIcon-16x16.xpm" #include "CorrelParamsDlg.h" CorrelParamsFrame::CorrelParamsFrame(const CorrelParams& correl_params, GdaVarTools::Manager& var_man, Project* project_) -: wxFrame((wxWindow*) 0, wxID_ANY, "Correlogram Parameters", +: wxFrame((wxWindow*) 0, wxID_ANY, _("Correlogram Parameters"), wxDefaultPosition, wxDefaultSize, wxDEFAULT_FRAME_STYLE), CorrelParamsObservable(correl_params, var_man), project(project_), var_txt(0), var_choice(0), dist_txt(0), dist_choice(0), bins_txt(0), @@ -42,19 +44,43 @@ all_pairs_rad(0), est_pairs_txt(0), est_pairs_num_txt(0), rand_samp_rad(0), max_iter_txt(0), max_iter_tctrl(0), help_btn(0), apply_btn(0) { - LOG_MSG("Entering CorrelParamsFrame::CorrelParamsFrame"); + wxLogMessage("Entering CorrelParamsFrame::CorrelParamsFrame"); wxPanel* panel = new wxPanel(this); panel->SetBackgroundColour(*wxWHITE); SetBackgroundColour(*wxWHITE); { - var_txt = new wxStaticText(panel, XRCID("ID_VAR_TXT"), "Variable:"); + var_txt = new wxStaticText(panel, XRCID("ID_VAR_TXT"), _("Variable:")); var_choice = new wxChoice(panel, XRCID("ID_VAR_CHOICE"), - wxDefaultPosition,wxSize(160,-1)); + wxDefaultPosition,wxSize(80,-1)); wxString var_nm = ""; if (var_man.GetVarsCount() > 0) var_nm = var_man.GetName(0); - UpdateVarChoiceFromTable(var_nm); + + var_time_txt = new wxStaticText(panel, XRCID("ID_VAR_TIME_TXT"), _("Time:")); + var_time_choice = new wxChoice(panel, XRCID("ID_VAR_TIME_CHOICE"), + wxDefaultPosition,wxSize(80,-1)); + + Connect(XRCID("ID_VAR_TIME_CHOICE"), wxEVT_CHOICE, + wxCommandEventHandler(CorrelParamsFrame::OnTime1)); + + is_time = project->GetTableInt()->IsTimeVariant(); + time_steps = project->GetTableInt()->GetTimeSteps(); + for (int i=0; iGetTableInt()->GetTimeString(i); + var_time_choice->Append(s); + } + if (is_time == false) { + v1_time = 0; + var_time_txt->Hide(); + var_time_choice->Hide(); + } else { + v1_time = 0; + var_time_choice->SetSelection(v1_time); + } + + UpdateVarChoiceFromTable(var_nm); Connect(XRCID("ID_VAR_CHOICE"), wxEVT_CHOICE, wxCommandEventHandler(CorrelParamsFrame::OnVarChoiceSelected)); } @@ -62,8 +88,12 @@ help_btn(0), apply_btn(0) var_h_szr->Add(var_txt, 0, wxALIGN_CENTER_VERTICAL); var_h_szr->AddSpacer(5); var_h_szr->Add(var_choice, 0, wxALIGN_CENTER_VERTICAL); + var_h_szr->AddSpacer(5); + var_h_szr->Add(var_time_txt, 0, wxALIGN_CENTER_VERTICAL); + var_h_szr->AddSpacer(5); + var_h_szr->Add(var_time_choice, 0, wxALIGN_CENTER_VERTICAL); - dist_txt = new wxStaticText(panel, XRCID("ID_DIST_TXT"), "Distance:"); + dist_txt = new wxStaticText(panel, XRCID("ID_DIST_TXT"), _("Distance:")); dist_choice = new wxChoice(panel, XRCID("ID_DIST_CHOICE"), wxDefaultPosition, wxSize(160,-1)); dist_choice->Append("Euclidean Distance"); @@ -88,7 +118,7 @@ help_btn(0), apply_btn(0) dist_h_szr->Add(dist_choice, 0, wxALIGN_CENTER_VERTICAL); { - bins_txt = new wxStaticText(panel, XRCID("ID_BINS_TXT"), "Number Bins:"); + bins_txt = new wxStaticText(panel, XRCID("ID_BINS_TXT"), _("Number Bins:")); wxString vs; vs << correl_params.bins; bins_spn_ctrl = new wxSpinCtrl(panel, XRCID("ID_BINS_SPN_CTRL"), @@ -97,6 +127,7 @@ help_btn(0), apply_btn(0) CorrelParams::min_bins_cnst, CorrelParams::max_bins_cnst, correl_params.bins); + num_bins = correl_params.bins; Connect(XRCID("ID_BINS_SPN_CTRL"), wxEVT_SPINCTRL, wxSpinEventHandler(CorrelParamsFrame::OnBinsSpinEvent)); Connect(XRCID("ID_BINS_SPN_CTRL"), wxEVT_TEXT_ENTER, @@ -107,7 +138,7 @@ help_btn(0), apply_btn(0) bins_h_szr->AddSpacer(5); bins_h_szr->Add(bins_spn_ctrl, 0, wxALIGN_CENTER_VERTICAL); - thresh_cbx = new wxCheckBox(panel, XRCID("ID_THRESH_CBX"), "Max Distance:"); + thresh_cbx = new wxCheckBox(panel, XRCID("ID_THRESH_CBX"), _("Max Distance:")); thresh_cbx->SetValue(false); thresh_tctrl = new wxTextCtrl(panel, XRCID("ID_THRESH_TCTRL"), "", wxDefaultPosition, wxSize(100,-1), @@ -139,14 +170,14 @@ help_btn(0), apply_btn(0) thresh_v_szr->Add(thresh_sld_h_szr, 0, wxALIGN_CENTER_HORIZONTAL); all_pairs_rad = new wxRadioButton(panel, XRCID("ID_ALL_PAIRS_RAD"), - "All Pairs", wxDefaultPosition, + _("All Pairs"), wxDefaultPosition, wxDefaultSize, wxALIGN_CENTER_VERTICAL | wxRB_GROUP); all_pairs_rad->SetValue(correl_params.method == CorrelParams::ALL_PAIRS); Connect(XRCID("ID_ALL_PAIRS_RAD"), wxEVT_RADIOBUTTON, wxCommandEventHandler(CorrelParamsFrame::OnAllPairsRadioSelected)); - est_pairs_txt = new wxStaticText(panel, XRCID("ID_EST_PAIRS_TXT"), "Estimated Pairs:"); + est_pairs_txt = new wxStaticText(panel, XRCID("ID_EST_PAIRS_TXT"), _("Estimated Pairs:")); est_pairs_num_txt = new wxStaticText(panel, XRCID("ID_EST_PAIRS_NUM_TXT"), "4,000,000"); wxBoxSizer* est_pairs_h_szr = new wxBoxSizer(wxHORIZONTAL); est_pairs_h_szr->Add(est_pairs_txt, 0, wxALIGN_CENTER_VERTICAL); @@ -157,10 +188,10 @@ help_btn(0), apply_btn(0) all_pairs_v_szr->AddSpacer(2); all_pairs_v_szr->Add(est_pairs_h_szr, 0, wxLEFT, 18); - rand_samp_rad = new wxRadioButton(panel, XRCID("ID_RAND_SAMP_RAD"), "Random Sample", wxDefaultPosition, wxDefaultSize, wxALIGN_CENTER_VERTICAL); + rand_samp_rad = new wxRadioButton(panel, XRCID("ID_RAND_SAMP_RAD"), _("Random Sample"), wxDefaultPosition, wxDefaultSize, wxALIGN_CENTER_VERTICAL); rand_samp_rad->SetValue(correl_params.method != CorrelParams::ALL_PAIRS); Connect(XRCID("ID_RAND_SAMP_RAD"), wxEVT_RADIOBUTTON, wxCommandEventHandler(CorrelParamsFrame::OnRandSampRadioSelected)); - max_iter_txt = new wxStaticText(panel, XRCID("ID_MAX_ITER_TXT"), "Sample Size:"); + max_iter_txt = new wxStaticText(panel, XRCID("ID_MAX_ITER_TXT"), _("Sample Size:")); { wxString vs; vs << correl_params.max_iterations; @@ -175,14 +206,34 @@ help_btn(0), apply_btn(0) max_iter_h_szr->Add(max_iter_txt, 0, wxALIGN_CENTER_VERTICAL); max_iter_h_szr->AddSpacer(8); max_iter_h_szr->Add(max_iter_tctrl, 0, wxALIGN_CENTER_VERTICAL); + + wxBoxSizer* random_opt_h_szr = new wxBoxSizer(wxHORIZONTAL); + { + wxStaticText* st17 = new wxStaticText(panel, wxID_ANY, _("Use specified seed:"), + wxDefaultPosition, wxSize(128,-1)); + wxBoxSizer *hbox17 = new wxBoxSizer(wxHORIZONTAL); + chk_seed = new wxCheckBox(panel, wxID_ANY, ""); + seedButton = new wxButton(panel, wxID_OK, _("Change"), wxDefaultPosition, wxSize(64, -1)); + random_opt_h_szr->Add(st17, 0, wxALIGN_CENTER_VERTICAL); + random_opt_h_szr->Add(chk_seed,0, wxALIGN_CENTER_VERTICAL); + random_opt_h_szr->Add(seedButton, 0, wxALIGN_CENTER_VERTICAL); + if (GdaConst::use_gda_user_seed) { + chk_seed->SetValue(true); + seedButton->Enable(); + } + chk_seed->Bind(wxEVT_CHECKBOX, &CorrelParamsFrame::OnSeedCheck, this); + seedButton->Bind(wxEVT_BUTTON, &CorrelParamsFrame::OnChangeSeed, this); + } + wxBoxSizer* rand_samp_v_szr = new wxBoxSizer(wxVERTICAL); rand_samp_v_szr->Add(rand_samp_rad); rand_samp_v_szr->AddSpacer(2); - rand_samp_v_szr->Add(max_iter_h_szr, 0, wxLEFT, 18); + rand_samp_v_szr->Add(max_iter_h_szr, 0, wxLEFT, 12); + rand_samp_v_szr->Add(random_opt_h_szr, 0, wxLEFT, 12); - help_btn = new wxButton(panel, XRCID("ID_HELP_BTN"), "Help", + help_btn = new wxButton(panel, XRCID("ID_HELP_BTN"), _("Help"), wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT); - apply_btn = new wxButton(panel, XRCID("ID_APPLY_BTN"), "Apply", + apply_btn = new wxButton(panel, XRCID("ID_APPLY_BTN"), _("Apply"), wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT); Connect(XRCID("ID_HELP_BTN"), wxEVT_BUTTON, @@ -234,21 +285,80 @@ help_btn(0), apply_btn(0) SetIcon(wxIcon(GeoDaIcon_16x16_xpm)); Show(true); - LOG_MSG("Exiting CorrelParamsFrame::CorrelParamsFrame"); + var_choice->SetFocus(); + wxLogMessage("Exiting CorrelParamsFrame::CorrelParamsFrame"); } CorrelParamsFrame::~CorrelParamsFrame() { - LOG_MSG("In CorrelParamsFrame::~CorrelParamsFrame"); + wxLogMessage("In CorrelParamsFrame::~CorrelParamsFrame"); notifyObserversOfClosing(); } +void CorrelParamsFrame::OnSeedCheck(wxCommandEvent& event) +{ + bool use_user_seed = chk_seed->GetValue(); + + if (use_user_seed) { + seedButton->Enable(); + if (GdaConst::use_gda_user_seed == false && GdaConst::gda_user_seed == 0) { + OnChangeSeed(event); + return; + } + GdaConst::use_gda_user_seed = true; + + OGRDataAdapter& ogr_adapt = OGRDataAdapter::GetInstance(); + ogr_adapt.AddEntry("use_gda_user_seed", "1"); + } else { + GdaConst::use_gda_user_seed = false; + seedButton->Disable(); + } +} + +void CorrelParamsFrame::OnChangeSeed(wxCommandEvent& event) +{ + // prompt user to enter user seed (used globally) + wxString m; + m << _("Enter a seed value for random number generator:"); + + long long unsigned int val; + wxString dlg_val; + wxString cur_val; + cur_val << GdaConst::gda_user_seed; + + wxTextEntryDialog dlg(NULL, m, _("Enter a seed value"), cur_val); + if (dlg.ShowModal() != wxID_OK) return; + dlg_val = dlg.GetValue(); + dlg_val.Trim(true); + dlg_val.Trim(false); + if (dlg_val.IsEmpty()) return; + if (dlg_val.ToULongLong(&val)) { + uint64_t new_seed_val = val; + GdaConst::gda_user_seed = new_seed_val; + GdaConst::use_gda_user_seed = true; + + OGRDataAdapter& ogr_adapt = OGRDataAdapter::GetInstance(); + wxString str_gda_user_seed; + str_gda_user_seed << GdaConst::gda_user_seed; + ogr_adapt.AddEntry("gda_user_seed", str_gda_user_seed.ToStdString()); + ogr_adapt.AddEntry("use_gda_user_seed", "1"); + } else { + wxString m = _("\"%s\" is not a valid seed. Seed unchanged."); + m = wxString::Format(m, dlg_val); + wxMessageDialog dlg(NULL, m, _("Error"), wxOK | wxICON_ERROR); + dlg.ShowModal(); + GdaConst::use_gda_user_seed = false; + OGRDataAdapter& ogr_adapt = OGRDataAdapter::GetInstance(); + ogr_adapt.AddEntry("use_gda_user_seed", "0"); + } +} + void CorrelParamsFrame::OnHelpBtn(wxCommandEvent& ev) { - LOG_MSG("In CorrelParamsFrame::OnHelpBtn"); + wxLogMessage("In CorrelParamsFrame::OnHelpBtn"); WebViewHelpWin* win = new WebViewHelpWin(project, GetHelpPageHtml(), NULL, wxID_ANY, - "Correlogram Parameters Help", + _("Correlogram Parameters Help"), wxDefaultPosition, wxSize(500,500)); } @@ -259,7 +369,7 @@ void CorrelParamsFrame::OnApplyBtn(wxCommandEvent& ev) if (vc_sel < 0) return; - LOG_MSG("In CorrelParamsFrame::OnApplyBtn"); + wxLogMessage("In CorrelParamsFrame::OnApplyBtn"); { long new_bins = bins_spn_ctrl->GetValue(); if (new_bins < CorrelParams::min_bins_cnst) { @@ -269,6 +379,7 @@ void CorrelParamsFrame::OnApplyBtn(wxCommandEvent& ev) new_bins = CorrelParams::max_bins_cnst; } correl_params.bins = new_bins; + num_bins = new_bins; } { wxString s = dist_choice->GetStringSelection(); @@ -336,6 +447,7 @@ void CorrelParamsFrame::OnApplyBtn(wxCommandEvent& ev) { // update var_man with new selection wxString var_nm = var_choice->GetString(vc_sel); + var_nm = name_to_nm[var_nm]; TableInterface* table_int = project->GetTableInt(); int col_id = table_int->FindColId(var_nm); wxString var_man_nm0 = var_man.GetName(0); @@ -346,7 +458,6 @@ void CorrelParamsFrame::OnApplyBtn(wxCommandEvent& ev) var_man.RemoveVar(0); } if (var_man.GetVarsCount() == 0) { - int time = project->GetTimeState()->GetCurrTime(); std::vector min_vals; std::vector max_vals; table_int->GetMinMaxVals(col_id, min_vals, max_vals); @@ -356,15 +467,16 @@ void CorrelParamsFrame::OnApplyBtn(wxCommandEvent& ev) break; } } - var_man.AppendVar(var_nm, min_vals, max_vals, time); + var_man.AppendVar(var_nm, min_vals, max_vals, v1_time); } - + + var_man.SetCurTime(0,v1_time); double mean = 0; double var = 0; vector vals; vector vals_undef; - table_int->GetColData(col_id, 0, vals); - table_int->GetColUndefined(col_id, 0, vals_undef); + table_int->GetColData(col_id, v1_time, vals); + table_int->GetColUndefined(col_id, v1_time, vals_undef); CorrelogramAlgs::GetSampMeanAndVar(vals, vals_undef, mean, var); if (var <= 0) { wxString msg = "Please check your variable, e.g. make sure it is not a constant."; @@ -426,7 +538,11 @@ void CorrelParamsFrame::OnBinsTextCtrl(wxCommandEvent& ev) void CorrelParamsFrame::OnBinsSpinEvent(wxSpinEvent& ev) { - OnApplyBtn(ev); + int val = ev.GetValue(); + if (val != num_bins) { + OnApplyBtn(ev); + } + val = num_bins; ev.Skip(); } @@ -569,10 +685,10 @@ void CorrelParamsFrame::OnMaxIterTctrlKillFocus(wxFocusEvent& ev) void CorrelParamsFrame::UpdateFromTable() { - LOG_MSG("Entering CorrelParamsFrame::UpdateFromTable"); + wxLogMessage("Entering CorrelParamsFrame::UpdateFromTable"); TableInterface* table_int = project->GetTableInt(); notifyObservers(); - LOG_MSG("Exiting CorrelParamsFrame::UpdateFromTable"); + wxLogMessage("Exiting CorrelParamsFrame::UpdateFromTable"); } void CorrelParamsFrame::closeAndDeleteWhenEmpty() @@ -616,6 +732,24 @@ double CorrelParamsFrame::GetThreshMax() return project->GetMaxDistEuc(); } +void CorrelParamsFrame::OnTime1(wxCommandEvent& event) +{ + v1_time = var_time_choice->GetSelection(); + + wxString cur_var = var_choice->GetStringSelection(); + if (name_to_nm.find(cur_var)!=name_to_nm.end()) { + cur_var = name_to_nm[cur_var]; + } + { + TableInterface* table_int = project->GetTableInt(); + if (table_int->IsColTimeVariant(cur_var) == false) { + v1_time = 0; + } + } + UpdateVarChoiceFromTable(cur_var); + OnApplyBtn(event); +} + void CorrelParamsFrame::UpdateVarChoiceFromTable(const wxString& default_var) { TableInterface* table_int = project->GetTableInt(); @@ -623,16 +757,32 @@ void CorrelParamsFrame::UpdateVarChoiceFromTable(const wxString& default_var) int var_pos = -1; var_choice->Clear(); - std::vector names; - table_int->FillNumericNameList(names); - for (size_t i=0, sz=names.size(); iAppend(names[i]); - if (names[i] == default_var) var_pos = i; - } + name_to_nm.clear(); + + int idx = -1; + std::vector col_id_map; + table_int->FillNumericColIdMap(col_id_map); + for (int i=0, iend=col_id_map.size(); iGetColName(id); + if (table_int->IsColTimeVariant(id)) { + wxString nm = name; + nm << " (" << table_int->GetTimeString(v1_time) << ")"; + name_to_nm[nm] = name; + var_choice->Append(nm); + idx++; + } else { + var_choice->Append(name); + name_to_nm[name] = name; + idx++; + } + if (name == default_var) var_pos = idx; + } + + if (var_pos >= 0) { + var_choice->SetSelection(var_pos); + } - if (var_pos >= 0) { - var_choice->SetSelection(var_pos); - } UpdateApplyState(); } diff --git a/Explore/CorrelParamsDlg.h b/Explore/CorrelParamsDlg.h index 184d4b85c..1612e98f8 100644 --- a/Explore/CorrelParamsDlg.h +++ b/Explore/CorrelParamsDlg.h @@ -20,6 +20,7 @@ #ifndef __GEODA_CENTER_CORREL_PARAMS_DLG_H__ #define __GEODA_CENTER_CORREL_PARAMS_DLG_H__ +#include #include #include #include @@ -67,7 +68,12 @@ class CorrelParamsFrame : public wxFrame, public CorrelParamsObservable void OnThreshSlider(wxCommandEvent& ev); void OnMaxIterTextCtrl(wxCommandEvent& ev); void OnMaxIterTctrlKillFocus(wxFocusEvent& ev); + + void OnSeedCheck(wxCommandEvent& ev); + void OnChangeSeed(wxCommandEvent& ev); + void OnTime1(wxCommandEvent& event); + /** Validates variable list against table. New variables are added, order is updated, and missing variables are removed. If any changes to GdaVarTools::Manager are made, a notify event is @@ -93,11 +99,20 @@ class CorrelParamsFrame : public wxFrame, public CorrelParamsObservable void UpdateThreshTctrlVal(); void UpdateEstPairs(); wxString GetHelpPageHtml() const; - + + int num_bins; + bool is_time; + int time_steps; + int v1_time; + std::map name_to_nm; + Project* project; wxStaticText* var_txt; // ID_VAR_TXT wxChoice* var_choice; // ID_VAR_CHOICE + wxStaticText* var_time_txt; // ID_VAR_TXT + wxChoice* var_time_choice; // ID_VAR_CHOICE + wxStaticText* dist_txt; // ID_DIST_TXT wxChoice* dist_choice; // ID_DIST_CHOICE wxStaticText* bins_txt; // ID_BINS_TXT @@ -113,6 +128,9 @@ class CorrelParamsFrame : public wxFrame, public CorrelParamsObservable wxTextCtrl* max_iter_tctrl; // ID_MAX_ITER_TCTRL wxButton* help_btn; // ID_HELP_BTN wxButton* apply_btn; // ID_APPLY_BTN + + wxCheckBox* chk_seed; + wxButton* seedButton; static const long sldr_tcks = 1000; }; diff --git a/Explore/CorrelogramAlgs.cpp b/Explore/CorrelogramAlgs.cpp index c239afa73..767013d4d 100644 --- a/Explore/CorrelogramAlgs.cpp +++ b/Explore/CorrelogramAlgs.cpp @@ -25,6 +25,7 @@ #include #include #include +#include #include #include "../SpatialIndAlgs.h" #include "../GenGeomAlgs.h" @@ -32,7 +33,6 @@ #include "../logger.h" #include "CorrelogramAlgs.h" - void CorrelogramAlgs::GetSampMeanAndVar(const std::vector& Z_, const std::vector& Z_undef, double& mean, double& var) @@ -74,13 +74,21 @@ bool CorrelogramAlgs::MakeCorrRandSamp(const std::vector& pts, { using namespace std; using namespace GenGeomAlgs; - LOG_MSG("Entering CorrelogramAlgs::MakeCorrRandSamp"); + wxLogMessage("Entering CorrelogramAlgs::MakeCorrRandSamp"); wxStopWatch sw; // Mersenne Twister random number generator, randomly seeded // with current time in seconds since Jan 1 1970. - static boost::mt19937 rng(std::time(0)); - static boost::random::uniform_int_distribution<> X(0, pts.size()-1); + uint64_t seed; + if (GdaConst::use_gda_user_seed == false) + seed = std::time(0); + else + seed = GdaConst::gda_user_seed; + + boost::mt19937 rng(seed); + //static boost::random::uniform_int_distribution<> X(0, pts.size()-1); + boost::random::uniform_01 X(rng); + X.reset(); double nbins_d = (double) num_bins; if (dist_cutoff <= 0) { @@ -116,8 +124,8 @@ bool CorrelogramAlgs::MakeCorrRandSamp(const std::vector& pts, int t_max = 0; int t_max_const = iters + 9999999; while (t < iters ) { - size_t i=X(rng); - size_t j=X(rng); + size_t i= X() * (pts.size()-1); + size_t j= X() * (pts.size()-1); // potential hangs here if (Z_undef.size() > 0 && (Z_undef[i] || Z_undef[j])) { @@ -160,7 +168,7 @@ bool CorrelogramAlgs::MakeCorrRandSamp(const std::vector& pts, } } - LOG_MSG("Exiting CorrelogramAlgs::MakeCorrRandSamp"); + wxLogMessage("Exiting CorrelogramAlgs::MakeCorrRandSamp"); return true; } @@ -173,7 +181,7 @@ bool CorrelogramAlgs::MakeCorrAllPairs(const std::vector& pts, { using namespace std; using namespace GenGeomAlgs; - LOG_MSG("Entering CorrelogramAlgs::MakeCorrAllPairs"); + wxLogMessage("Entering CorrelogramAlgs::MakeCorrAllPairs"); wxStopWatch sw; size_t nobs = pts.size(); @@ -210,7 +218,7 @@ bool CorrelogramAlgs::MakeCorrAllPairs(const std::vector& pts, continue; } - Zprod_undef[pc] = false; + if (Z_undef.size() > 0) Zprod_undef[pc] = false; double d = (is_arc ? ComputeArcDistRad(pts[i].x, pts[i].y,pts[j].x, pts[j].y) : ComputeEucDist(pts[i].x, pts[i].y, pts[j].x, pts[j].y)); @@ -271,9 +279,9 @@ bool CorrelogramAlgs::MakeCorrAllPairs(const std::vector& pts, stringstream ss; ss << "MakeCorrMakeCorrAllPairs with " << pairs << " pairs finished in " << sw.Time() << " ms."; - LOG_MSG(ss.str()); + wxLogMessage(ss.str()); */ - LOG_MSG("Exiting CorrelogramAlgs::MakeCorrAllPairs"); + wxLogMessage("Exiting CorrelogramAlgs::MakeCorrAllPairs"); return true; } @@ -286,7 +294,7 @@ bool CorrelogramAlgs::MakeCorrThresh(const rtree_pt_2d_t& rtree, using namespace std; using namespace GenGeomAlgs; using namespace SpatialIndAlgs; - LOG_MSG("Entering CorrelogramAlgs::MakeCorrThresh (plane)"); + wxLogMessage("Entering CorrelogramAlgs::MakeCorrThresh (plane)"); wxStopWatch sw; if (thresh <= 0) return false; @@ -310,7 +318,7 @@ bool CorrelogramAlgs::MakeCorrThresh(const rtree_pt_2d_t& rtree, if (calc_prods) { GetSampMeanAndVar(Z, Z_undef, mean, var); if (var <= 0) { - //LOG_MSG("Error: non-positive variance calculated"); + //wxLogMessage("Error: non-positive variance calculated"); return false; } } @@ -360,9 +368,9 @@ bool CorrelogramAlgs::MakeCorrThresh(const rtree_pt_2d_t& rtree, stringstream ss; ss << "MakeCorrThresh with threshold " << thresh << " finished in " << sw.Time() << " ms."; - LOG_MSG(ss.str()); + wxLogMessage(ss.str()); */ - LOG_MSG("Exiting CorrelogramAlgs::MakeCorrThresh (plane)"); + wxLogMessage("Exiting CorrelogramAlgs::MakeCorrThresh (plane)"); return true; } @@ -376,7 +384,7 @@ bool CorrelogramAlgs::MakeCorrThresh(const rtree_pt_3d_t& rtree, using namespace std; using namespace GenGeomAlgs; using namespace SpatialIndAlgs; - LOG_MSG("Entering CorrelogramAlgs::MakeCorrThresh (sphere)"); + wxLogMessage("Entering CorrelogramAlgs::MakeCorrThresh (sphere)"); wxStopWatch sw; if (thresh <= 0) return false; @@ -399,7 +407,7 @@ bool CorrelogramAlgs::MakeCorrThresh(const rtree_pt_3d_t& rtree, if (calc_prods) { GetSampMeanAndVar(Z, Z_undef, mean, var); if (var <= 0) { - //LOG_MSG("Error: non-positive variance calculated"); + //wxLogMessage("Error: non-positive variance calculated"); return false; } } @@ -454,8 +462,8 @@ bool CorrelogramAlgs::MakeCorrThresh(const rtree_pt_3d_t& rtree, stringstream ss; ss << "MakeCorrThresh with threshold " << thresh << " finished in " << sw.Time() << " ms."; - LOG_MSG(ss.str()); + wxLogMessage(ss.str()); */ - LOG_MSG("Exiting CorrelogramAlgs::MakeCorrThresh (sphere)"); + wxLogMessage("Exiting CorrelogramAlgs::MakeCorrThresh (sphere)"); return true; } diff --git a/Explore/CorrelogramView.cpp b/Explore/CorrelogramView.cpp index caf15505b..9585fa0f1 100644 --- a/Explore/CorrelogramView.cpp +++ b/Explore/CorrelogramView.cpp @@ -55,9 +55,9 @@ CorrelogramFrame::CorrelogramFrame(wxFrame *parent, Project* project, const wxPoint& pos, const wxSize& size) : TemplateFrame(parent, project, title, pos, size, wxDEFAULT_FRAME_STYLE), -correl_params_frame(0), panel(0), +correl_params_frame(0), panel(0),lowess_param_frame(0), sp_can(0), panel_v_szr(0), bag_szr(0), top_h_sizer(0), -hist_plot(0), local_hl_state(0), message_win(0), project(project), shs_plot(0) +hist_plot(0), local_hl_state(0), message_win(0), project(project), shs_plot(0), display_statistics(false) { wxLogMessage("Open CorrelogramFrame."); local_hl_state = new HighlightState(); @@ -109,6 +109,10 @@ hist_plot(0), local_hl_state(0), message_win(0), project(project), shs_plot(0) CorrelogramFrame::~CorrelogramFrame() { + if (lowess_param_frame) { + lowess_param_frame->removeObserver(this); + lowess_param_frame->closeAndDeleteWhenEmpty(); + } if (correl_params_frame) { correl_params_frame->removeObserver(this); correl_params_frame->closeAndDeleteWhenEmpty(); @@ -118,6 +122,32 @@ CorrelogramFrame::~CorrelogramFrame() DeregisterAsActive(); } +void CorrelogramFrame::update(LowessParamObservable* o) +{ + if (sp_can) { + sp_can->ChangeLoessParams(o->GetF(), o->GetIter(), o->GetDeltaFactor()); + } +} + +void CorrelogramFrame::notifyOfClosing(LowessParamObservable* o) +{ + lowess_param_frame = 0; +} + +void CorrelogramFrame::OnEditLowessParams(wxCommandEvent& event) +{ + wxLogMessage("In CorrelogramFrame::OnEditLowessParams"); + if (lowess_param_frame) { + lowess_param_frame->Iconize(false); + lowess_param_frame->Raise(); + lowess_param_frame->SetFocus(); + } else { + Lowess l; + lowess_param_frame = new LowessParamFrame(l.GetF(), l.GetIter(), l.GetDeltaFactor(), project); + lowess_param_frame->registerObserver(this); + } +} + void CorrelogramFrame::OnMouseEvent(wxMouseEvent& event) { if (event.RightDown()) { @@ -137,8 +167,10 @@ void CorrelogramFrame::OnRightClick(const wxPoint& pos) if (!optMenu) return; UpdateContextMenuItems(optMenu); + GeneralWxUtils::CheckMenuItem(optMenu, XRCID("ID_CORRELOGRAM_DISPLAY_STATS"), display_statistics); PopupMenu(optMenu, pos); UpdateOptionMenuItems(); + wxMenuItem* save_menu = optMenu->FindItem(XRCID("ID_SAVE_CORRELOGRAM_STATS")); Connect(save_menu->GetId(), wxEVT_MENU, @@ -165,11 +197,12 @@ void CorrelogramFrame::OnSaveResult(wxCommandEvent& event) txt_out << ""; vector lbls; - lbls.push_back("Autocorr."); - lbls.push_back("Min"); - lbls.push_back("Max"); - lbls.push_back("# Pairs"); - + lbls.push_back(_("Autocorr.")); + lbls.push_back(_("Min")); + lbls.push_back(_("Max")); + lbls.push_back(_("# Pairs")); + + wxString header = ""; int total_pairs = 0; for (size_t i=0; iLoadMenu("ID_CORRELOGRAM_MENU_OPTIONS"); CorrelogramFrame::UpdateContextMenuItems(optMenu); - GeneralWxUtils::ReplaceMenu(mb, "Options", optMenu); + GeneralWxUtils::ReplaceMenu(mb, _("Options"), optMenu); UpdateOptionMenuItems(); } @@ -225,7 +258,7 @@ void CorrelogramFrame::UpdateOptionMenuItems() { //TemplateFrame::UpdateOptionMenuItems(); // set common items first wxMenuBar* mb = GdaFrame::GetGdaFrame()->GetMenuBar(); - int menu = mb->FindMenu("Options"); + int menu = mb->FindMenu(_("Options")); if (menu != wxNOT_FOUND) { CorrelogramFrame::UpdateContextMenuItems(mb->GetMenu(menu)); } @@ -259,7 +292,19 @@ void CorrelogramFrame::OnShowCorrelParams(wxCommandEvent& event) void CorrelogramFrame::OnDisplayStatistics(wxCommandEvent& event) { wxLogMessage("In CorrelogramFrame::OnDisplayStatistics()"); + display_statistics = !display_statistics; + if (shs_plot) { + if (display_statistics) shs_plot->Show(); + else shs_plot->Hide(); + top_h_sizer->RecalcSizes(); + } + Refresh(); UpdateOptionMenuItems(); + wxMenu* optMenu; + optMenu = wxXmlResource::Get()->LoadMenu("ID_CORRELOGRAM_MENU_OPTIONS"); + if (!optMenu) return; + void *data = reinterpret_cast(display_statistics); + optMenu->SetClientData( data ); } /** Implementation of TableStateObserver interface */ @@ -323,9 +368,9 @@ void CorrelogramFrame::notifyNewHover(const std::vector& hover_obs, wxString s; if (total_hover_obs > 0) { int id = hover_obs[0]; - s << "autocorrelation is " << cbins[id].corr_avg; - s << " for obs within distance band "; - s << cbins[id].dist_min << " to " << cbins[id].dist_max; + s << _("autocorrelation is ") << cbins[id].corr_avg; + s << _(" for obs within distance band "); + s << cbins[id].dist_min << _(" to ") << cbins[id].dist_max; } sb->SetStatusText(s); } @@ -342,8 +387,8 @@ void CorrelogramFrame::notifyNewHistHover(const std::vector& hover_obs, } wxString s; int id = hover_obs[0]; - s << cbins[id].num_pairs << " pairs in distance band "; - s << cbins[id].dist_min << " to " << cbins[id].dist_max; + s << cbins[id].num_pairs << _(" pairs in distance band "); + s << cbins[id].dist_min << _(" to ") << cbins[id].dist_max; sb->SetStatusText(s); } @@ -353,7 +398,7 @@ void CorrelogramFrame::SetupPanelForNumVariables(int num_vars) { if (!panel || !bag_szr) return; - int num_top_rows = GenUtils::max(1, num_vars); + int num_top_rows = std::max(1, num_vars); int num_rows_total = num_top_rows + 3; if (message_win) { message_win->Unbind(wxEVT_MOTION, &CorrelogramFrame::OnMouseEvent, this); @@ -369,6 +414,7 @@ void CorrelogramFrame::SetupPanelForNumVariables(int num_vars) &CorrelogramFrame::OnMouseEvent, this); scatt_plots[i]->Destroy(); + scatt_plots[i] = 0; } } scatt_plots.clear(); @@ -434,7 +480,7 @@ void CorrelogramFrame::SetupPanelForNumVariables(int num_vars) message_win->Bind(wxEVT_RIGHT_UP, &CorrelogramFrame::OnMouseEvent, this); UpdateMessageWin(); bag_szr->Add(message_win, wxGBPosition(0,1), wxGBSpan(1,1), wxEXPAND); - SetTitle("Correlogram" + type_str); + SetTitle(_("Correlogram") + type_str); } else { for (int row=0; row Y(cbins.size()); std::vector Y_undef(cbins.size()); @@ -508,7 +554,7 @@ void CorrelogramFrame::SetupPanelForNumVariables(int num_vars) X_undef[i] = false; } - SimpleScatterPlotCanvas* sp_can = 0; + //SimpleScatterPlotCanvas* sp_can = 0; sp_can = new SimpleScatterPlotCanvas(panel, this, project, local_hl_state, this, X, Y, X_undef, Y_undef, @@ -524,7 +570,7 @@ void CorrelogramFrame::SetupPanelForNumVariables(int num_vars) valid_sampling, // show LOWESS fit false); sp_can->SetFixedAspectRatioMode(false); - sp_can->ChangeLoessParams(0.2,5,0.02); + //sp_can->ChangeLoessParams(0.2,5,0.02); bag_szr->Add(sp_can, wxGBPosition(row, 1), wxGBSpan(1,1), wxEXPAND); scatt_plots.push_back(sp_can); } @@ -557,7 +603,7 @@ void CorrelogramFrame::SetupPanelForNumVariables(int num_vars) { sa_can = new SimpleAxisCanvas(panel, this, project, local_hl_state, - freq_vals, "Frequency", + freq_vals, _("Frequency"), freq_min, freq_max, false, // is horizontal ? true, // show axes @@ -600,14 +646,14 @@ void CorrelogramFrame::SetupPanelForNumVariables(int num_vars) wxString title; if (par.dist_metric == WeightsMetaInfo::DM_arc) { - title << "Arc Distance, "; + title << _("Arc Distance") << ", "; if (par.dist_units == WeightsMetaInfo::DU_mile) { - title << " mi"; + title << _(" mi"); } else { - title << " km"; + title << _(" km"); } } else { - title << "Euclidean Distance"; + title << _("Euclidean Distance"); } AxisScale h_axs; @@ -627,10 +673,16 @@ void CorrelogramFrame::SetupPanelForNumVariables(int num_vars) h_axs.tics[i] = h_axs.data_min + d*h_axs.tic_inc; stringstream ss; if (h_axs.tics[i] < 10000000) { - ss << std::fixed << std::setprecision(1) << h_axs.tics[i]; + if ( h_axs.tics[i] == (int) h_axs.tics[i]) + ss << wxString::Format("%d", (int) h_axs.tics[i]); + else + ss << std::fixed << std::setprecision(1) << h_axs.tics[i]; h_axs.tics_str[i] = ss.str(); } else { - ss << std::setprecision(1) << h_axs.tics[i]; + if ( h_axs.tics[i] == (int) h_axs.tics[i]) + ss << wxString::Format("%d", (int) h_axs.tics[i]); + else + ss << std::setprecision(1) << h_axs.tics[i]; h_axs.tics_str[i] = ss.str(); } h_axs.tics_str_show[i] = true; @@ -708,10 +760,10 @@ void CorrelogramFrame::SetupPanelForNumVariables(int num_vars) vector lbls; - lbls.push_back("Autocorr."); - lbls.push_back("Min"); - lbls.push_back("Max"); - lbls.push_back("# Pairs"); + lbls.push_back(_("Autocorr.")); + lbls.push_back(_("Min")); + lbls.push_back(_("Max")); + lbls.push_back(_("# Pairs")); vector > vals; vector stats; @@ -736,17 +788,20 @@ void CorrelogramFrame::SetupPanelForNumVariables(int num_vars) stats.push_back(range_left); stats.push_back(range_right); stats.push_back(est_dist); - + SimpleHistStatsCanvas* shs_can = 0; shs_can = new SimpleHistStatsCanvas(panel, this, project, local_hl_state, lbls, vals, stats, "ID_CORRELOGRAM_MENU_OPTIONS", - wxDefaultPosition, wxSize(-1, 90)); + wxDefaultPosition, wxSize(-1, 110)); shs_can->SetFixedAspectRatioMode(false); //bag_szr->Add(shs_can, wxGBPosition(num_top_rows+2, 1), wxGBSpan(1,1), wxEXPAND); shs_plot = shs_can; + + if (display_statistics) shs_plot->Show(); + else shs_plot->Hide(); panel_v_szr->Add(shs_can, 0, wxLEFT | wxRIGHT | wxEXPAND); @@ -760,6 +815,7 @@ void CorrelogramFrame::SetupPanelForNumVariables(int num_vars) } } + double CorrelogramFrame::GetEstDistWithZeroAutocorr(double& rng_left, double& rng_right) { @@ -767,6 +823,14 @@ double CorrelogramFrame::GetEstDistWithZeroAutocorr(double& rng_left, for (size_t i=0; i"; - s << "Options > Change Parameters
    "; - s << "to specify variable and distance parameters."; + s << _("Please right-click or use
    "); + s << "" << _("Options > Change Parameters") << "
    "; + s << _("to specify variable and distance parameters."); } else if (count > 0) { s << "Variables specified:
    "; for (int i=0; i Z_undef; if (var_man.GetVarsCount() > 0) { wxString nm = var_man.GetName(0); - int tm = var_man.GetTime(0); - wxString title(var_man.GetNameWithTime(0)); + int tm = var_man.GetCurTime(0); + const std::vector& data(data_map[nm][tm]); const std::vector& data_undef(data_undef_map[nm][tm]); Z.resize(data.size()); @@ -942,8 +1012,8 @@ bool CorrelogramFrame::UpdateCorrelogramData() } if (success == false) { - wxString msg = "Please select another variable with values more suitable for computing a correlogram."; - wxString title = "Variable Value Error"; + wxString msg = _("Please select another variable with values more suitable for computing a correlogram."); + wxString title = _("Variable Value Error"); wxMessageDialog dlg (this, msg, title, wxOK | wxICON_ERROR); dlg.ShowModal(); return success; diff --git a/Explore/CorrelogramView.h b/Explore/CorrelogramView.h index 268e6216a..8c0661401 100644 --- a/Explore/CorrelogramView.h +++ b/Explore/CorrelogramView.h @@ -29,6 +29,8 @@ #include "CorrelParamsObserver.h" #include "SimpleScatterPlotCanvas.h" #include "SimpleBinsHistCanvas.h" +#include "LowessParamDlg.h" +#include "LowessParamObserver.h" #include "../ShapeOperations/Lowess.h" #include "../ShapeOperations/SmoothingUtils.h" #include "../TemplateCanvas.h" @@ -53,7 +55,7 @@ typedef std::map data_undef_map_type; CorrelogramFrame manages all of its canvas child windows. */ class CorrelogramFrame : public TemplateFrame, public CorrelParamsObserver, -public SimpleScatterPlotCanvasCbInt, public SimpleBinsHistCanvasCbInt +public SimpleScatterPlotCanvasCbInt, public SimpleBinsHistCanvasCbInt, public LowessParamObserver { public: CorrelogramFrame(wxFrame *parent, Project* project, @@ -67,10 +69,13 @@ public SimpleScatterPlotCanvasCbInt, public SimpleBinsHistCanvasCbInt virtual void MapMenus(); virtual void UpdateOptionMenuItems(); virtual void UpdateContextMenuItems(wxMenu* menu); + virtual void OnRightClick(const wxPoint& pos); void OnShowCorrelParams(wxCommandEvent& event); void OnDisplayStatistics(wxCommandEvent& event); - + void OnSaveResult(wxCommandEvent& event); + void OnEditLowessParams(wxCommandEvent& event); + /** Implementation of TableStateObserver interface */ virtual void update(TableState* o); virtual bool AllowObservationAddDelete() { return true; } @@ -89,11 +94,10 @@ public SimpleScatterPlotCanvasCbInt, public SimpleBinsHistCanvasCbInt /** Implementation of SimpleScatterPlotCanvasCbInt interface */ virtual void notifyNewHistHover(const std::vector& hover_obs, int total_hover_obs); - - virtual void OnRightClick(const wxPoint& pos); - - void OnSaveResult(wxCommandEvent& event); - + + /** Implementation of LowessParamObserver interface */ + virtual void update(LowessParamObservable* o); + virtual void notifyOfClosing(LowessParamObservable* o); protected: void ReDraw(); @@ -104,6 +108,7 @@ public SimpleScatterPlotCanvasCbInt, public SimpleBinsHistCanvasCbInt double GetEstDistWithZeroAutocorr(double& rng_left, double& rng_right); Project* project; + LowessParamFrame* lowess_param_frame; CorrelParamsFrame* correl_params_frame; CorrelParams par; GdaVarTools::Manager var_man; @@ -116,7 +121,10 @@ public SimpleScatterPlotCanvasCbInt, public SimpleBinsHistCanvasCbInt SimpleBinsHistCanvas* hist_plot; SimpleHistStatsCanvas* shs_plot; HLStateInt* local_hl_state; - + SimpleScatterPlotCanvas* sp_can; + + bool display_statistics; + wxBoxSizer* top_h_sizer; wxPanel* panel; wxBoxSizer* panel_v_szr; diff --git a/Explore/CovSpHLStateProxy.h b/Explore/CovSpHLStateProxy.h index d5b05d58a..72a5d7e3d 100644 --- a/Explore/CovSpHLStateProxy.h +++ b/Explore/CovSpHLStateProxy.h @@ -64,6 +64,7 @@ class CovSpHLStateProxy : public HLStateInt, public HighlightStateObserver { virtual wxString GetEventTypeStr(); virtual void SetEventType( EventType e ) { event_type = e; } virtual int GetTotalHighlighted() { return total_highlighted; } + virtual void SetTotalHighlighted(int n) { total_highlighted = n; } virtual void registerObserver(HighlightStateObserver* o); virtual void removeObserver(HighlightStateObserver* o); diff --git a/Explore/CovSpView.cpp b/Explore/CovSpView.cpp index 3242fd7a8..a6f1d6ccf 100644 --- a/Explore/CovSpView.cpp +++ b/Explore/CovSpView.cpp @@ -149,7 +149,7 @@ void CovSpFrame::MapMenus() LoadMenu("ID_COV_SCATTER_PLOT_MENU_OPTIONS"); CovSpFrame::UpdateContextMenuItems(optMenu); - GeneralWxUtils::ReplaceMenu(mb, "Options", optMenu); + GeneralWxUtils::ReplaceMenu(mb, _("Options"), optMenu); UpdateOptionMenuItems(); } @@ -157,7 +157,7 @@ void CovSpFrame::UpdateOptionMenuItems() { //TemplateFrame::UpdateOptionMenuItems(); // set common items first wxMenuBar* mb = GdaFrame::GetGdaFrame()->GetMenuBar(); - int menu = mb->FindMenu("Options"); + int menu = mb->FindMenu(_("Options")); if (menu == wxNOT_FOUND) { } else { CovSpFrame::UpdateContextMenuItems(mb->GetMenu(menu)); @@ -184,7 +184,7 @@ void CovSpFrame::UpdateContextMenuItems(wxMenu* menu) void CovSpFrame::UpdateTitle() { - wxString s = _("Nonparametric Spatial Autocorrelation"); + wxString s = _("Spatial Correlogram"); if (var_man.GetVarsCount() > 0) s << " - " << var_man.GetNameWithTime(0); SetTitle(s); } @@ -194,7 +194,8 @@ wxString CovSpFrame::GetUpdateStatusBarString(const vector& hover_obs, { wxString s; const pairs_bimap_type& bimap = project->GetSharedPairsBimap(); - int last = GenUtils::min(total_hover_obs, hover_obs.size(), 2); + int last = std::min(total_hover_obs, (int)hover_obs.size()); + last = std::min(last, 2); size_t t = var_man.GetTime(0); typedef pairs_bimap_type::left_map::const_iterator left_const_iterator; for (int h=0; hIconize(false); lowess_param_frame->Raise(); lowess_param_frame->SetFocus(); } else { Lowess l; // = t->GetLowess(); // should be shared by all cells - lowess_param_frame = new LowessParamFrame(l.GetF(), l.GetIter(), - l.GetDeltaFactor(), - project); + lowess_param_frame = new LowessParamFrame(l.GetF(), l.GetIter(), l.GetDeltaFactor(), project); lowess_param_frame->registerObserver(this); } } @@ -256,15 +256,13 @@ void CovSpFrame::OnShowVarsChooser(wxCommandEvent& event) { wxLogMessage("In CovSpFrame::OnShowVarsChooser"); if (too_many_obs) return; - VariableSettingsDlg VS(project, VariableSettingsDlg::univariate, - false, true, "Variable Choice", "Variable"); + VariableSettingsDlg VS(project, VariableSettingsDlg::univariate, false, true, _("Variable Choice"), _("Variable")); if (VS.ShowModal() != wxID_OK) return; GdaVarTools::VarInfo& v = VS.var_info[0]; vector tm_strs; project->GetTableInt()->GetTimeStrings(tm_strs); GdaVarTools::Manager t_var_man(tm_strs); - t_var_man.AppendVar(v.name, v.min, v.max, v.time, - v.sync_with_global_time, v.fixed_scale); + t_var_man.AppendVar(v.name, v.min, v.max, v.time, v.sync_with_global_time, v.fixed_scale); var_man = t_var_man; // If distance metric or units changed, then reinit distance as well @@ -518,22 +516,17 @@ void CovSpFrame::UpdateMessageWin() if (too_many_obs) { long n_obs = project->GetNumRecords(); long n_pairs = (n_obs*(n_obs-1))/2; - s << "This view currently supports data with at most 1000 observations. "; - s << "The Nonparametric Spatial Autocorrelation Scatterplot plots "; - s << "distances between all pairs of observations. "; - s << "The current data set has " << n_obs << " observations and "; - s << n_pairs << " unordered pairs of observations."; + wxString msg = wxString::Format(_("This view currently supports data with at most 1000 observations. The Spatial Correlogram Scatterplot plots distances between all pairs of observations. The current data set has %d observations and %d unordered pairs of observations."), n_obs, n_pairs); + s << msg; } else { int count = var_man.GetVarsCount(); if (count == 0) { - s << "Please use
    "; - s << "Options > Change Variable
    "; - s << "to specify a variable."; + s << _("Please use
    Options > Change Variable
    to specify a variable."); } if (Z_error_msg[var_man.GetTime(0)].IsEmpty()) { - s << "Variable " << var_man.GetName(0); - s << " is specified. "; + wxString msg = wxString::Format(_("Variable %s is specified. "), var_man.GetName(0)); + s << msg; } else { - s << "Error: " << Z_error_msg[var_man.GetTime(0)]; + s << _("Error: ") << Z_error_msg[var_man.GetTime(0)]; } } s << "

    "; @@ -601,9 +594,9 @@ void CovSpFrame::UpdateDataFromVarMan() } wxString str_template; - str_template = _T("Variable %s is a placeholer"); + str_template = _("Variable %s is a placeholer"); if (tm_variant) { - str_template = _T("Variable %s at time %d is a placeholer"); + str_template = _("Variable %s at time %d is a placeholer"); } wxString s = wxString::Format(str_template, z_name, @@ -643,9 +636,9 @@ void CovSpFrame::UpdateDataFromVarMan() if (!success) { wxString str_template; - str_template = _T("Variable %s is a placeholer"); + str_template = _("Variable %s is a placeholer"); if (tm_variant) { - str_template = _T("Variable %s at time %d could not be standardized."); + str_template = _("Variable %s at time %d could not be standardized."); } wxString s = wxString::Format(str_template, z_name, diff --git a/Explore/CovSpView.h b/Explore/CovSpView.h index 54d317352..c5c80566d 100644 --- a/Explore/CovSpView.h +++ b/Explore/CovSpView.h @@ -90,13 +90,13 @@ typedef std::vector vec_vec_bool_type; class CovSpFrame : public TemplateFrame, public LowessParamObserver { public: - CovSpFrame(wxFrame *parent, Project* project, - const GdaVarTools::Manager& var_man, - WeightsMetaInfo::DistanceMetricEnum dist_metric, - WeightsMetaInfo::DistanceUnitsEnum dist_units, - const wxString& title = _("Nonparametric Spatial Autocorrelation"), - const wxPoint& pos = wxDefaultPosition, - const wxSize& size = GdaConst::scatterplot_default_size); + CovSpFrame(wxFrame *parent, Project* project, + const GdaVarTools::Manager& var_man, + WeightsMetaInfo::DistanceMetricEnum dist_metric, + WeightsMetaInfo::DistanceUnitsEnum dist_units, + const wxString& title = _("Spatial Correlogram"), + const wxPoint& pos = wxDefaultPosition, + const wxSize& size = GdaConst::scatterplot_default_size); virtual ~CovSpFrame(); void OnMouseEvent(wxMouseEvent& event); diff --git a/Explore/GStatCoordinator.cpp b/Explore/GStatCoordinator.cpp index 558f125f2..f76b84711 100644 --- a/Explore/GStatCoordinator.cpp +++ b/Explore/GStatCoordinator.cpp @@ -22,6 +22,7 @@ #include #include #include +#include #include #include #include "../DataViewer/TableInterface.h" @@ -33,56 +34,7 @@ #include "GetisOrdMapNewView.h" #include "GStatCoordinator.h" -/* - Example data: x = {2, 3, 3.2, 5, 8, 7} - locations = {(10, 10), (20, 10), (40, 10), (15, 20), (30, 20), (30, 30)} - distances: - 0 1 2 3 4 5 - 0 0.00 10.00 30.00 11.18 22.36 28.28 - 1 10.00 0.00 20.00 11.18 14.14 22.36 - 2 30.00 20.00 0.00 26.93 14.14 22.36 - 3 11.18 11.18 26.93 0.00 15.00 18.03 - 4 22.36 14.14 14.14 15.00 0.00 10.00 - 5 28.28 22.36 22.46 18.03 10.00 0.00 - - W for threshold distance = 15 - 0: 1 3 - 1: 0 3 4 - 2: 4 - 3: 0 1 4 - 4: 1 2 3 5 - 5: 4 - - W_i = [1, 1, 1, 1, 1] - - G_i = (lag_i)/(x_star-x_i) - = {0.152671756, 0.198412698, 0.32, 0.186781609, 0.225247525, 0.377358491} - - n = 6 - ExG = E[G*_i] = 1/(n-1) = 0.2 - ExGstar = E[G_i] = 1/n = 1.6666666 - x_star = 2 + 3 + 3.2 + 5 + 8 + 7 = 28.2 - x_sstar = 2^2 + 3^2 + (3.2)^2 + 5^2 + 8^2 + 7^2 = 161.24 - x_hat = x_star/n = 28.2/6 = 4.7 - s2 = x_sstar/n - (x_hat)^2 = 4.783333 - s = sqrt(s^2) = 2.18708329 - - x_hat_i = {5.24, 5.04, 5, 4.64, 4.04, 4.24} - s2_i = (x_sstar-x_i^2)/(n-1) - (x_hat_i)^2 - = {3.9904, 5.0464, 5.2, 5.7184, 3.1264, 4.4704} - Var[G_i] = (1/(n-1)^2) * (s_i/x_hat_i)^2 - = {0.00581318105, 0.00794658604, 0.00832, 0.0106242568, 0.00766199392, - 0.00994660021 } - z_i = (G_i - E[G_i]) / sqrt(Var[G_i]) - = {-0.620745338, -0.0178061189, 1.31558703, - -0.128241714, 0.288434967, 1.77833941} - - */ - - -GStatWorkerThread::GStatWorkerThread(const GalElement* W_, - const std::vector& undefs_, - int obs_start_s, int obs_end_s, +GStatWorkerThread::GStatWorkerThread(int obs_start_s, int obs_end_s, uint64_t seed_start_s, GStatCoordinator* gstat_coord_s, wxMutex* worker_list_mutex_s, @@ -90,8 +42,6 @@ GStatWorkerThread::GStatWorkerThread(const GalElement* W_, std::list *worker_list_s, int thread_id_s) : wxThread(), -W(W_), -undefs(undefs_), obs_start(obs_start_s), obs_end(obs_end_s), seed_start(seed_start_s), gstat_coord(gstat_coord_s), worker_list_mutex(worker_list_mutex_s), @@ -110,7 +60,7 @@ wxThread::ExitCode GStatWorkerThread::Entry() LOG_MSG(wxString::Format("GStatWorkerThread %d started", thread_id)); // call work for assigned range of observations - gstat_coord->CalcPseudoP_range(W, undefs, obs_start, obs_end, seed_start); + gstat_coord->CalcPseudoP_range(obs_start, obs_end, seed_start); wxMutexLocker lock(*worker_list_mutex); // remove ourself from the list @@ -130,7 +80,8 @@ GStatCoordinator(boost::uuids::uuid weights_id, Project* project, const std::vector& var_info_s, const std::vector& col_ids, - bool row_standardize_weights) + bool row_standardize_weights, + bool _is_local_joint_count) : w_man_state(project->GetWManState()), w_man_int(project->GetWManInt()), w_id(weights_id), @@ -140,8 +91,10 @@ permutations(999), var_info(var_info_s), data(var_info_s.size()), data_undef(var_info_s.size()), -last_seed_used(0), reuse_last_seed(false) +last_seed_used(123456789), reuse_last_seed(true), +is_local_joint_count(_is_local_joint_count) { + wxLogMessage("Entering GStatCoordinator::GStatCoordinator()."); reuse_last_seed = GdaConst::use_gda_user_seed; if ( GdaConst::use_gda_user_seed) { last_seed_used = GdaConst::gda_user_seed; @@ -162,17 +115,19 @@ last_seed_used(0), reuse_last_seed(false) maps[i] = (GetisOrdMapFrame*) 0; } w_man_state->registerObserver(this); + wxLogMessage("Exiting GStatCoordinator::GStatCoordinator()."); } GStatCoordinator::~GStatCoordinator() { - LOG_MSG("In GStatCoordinator::~GStatCoordinator"); + wxLogMessage("In GStatCoordinator::~GStatCoordinator"); w_man_state->removeObserver(this); DeallocateVectors(); } void GStatCoordinator::DeallocateVectors() { + wxLogMessage("In GStatCoordinator::DeallocateVectors"); for (int i=0; iGetGal(w_id); } - x = x_vecs[t]; + + if (is_local_joint_count) { + int num_obs_1s = 0; + int num_obs_0s = 0; + int valid_num_obs = 0; + + for (int i=0; i 0 ) { n[t]++; x_star[t] += x[i]; @@ -355,12 +354,14 @@ void GStatCoordinator::InitFromVarInfo() CalcGs(); CalcPseudoP(); + wxLogMessage("Out GStatCoordinator::InitFromVarInfo"); } /** Update Secondary Attributes based on Primary Attributes. Update num_time_vals and ref_var_index based on Secondary Attributes. */ void GStatCoordinator::VarInfoAttributeChange() { + wxLogMessage("In GStatCoordinator::VarInfoAttributeChange"); GdaVarTools::UpdateVarInfoSecondaryAttribs(var_info); is_any_time_variant = false; @@ -380,17 +381,16 @@ void GStatCoordinator::VarInfoAttributeChange() num_time_vals = (var_info[ref_var_index].time_max - var_info[ref_var_index].time_min) + 1; } - //GdaVarTools::PrintVarInfoVector(var_info); + wxLogMessage("Out GStatCoordinator::VarInfoAttributeChange"); } /** The category vector c_val will be filled based on the current significance filter and significance values corresponding to specified canvas_time. */ -void GStatCoordinator::FillClusterCats(int canvas_time, - bool is_gi, - bool is_perm, - std::vector& c_val) +void GStatCoordinator::FillClusterCats(int canvas_time, bool is_gi, bool is_perm, std::vector& c_val) { + wxLogMessage("In GStatCoordinator::FillClusterCats()"); + int t = canvas_time; double* p_val = 0; if (is_gi && is_perm) p_val = pseudo_p_vecs[t]; @@ -410,12 +410,20 @@ void GStatCoordinator::FillClusterCats(int canvas_time, c_val[i] = 3; // isolate } else if (p_val[i] <= significance_cutoff) { - c_val[i] = z_val[i] > 0 ? 1 : 2; // high = 1, low = 2 - + if (is_local_joint_count == false) { + c_val[i] = z_val[i] > 0 ? 1 : 2; // high = 1, low = 2 + + } else { + if (x_vecs[t][i] == 1 && z_val[i] > 0) + c_val[i] = 1; + else + c_val[i] = 0; + } } else { c_val[i] = 0; // not significant } } + wxLogMessage("Out GStatCoordinator::FillClusterCats()"); } @@ -423,6 +431,7 @@ void GStatCoordinator::FillClusterCats(int canvas_time, binary weights. Weights with self-neighbors are handled correctly. */ void GStatCoordinator::CalcGs() { + wxLogMessage("In GStatCoordinator::CalcGs()"); using boost::math::normal; // typedef provides default type is double. // Construct a standard normal distribution std_norm_dist normal std_norm_dist; // default mean = zero, and s.d. = unity @@ -438,19 +447,15 @@ void GStatCoordinator::CalcGs() pseudo_p = pseudo_p_vecs[t]; pseudo_p_star = pseudo_p_star_vecs[t]; x = x_vecs[t]; + nn_1_t = num_neighbors_1[t]; - has_undefined[t] = false; has_isolates[t] = false; const GalElement* W = Gal_vecs[t]->gal; - double n_expr = sqrt((n[t]-1)*(n[t]-1)*(n[t]-2)); + for (long i=0; i 0 ) { @@ -471,15 +476,11 @@ void GStatCoordinator::CalcGs() double xd_i = x_star[t] - x[i]; if (xd_i != 0) { G[i] = lag / xd_i; - } else { - G_defined[i] = false; } double x_hat_i = xd_i * ExG[t]; // (x_star - x[i])/(n-1) - double ExGi = Wi/(n[t]-1); // location-specific variance - double ss_i = ((x_sstar[t] - x[i]*x[i])/(n[t]-1) - - x_hat_i*x_hat_i); + double ss_i = ((x_sstar[t] - x[i]*x[i])/(n[t]-1)-x_hat_i*x_hat_i); double sdG_i = sqrt(Wi*(n[t]-1-Wi)*ss_i)/(n_expr * x_hat_i); // compute z and one-sided p-val from standard-normal table @@ -490,22 +491,11 @@ void GStatCoordinator::CalcGs() } else { p[i] = cdf(std_norm_dist, z[i]); } - } else { - has_undefined[t] = true; } } else { has_isolates[t] = true; } } - - if (x_star[t] == 0) { - for (long i=0; i& undefs = x_undefs[t]; - - G = G_vecs[t]; - G_defined = G_defined_vecs[t]; - G_star = G_star_vecs[t]; - z = z_vecs[t]; - p = p_vecs[t]; - z_star = z_star_vecs[t]; - p_star = p_star_vecs[t]; - pseudo_p = pseudo_p_vecs[t]; - pseudo_p_star = pseudo_p_star_vecs[t]; - x = x_vecs[t]; - x_star_t = x_star[t]; - - if (nCPUs <= 1) { - if (!reuse_last_seed) last_seed_used = time(0); - CalcPseudoP_range(Gal_vecs[t]->gal, undefs, 0, num_obs-1, last_seed_used); - } else { - CalcPseudoP_threaded(Gal_vecs[t]->gal, undefs); - } - } - /* - wxString m; - m << "GStat on " << num_obs << " obs with " << permutations; - m << " perms over " << num_time_vals << " time periods took "; - m << sw.Time() << " ms. Last seed used: " << last_seed_used; - LOG_MSG(m); - */ - LOG_MSG("Exiting GStatCoordinator::CalcPseudoP"); + wxLogMessage("Entering GStatCoordinator::CalcPseudoP"); + CalcPseudoP_threaded(); + wxLogMessage("Exiting GStatCoordinator::CalcPseudoP"); } -void GStatCoordinator::CalcPseudoP_threaded(const GalElement* W, - const std::vector& undefs) +void GStatCoordinator::CalcPseudoP_threaded() { LOG_MSG("Entering GStatCoordinator::CalcPseudoP_threaded"); - int nCPUs = wxThread::GetCPUCount(); + int nCPUs = GdaConst::gda_cpu_cores; + if (!GdaConst::gda_set_cpu_cores) + nCPUs = wxThread::GetCPUCount(); // mutext protects access to the worker_list wxMutex worker_list_mutex; @@ -657,12 +608,9 @@ void GStatCoordinator::CalcPseudoP_threaded(const GalElement* W, uint64_t seed_start = last_seed_used+a; uint64_t seed_end = seed_start + ((uint64_t) (b-a)); int thread_id = i+1; - wxString msg; - msg << "thread " << thread_id << ": " << a << "->" << b; - msg << ", seed: " << seed_start << "->" << seed_end; GStatWorkerThread* thread = - new GStatWorkerThread(W, undefs, a, b, seed_start, this, + new GStatWorkerThread(a, b, seed_start, this, &worker_list_mutex, &worker_list_empty_cond, &worker_list, thread_id); @@ -675,7 +623,7 @@ void GStatCoordinator::CalcPseudoP_threaded(const GalElement* W, } if (is_thread_error) { // fall back to single thread calculation mode - CalcPseudoP_range(W, undefs, 0, num_obs-1, last_seed_used); + CalcPseudoP_range(0, num_obs-1, last_seed_used); } else { std::list::iterator it; for (it = worker_list.begin(); it != worker_list.end(); it++) { @@ -689,93 +637,124 @@ void GStatCoordinator::CalcPseudoP_threaded(const GalElement* W, // alarm (spurious signal), the loop will exit. } } - LOG_MSG("Exiting GStatCoordinator::CalcPseudoP_threaded"); } /** In the code that computes Gi and Gi*, we specifically checked for self-neighbors and handled the situation appropriately. For the permutation code, we will disallow self-neighbors. */ -void GStatCoordinator::CalcPseudoP_range(const GalElement* W, - const std::vector& undefs, - int obs_start, int obs_end, - uint64_t seed_start) +void GStatCoordinator::CalcPseudoP_range(int obs_start, int obs_end,uint64_t seed_start) { GeoDaSet workPermutation(num_obs); - int max_rand = num_obs-1; for (long i=obs_start; i<=obs_end; i++) { + std::vector countGLarger(num_time_vals, 0); + std::vector countGStarLarger(num_time_vals, 0); - if (undefs[i]) + // get full neighbors even if has undefined value + int numNeighbors = 0; + GalElement* w; + for (int t=0; tgal; + if (w[i].Size() > numNeighbors) + numNeighbors = w[i].Size(); + } + if (numNeighbors == 0) { continue; - - const int numNeighsI = W[i].Size(); - const double numNeighsD = W[i].Size(); + } - //only compute for non-isolates - if ( numNeighsI > 0 && G_defined[i]) { - // know != 0 since G_defined[i] true - double xd_i = x_star_t - x[i]; - - int countGLarger = 0; - int countGStarLarger = 0; - double permutedG = 0; - double permutedGStar = 0; + if (is_local_joint_count && nn_1_t[i] ==0) { + for (int t=0; t0) { + workPermutation.Push(newRandom); + rand++; + } + } + std::vector permNeighbors(numNeighbors); + for (int cp=0; cp& undefs = x_undefs[t]; + double permutedG = 0; + double permutedGStar = 0; + double* _G = G_vecs[t]; + double* _G_star = G_star_vecs[t]; + double* _x = x_vecs[t]; + double _x_star_t = x_star[t]; + + if (undefs[i]) + continue; + + double xd_i = _x_star_t - _x[i]; + int validNeighbors = 0; + double lag_i=0; + + // use permutation to compute the lags + for (int j=0; j 0 && row_standardize) { + permutedG = lag_i / (validNeighbors * xd_i); + permutedGStar = (lag_i+_x[i]) / ((validNeighbors+1.0)*_x_star_t); + } else { // binary weights + // Wi = numNeighsD // assume no self-neighbors + permutedG = lag_i / xd_i; + permutedGStar = (lag_i+_x[i]) / _x_star_t; + } + + if (permutedG >= _G[i]) countGLarger[t]++; + if (permutedGStar >= _G_star[i]) countGStarLarger[t]++; + } + } + + for (int t=0; t= G[i]) countGLarger++; - if (permutedGStar >= G_star[i]) countGStarLarger++; - } - // pick the smallest - if (permutations-countGLarger < countGLarger) { - countGLarger=permutations-countGLarger; - } - pseudo_p[i] = (countGLarger + 1.0)/(permutations+1.0); - //if (i == DBGI) LOG(pseudo_p[i]); - - if (permutations-countGStarLarger < countGStarLarger) { - countGStarLarger=permutations-countGStarLarger; - } - pseudo_p_star[i] = (countGStarLarger + 1.0)/(permutations+1.0); - } + if (permutations-countGStarLarger[t] < countGStarLarger[t]) { + countGStarLarger[t] = permutations-countGStarLarger[t]; + } + ps_t[i] = (countGStarLarger[t] + 1.0)/(permutations+1.0); + } } } void GStatCoordinator::SetSignificanceFilter(int filter_id) { + wxLogMessage("In GStatCoordinator::SetSignificanceFilter"); + if (filter_id == -1) { + // user input cutoff + significance_filter = filter_id; + return; + } // 0: >0.05 1: 0.05, 2: 0.01, 3: 0.001, 4: 0.0001 if (filter_id < 1 || filter_id > 4) return; significance_filter = filter_id; @@ -783,6 +762,7 @@ void GStatCoordinator::SetSignificanceFilter(int filter_id) if (filter_id == 2) significance_cutoff = 0.01; if (filter_id == 3) significance_cutoff = 0.001; if (filter_id == 4) significance_cutoff = 0.0001; + wxLogMessage("Exiting GStatCoordinator::SetSignificanceFilter"); } void GStatCoordinator::update(WeightsManState* o) diff --git a/Explore/GStatCoordinator.h b/Explore/GStatCoordinator.h index a1733a91b..067601f15 100644 --- a/Explore/GStatCoordinator.h +++ b/Explore/GStatCoordinator.h @@ -52,9 +52,7 @@ typedef boost::multi_array b_array_type; class GStatWorkerThread : public wxThread { public: - GStatWorkerThread(const GalElement* W, - const std::vector& undefs, - int obs_start, int obs_end, uint64_t seed_start, + GStatWorkerThread(int obs_start, int obs_end, uint64_t seed_start, GStatCoordinator* gstat_coord, wxMutex* worker_list_mutex, wxCondition* worker_list_empty_cond, @@ -63,8 +61,6 @@ class GStatWorkerThread : public wxThread virtual ~GStatWorkerThread(); virtual void* Entry(); // thread execution starts here - const GalElement* W; - const std::vector& undefs; int obs_start; int obs_end; uint64_t seed_start; @@ -82,7 +78,8 @@ class GStatCoordinator : public WeightsManStateObserver GStatCoordinator(boost::uuids::uuid weights_id, Project* project, const std::vector& var_info, const std::vector& col_ids, - bool row_standardize_weights); + bool row_standardize_weights, + bool is_local_joint_count=false); virtual ~GStatCoordinator(); bool IsOk() { return true; } @@ -93,7 +90,10 @@ class GStatCoordinator : public WeightsManStateObserver void SetSignificanceFilter(int filter_id); int GetSignificanceFilter() { return significance_filter; } int permutations; // any number from 9 to 99999, 99 will be default - + double bo; //Bonferroni bound + double fdr; //False Discovery Rate + double user_sig_cutoff; // user defined cutoff + uint64_t GetLastUsedSeed() { return last_seed_used; } @@ -107,7 +107,7 @@ class GStatCoordinator : public WeightsManStateObserver GdaConst::gda_user_seed = last_seed_used; wxString val; val << last_seed_used; - OGRDataAdapter::GetInstance().AddEntry("gda_user_seed", val.ToStdString()); + OGRDataAdapter::GetInstance().AddEntry("gda_user_seed", val); } bool IsReuseLastSeed() { return reuse_last_seed; } @@ -129,7 +129,10 @@ class GStatCoordinator : public WeightsManStateObserver virtual void closeObserver(boost::uuids::uuid id); std::vector n; // # non-neighborless observations - + + // a special case Local Join Count + bool is_local_joint_count; + double x_star_t; // temporary x_star for use in worker threads std::vector x_star; // sum of all x_i // threaded std::vector x_sstar; // sum of all (x_i)^2 @@ -143,7 +146,11 @@ class GStatCoordinator : public WeightsManStateObserver std::vector VarGstar; // since W is row-standardized, sdGstar same for all i std::vector sdGstar; - + // number of neighbors + vector num_neighbors; + // number of neighbors with 1 + std::vector num_neighbors_1; + protected: // The following ten are just temporary pointers into the corresponding // space-time data arrays below @@ -161,6 +168,8 @@ class GStatCoordinator : public WeightsManStateObserver double* pseudo_p; //threaded double* pseudo_p_star; //threaded double* x; //threaded + double* e_p; //threaded + wxInt64* nn_1_t; public: std::vector G_vecs; //threaded @@ -211,8 +220,7 @@ class GStatCoordinator : public WeightsManStateObserver std::vector maps; void CalcPseudoP(); - void CalcPseudoP_range(const GalElement* W, const std::vector& undefs, - int obs_start, int obs_end, uint64_t seed_start); + void CalcPseudoP_range(int obs_start, int obs_end, uint64_t seed_start); void InitFromVarInfo(); void VarInfoAttributeChange(); @@ -223,7 +231,7 @@ class GStatCoordinator : public WeightsManStateObserver void DeallocateVectors(); void AllocateVectors(); - void CalcPseudoP_threaded(const GalElement* W, const std::vector& undefs); + void CalcPseudoP_threaded(); void CalcGs(); std::vector has_undefined; std::vector has_isolates; diff --git a/Explore/GetisOrdMapNewView.cpp b/Explore/GetisOrdMapNewView.cpp index 23add735d..c1ec16122 100644 --- a/Explore/GetisOrdMapNewView.cpp +++ b/Explore/GetisOrdMapNewView.cpp @@ -34,6 +34,8 @@ #include "../DialogTools/PermutationCounterDlg.h" #include "../DialogTools/SaveToTableDlg.h" #include "../DialogTools/VariableSettingsDlg.h" +#include "../DialogTools/RandomizationDlg.h" +#include "../VarCalc/WeightsManInterface.h" #include "ConditionalClusterMapView.h" #include "GStatCoordinator.h" #include "GetisOrdMapNewView.h" @@ -46,25 +48,46 @@ BEGIN_EVENT_TABLE(GetisOrdMapCanvas, MapCanvas) EVT_MOUSE_CAPTURE_LOST(TemplateCanvas::OnMouseCaptureLostEvent) END_EVENT_TABLE() + GetisOrdMapCanvas::GetisOrdMapCanvas(wxWindow *parent, - TemplateFrame* t_frame, - Project* project, - GStatCoordinator* gs_coordinator, - bool is_gi_s, bool is_clust_s, - bool is_perm_s, - bool row_standardize_s, - const wxPoint& pos, - const wxSize& size) + TemplateFrame* t_frame, + Project* project, + GStatCoordinator* gs_coordinator, + bool is_gi_s, bool is_clust_s, + bool is_perm_s, + bool row_standardize_s, + const wxPoint& pos, + const wxSize& size) : MapCanvas(parent, t_frame, project, - std::vector(0), std::vector(0), - CatClassification::no_theme, - no_smoothing, 1, boost::uuids::nil_uuid(), pos, size), + std::vector(0), std::vector(0), + CatClassification::no_theme, + no_smoothing, 1, boost::uuids::nil_uuid(), pos, size), gs_coord(gs_coordinator), is_gi(is_gi_s), is_clust(is_clust_s), is_perm(is_perm_s), row_standardize(row_standardize_s) { - LOG_MSG("Entering GetisOrdMapCanvas::GetisOrdMapCanvas"); - + wxLogMessage("Entering GetisOrdMapCanvas::GetisOrdMapCanvas"); + + str_not_sig = _("Not Significant"); + str_high = _("High"); + str_low = _("Low"); + str_undefined = _("Undefined"); + str_neighborless = _("Neighborless"); + str_p005 = "p = 0.05"; + str_p001 = "p = 0.01"; + str_p0001 = "p = 0.001"; + str_p00001 = "p = 0.0001"; + + SetPredefinedColor(str_not_sig, wxColour(240, 240, 240)); + SetPredefinedColor(str_high, wxColour(255, 0, 0)); + SetPredefinedColor(str_low, wxColour(0, 0, 255)); + SetPredefinedColor(str_undefined, wxColour(70, 70, 70)); + SetPredefinedColor(str_neighborless, wxColour(140, 140, 140)); + SetPredefinedColor(str_p005, wxColour(75, 255, 80)); + SetPredefinedColor(str_p001, wxColour(6, 196, 11)); + SetPredefinedColor(str_p0001, wxColour(3, 116, 6)); + SetPredefinedColor(str_p00001, wxColour(1, 70, 3)); + if (is_clust) { cat_classif_def.cat_classif_type = CatClassification::getis_ord_categories; @@ -80,18 +103,18 @@ row_standardize(row_standardize_s) template_frame->AddGroupDependancy(var_info[t].name); } CreateAndUpdateCategories(); - - LOG_MSG("Exiting GetisOrdMapCanvas::GetisOrdMapCanvas"); + UpdateStatusBar(); + wxLogMessage("Exiting GetisOrdMapCanvas::GetisOrdMapCanvas"); } GetisOrdMapCanvas::~GetisOrdMapCanvas() { - LOG_MSG("In GetisOrdMapCanvas::~GetisOrdMapCanvas"); + wxLogMessage("In GetisOrdMapCanvas::~GetisOrdMapCanvas"); } void GetisOrdMapCanvas::DisplayRightClickMenu(const wxPoint& pos) { - LOG_MSG("Entering GetisOrdMapCanvas::DisplayRightClickMenu"); + wxLogMessage("Entering GetisOrdMapCanvas::DisplayRightClickMenu"); // Workaround for right-click not changing window focus in OSX / wxW 3.0 wxActivateEvent ae(wxEVT_NULL, true, 0, wxActivateEvent::Reason_Mouse); ((GetisOrdMapFrame*) template_frame)->OnActivate(ae); @@ -104,13 +127,16 @@ void GetisOrdMapCanvas::DisplayRightClickMenu(const wxPoint& pos) template_frame->UpdateContextMenuItems(optMenu); template_frame->PopupMenu(optMenu, pos + GetPosition()); template_frame->UpdateOptionMenuItems(); - LOG_MSG("Exiting MapCanvas::DisplayRightClickMenu"); + wxLogMessage("Exiting MapCanvas::DisplayRightClickMenu"); } wxString GetisOrdMapCanvas::GetCanvasTitle() { wxString new_title; - new_title << (is_gi ? "Gi " : "Gi* "); + + if (gs_coord->is_local_joint_count) new_title = "Local Join Count "; + else new_title = (is_gi ? "Gi " : "Gi* "); + new_title << (is_clust ? "Cluster" : "Significance") << " Map "; new_title << "(" << gs_coord->weight_name << "): "; new_title << GetNameWithTime(0); @@ -122,13 +148,20 @@ wxString GetisOrdMapCanvas::GetCanvasTitle() return new_title; } +wxString GetisOrdMapCanvas::GetVariableNames() +{ + wxString new_title; + new_title << GetNameWithTime(0); + return new_title; +} + /** This method definition is empty. It is here to override any call to the parent-class method since smoothing and theme changes are not supported by GetisOrd maps */ bool GetisOrdMapCanvas::ChangeMapType(CatClassification::CatClassifType new_theme, SmoothingType new_smoothing) { - LOG_MSG("In GetisOrdMapCanvas::ChangeMapType"); + wxLogMessage("In GetisOrdMapCanvas::ChangeMapType"); return false; } @@ -152,14 +185,15 @@ void GetisOrdMapCanvas::SetCheckMarks(wxMenu* menu) sig_filter == 3); GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_SIGNIFICANCE_FILTER_0001"), sig_filter == 4); - + GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_SIGNIFICANCE_FILTER_SETUP"), + sig_filter == -1); GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_USE_SPECIFIED_SEED"), gs_coord->IsReuseLastSeed()); } void GetisOrdMapCanvas::TimeChange() { - LOG_MSG("Entering GetisOrdMapCanvas::TimeChange"); + wxLogMessage("Entering GetisOrdMapCanvas::TimeChange"); if (!is_any_sync_with_global_time) return; int cts = project->GetTimeState()->GetCurrTime(); @@ -191,7 +225,7 @@ void GetisOrdMapCanvas::TimeChange() invalidateBms(); PopulateCanvas(); Refresh(); - LOG_MSG("Exiting GetisOrdMapCanvas::TimeChange"); + wxLogMessage("Exiting GetisOrdMapCanvas::TimeChange"); } /** Update Categories based on info in GStatCoordinator */ @@ -209,6 +243,7 @@ void GetisOrdMapCanvas::CreateAndUpdateCategories() int isolates_cat = -1; int num_cats = 0; double stop_sig = 0; + Shapefile::Header& hdr = project->main_data.header; if (gs_coord->GetHasIsolates(t)) { num_cats++; @@ -219,132 +254,182 @@ void GetisOrdMapCanvas::CreateAndUpdateCategories() if (is_clust) { num_cats += 3; - } else { - num_cats += 6-gs_coord->GetSignificanceFilter(); + // in Local Join Count, don't display Low category + if (gs_coord->is_local_joint_count) + num_cats -= 1; - double sig_cutoff = gs_coord->significance_cutoff; + cat_data.CreateCategoriesAtCanvasTm(num_cats, t); + + cat_data.SetCategoryLabel(t, 0, str_not_sig); + cat_data.SetCategoryColor(t, 0, lbl_color_dict[str_not_sig]); + cat_data.SetCategoryLabel(t, 1, str_high); + cat_data.SetCategoryColor(t, 1, lbl_color_dict[str_high]); + + if (!gs_coord->is_local_joint_count) { + cat_data.SetCategoryLabel(t, 2, str_low); + cat_data.SetCategoryColor(t, 2, lbl_color_dict[str_low]); + } + + if (gs_coord->GetHasIsolates(t) && gs_coord->GetHasUndefined(t)) { + isolates_cat = 3 - gs_coord->is_local_joint_count; + undefined_cat = 4 - gs_coord->is_local_joint_count; + } else if (gs_coord->GetHasUndefined(t)) { + undefined_cat = 3 - gs_coord->is_local_joint_count; + } else if (gs_coord->GetHasIsolates(t)) { + isolates_cat = 3 - gs_coord->is_local_joint_count; + } + if (undefined_cat != -1) { + cat_data.SetCategoryLabel(t, undefined_cat, str_undefined); + cat_data.SetCategoryColor(t, undefined_cat, lbl_color_dict[str_undefined]); + } + if (isolates_cat != -1) { + cat_data.SetCategoryLabel(t, isolates_cat, str_neighborless); + cat_data.SetCategoryColor(t, isolates_cat, lbl_color_dict[str_neighborless]); + } + + gs_coord->FillClusterCats(t, is_gi, is_perm, cluster); + + for (int i=0, iend=gs_coord->num_obs; ipermutations; stop_sig = 1.0 / (1.0 + set_perm); + double sig_cutoff = gs_coord->significance_cutoff; + wxString def_cats[4] = {str_p005, str_p001, str_p0001, str_p00001}; + double def_cutoffs[4] = {0.05, 0.01, 0.001, 0.0001}; + + bool is_cust_cutoff = true; + for (int i=0; i<4; i++) { + if (sig_cutoff == def_cutoffs[i]) { + is_cust_cutoff = false; + break; + } + } + + if ( is_cust_cutoff ) { + // if set customized cutoff value + wxString lbl = wxString::Format("p = %g", sig_cutoff); + if ( sig_cutoff > 0.05 ) { + def_cutoffs[0] = sig_cutoff; + lbl_color_dict[lbl] = lbl_color_dict[def_cats[0]]; + def_cats[0] = lbl; + } else { + for (int i = 1; i < 4; i++) { + if (def_cutoffs[i-1] + def_cutoffs[i] < 2 * sig_cutoff){ + lbl_color_dict[lbl] = lbl_color_dict[def_cats[i-1]]; + def_cutoffs[i-1] = sig_cutoff; + def_cats[i-1] = lbl; + break; + } else { + lbl_color_dict[lbl] = lbl_color_dict[def_cats[i]]; + def_cutoffs[i] = sig_cutoff; + def_cats[i] = lbl; + break; + } + } + } + } - if ( sig_cutoff >= 0.0001 && stop_sig > 0.0001) { + num_cats = 5; + for (int j=0; j < 4; j++) { + if (sig_cutoff < def_cutoffs[j]) + num_cats -= 1; + } + + // issue #474 only show significance levels that can be mapped for the given number of permutations, e.g., for 99 it would stop at 0.01, for 999 at 0.001, etc. + if ( sig_cutoff >= def_cutoffs[3] && stop_sig > def_cutoffs[3] ){ //0.0001 num_cats -= 1; } - if ( sig_cutoff >= 0.001 && stop_sig > 0.001 ) { + if ( sig_cutoff >= def_cutoffs[2] && stop_sig > def_cutoffs[2] ){ //0.001 num_cats -= 1; } - if ( sig_cutoff >= 0.01 && stop_sig > 0.01 ) { + if ( sig_cutoff >= def_cutoffs[1] && stop_sig > def_cutoffs[1] ){ //0.01 num_cats -= 1; } - } - cat_data.CreateCategoriesAtCanvasTm(num_cats, t); - - if (is_clust) { - cat_data.SetCategoryLabel(t, 0, "Not Significant"); - cat_data.SetCategoryColor(t, 0, wxColour(240, 240, 240)); - cat_data.SetCategoryLabel(t, 1, "High"); - cat_data.SetCategoryColor(t, 1, wxColour(255, 0, 0)); - cat_data.SetCategoryLabel(t, 2, "Low"); - cat_data.SetCategoryColor(t, 2, wxColour(0, 0, 255)); + cat_data.CreateCategoriesAtCanvasTm(num_cats, t); - if (gs_coord->GetHasIsolates(t) && - gs_coord->GetHasUndefined(t)) - { - isolates_cat = 3; - undefined_cat = 4; - } else if (gs_coord->GetHasUndefined(t)) { - undefined_cat = 3; - } else if (gs_coord->GetHasIsolates(t)) { - isolates_cat = 3; - } + // 0: >0.05 1: 0.05, 2: 0.01, 3: 0.001, 4: 0.0001 + cat_data.SetCategoryLabel(t, 0, str_not_sig); - } else { - // 0: >0.05 1: 0.05, 2: 0.01, 3: 0.001, 4: 0.0001 - int s_f = gs_coord->GetSignificanceFilter(); - cat_data.SetCategoryLabel(t, 0, "Not Significant"); - cat_data.SetCategoryColor(t, 0, wxColour(240, 240, 240)); - - int skip_cat = 0; - if (s_f <=4 && stop_sig <= 0.0001) { - cat_data.SetCategoryLabel(t, 5-s_f, "p = 0.0001"); - cat_data.SetCategoryColor(t, 5-s_f, wxColour(1, 70, 3)); - } else skip_cat++; - if (s_f <= 3 && stop_sig <= 0.001) { - cat_data.SetCategoryLabel(t, 4-s_f, "p = 0.001"); - cat_data.SetCategoryColor(t, 4-s_f, wxColour(3, 116, 6)); - } else skip_cat++; - if (s_f <= 2 && stop_sig <= 0.01) { - cat_data.SetCategoryLabel(t, 3-s_f, "p = 0.01"); - cat_data.SetCategoryColor(t, 3-s_f, wxColour(6, 196, 11)); - } else skip_cat++; + if (hdr.shape_type == Shapefile::POINT_TYP) { + cat_data.SetCategoryColor(t, 0, wxColour(190, 190, 190)); + } else { + cat_data.SetCategoryColor(t, 0, wxColour(240, 240, 240)); + } - if (s_f <= 1) { - cat_data.SetCategoryLabel(t, 2-s_f, "p = 0.05"); - cat_data.SetCategoryColor(t, 2-s_f, wxColour(75, 255, 80)); - } + int cat_idx = 1; + std::map level_cat_dict; + for (int j=0; j < 4; j++) { + if (sig_cutoff >= def_cutoffs[j] && def_cutoffs[j] >= stop_sig) { + cat_data.SetCategoryColor(t, cat_idx, lbl_color_dict[def_cats[j]]); + cat_data.SetCategoryLabel(t, cat_idx, def_cats[j]); + level_cat_dict[j] = cat_idx; + cat_idx += 1; + } + } - if (gs_coord->GetHasIsolates(t) && - gs_coord->GetHasUndefined(t)) - { - isolates_cat = 6-s_f - skip_cat; - undefined_cat = 7-s_f - skip_cat; - } else if (gs_coord->GetHasUndefined(t)) { - undefined_cat = 6-s_f - skip_cat; - } else if (gs_coord->GetHasIsolates(t)) { - isolates_cat = 6-s_f - skip_cat; - } - } - if (undefined_cat != -1) { - cat_data.SetCategoryLabel(t, undefined_cat, "Undefined"); - cat_data.SetCategoryColor(t, undefined_cat, wxColour(70, 70, 70)); - } - if (isolates_cat != -1) { - cat_data.SetCategoryLabel(t, isolates_cat, "Neighborless"); - cat_data.SetCategoryColor(t, isolates_cat, wxColour(140, 140, 140)); + if (gs_coord->GetHasIsolates(t) && + gs_coord->GetHasUndefined(t)) { + isolates_cat = cat_idx++; + undefined_cat = cat_idx++; + + } else if (gs_coord->GetHasUndefined(t)) { + undefined_cat = cat_idx++; + + } else if (gs_coord->GetHasIsolates(t)) { + isolates_cat = cat_idx++; + } + + if (undefined_cat != -1) { + cat_data.SetCategoryLabel(t, undefined_cat, str_undefined); + cat_data.SetCategoryColor(t, undefined_cat, lbl_color_dict[str_undefined]); + } + if (isolates_cat != -1) { + cat_data.SetCategoryLabel(t, isolates_cat, str_neighborless); + cat_data.SetCategoryColor(t, isolates_cat, lbl_color_dict[str_neighborless]); + } + + gs_coord->FillClusterCats(t, is_gi, is_perm, cluster); + double* p = 0; + if (is_gi && is_perm) + p = gs_coord->pseudo_p_vecs[t]; + if (is_gi && !is_perm) + p = gs_coord->p_vecs[t]; + if (!is_gi && is_perm) + p = gs_coord->pseudo_p_star_vecs[t]; + if (!is_gi && !is_perm) + p = gs_coord->p_star_vecs[t]; + + int s_f = gs_coord->GetSignificanceFilter(); + for (int i=0, iend=gs_coord->num_obs; i= 0; c-- ) { + if ( p[i] <= def_cutoffs[c] ) { + cat_data.AppendIdToCategory(t, level_cat_dict[c], i); + break; + } + } + } + } } - gs_coord->FillClusterCats(t, is_gi, is_perm, cluster); - - if (is_clust) { - for (int i=0, iend=gs_coord->num_obs; ipseudo_p_vecs[t]; - if (is_gi && !is_perm) - p_val = gs_coord->p_vecs[t]; - if (!is_gi && is_perm) - p_val = gs_coord->pseudo_p_star_vecs[t]; - if (!is_gi && !is_perm) - p_val = gs_coord->p_star_vecs[t]; - int s_f = gs_coord->GetSignificanceFilter(); - for (int i=0, iend=gs_coord->num_obs; iGetStatusBar(); + } + if (!sb) + return; + wxString s; + s << _("#obs=") << project->GetNumRecords() <<" "; + + if ( highlight_state->GetTotalHighlighted() > 0) { + // for highlight from other windows + s << _("#selected=") << highlight_state->GetTotalHighlighted()<< " "; + } + if (mousemode == select && selectstate == start) { + if (total_hover_obs >= 1) { + s << _("#hover obs ") << hover_obs[0]+1; + } + if (total_hover_obs >= 2) { + s << ", "; + s << _("obs ") << hover_obs[1]+1; + } + if (total_hover_obs >= 3) { + s << ", "; + s << _("obs ") << hover_obs[2]+1; + } + if (total_hover_obs >= 4) { + s << ", ..."; + } + } + if (is_clust && gs_coord) { + double p_val = gs_coord->significance_cutoff; + wxString inf_str = wxString::Format(" p <= %g", p_val); + s << inf_str; + } + sb->SetStatusText(s); +} + void GetisOrdMapCanvas::TimeSyncVariableToggle(int var_index) { - LOG_MSG("In GetisOrdMapCanvas::TimeSyncVariableToggle"); + wxLogMessage("In GetisOrdMapCanvas::TimeSyncVariableToggle"); gs_coord->var_info[var_index].sync_with_global_time = !gs_coord->var_info[var_index].sync_with_global_time; for (int i=0; iAdd(template_canvas, 1, wxEXPAND); rpanel->SetSizer(rbox); + WeightsManInterface* w_man_int = project->GetWManInt(); + ((MapCanvas*) template_canvas)->SetWeightsId(w_man_int->GetDefault()); + wxPanel* lpanel = new wxPanel(splitter_win); template_legend = new MapNewLegend(lpanel, template_canvas, wxPoint(0,0), wxSize(0,0)); wxBoxSizer* lbox = new wxBoxSizer(wxVERTICAL); @@ -450,9 +579,9 @@ row_standardize(row_standardize_s) wxPanel* toolbar_panel = new wxPanel(this,-1, wxDefaultPosition); wxBoxSizer* toolbar_sizer= new wxBoxSizer(wxVERTICAL); - wxToolBar* tb = wxXmlResource::Get()->LoadToolBar(toolbar_panel, "ToolBar_MAP"); + toolbar = wxXmlResource::Get()->LoadToolBar(toolbar_panel, "ToolBar_MAP"); SetupToolbar(); - toolbar_sizer->Add(tb, 0, wxEXPAND|wxALL); + toolbar_sizer->Add(toolbar, 0, wxEXPAND|wxALL); toolbar_panel->SetSizerAndFit(toolbar_sizer); wxBoxSizer* sizer = new wxBoxSizer(wxVERTICAL); @@ -462,15 +591,15 @@ row_standardize(row_standardize_s) SetAutoLayout(true); gs_coord->registerObserver(this); - DisplayStatusBar(true); + SetTitle(template_canvas->GetCanvasTitle()); Show(true); - LOG_MSG("Exiting GetisOrdMapFrame::GetisOrdMapFrame"); + wxLogMessage("Exiting GetisOrdMapFrame::GetisOrdMapFrame"); } GetisOrdMapFrame::~GetisOrdMapFrame() { - LOG_MSG("In GetisOrdMapFrame::~GetisOrdMapFrame"); + wxLogMessage("In GetisOrdMapFrame::~GetisOrdMapFrame"); if (gs_coord) { gs_coord->removeObserver(this); gs_coord = 0; @@ -479,7 +608,7 @@ GetisOrdMapFrame::~GetisOrdMapFrame() void GetisOrdMapFrame::OnActivate(wxActivateEvent& event) { - LOG_MSG("In GetisOrdMapFrame::OnActivate"); + wxLogMessage("In GetisOrdMapFrame::OnActivate"); if (event.GetActive()) { RegisterAsActive("GetisOrdMapFrame", GetTitle()); } @@ -488,7 +617,7 @@ void GetisOrdMapFrame::OnActivate(wxActivateEvent& event) void GetisOrdMapFrame::MapMenus() { - LOG_MSG("In GetisOrdMapFrame::MapMenus"); + wxLogMessage("In GetisOrdMapFrame::MapMenus"); wxMenuBar* mb = GdaFrame::GetGdaFrame()->GetMenuBar(); // Map Options Menus wxMenu* optMenu = wxXmlResource::Get()-> @@ -496,7 +625,7 @@ void GetisOrdMapFrame::MapMenus() ((MapCanvas*) template_canvas)-> AddTimeVariantOptionsToMenu(optMenu); ((MapCanvas*) template_canvas)->SetCheckMarks(optMenu); - GeneralWxUtils::ReplaceMenu(mb, "Options", optMenu); + GeneralWxUtils::ReplaceMenu(mb, _("Options"), optMenu); UpdateOptionMenuItems(); } @@ -504,7 +633,7 @@ void GetisOrdMapFrame::UpdateOptionMenuItems() { TemplateFrame::UpdateOptionMenuItems(); // set common items first wxMenuBar* mb = GdaFrame::GetGdaFrame()->GetMenuBar(); - int menu = mb->FindMenu("Options"); + int menu = mb->FindMenu(_("Options")); if (menu == wxNOT_FOUND) { LOG_MSG("GetisOrdMapFrame::UpdateOptionMenuItems: " "Options menu not found"); @@ -558,7 +687,11 @@ void GetisOrdMapFrame::OnRanOtherPer(wxCommandEvent& event) PermutationCounterDlg dlg(this); if (dlg.ShowModal() == wxID_OK) { long num; - dlg.m_number->GetValue().ToLong(&num); + wxString input = dlg.m_number->GetValue(); + + wxLogMessage(input); + + input.ToLong(&num); RanXPer(num); } } @@ -584,6 +717,9 @@ void GetisOrdMapFrame::OnSpecifySeedDlg(wxCommandEvent& event) wxTextEntryDialog dlg(NULL, m, "\nEnter a seed value", cur_val); if (dlg.ShowModal() != wxID_OK) return; dlg_val = dlg.GetValue(); + + wxLogMessage(dlg_val); + dlg_val.Trim(true); dlg_val.Trim(false); if (dlg_val.IsEmpty()) return; @@ -594,14 +730,15 @@ void GetisOrdMapFrame::OnSpecifySeedDlg(wxCommandEvent& event) } else { wxString m; m << "\"" << dlg_val << "\" is not a valid seed. Seed unchanged."; - wxMessageDialog dlg(NULL, m, "Error", wxOK | wxICON_ERROR); + wxMessageDialog dlg(NULL, m, _("Error"), wxOK | wxICON_ERROR); dlg.ShowModal(); } } void GetisOrdMapFrame::SetSigFilterX(int filter) { - if (filter == gs_coord->GetSignificanceFilter()) return; + if (filter == gs_coord->GetSignificanceFilter()) + return; gs_coord->SetSignificanceFilter(filter); gs_coord->notifyObservers(); UpdateOptionMenuItems(); @@ -627,6 +764,69 @@ void GetisOrdMapFrame::OnSigFilter0001(wxCommandEvent& event) SetSigFilterX(4); } +void GetisOrdMapFrame::OnSigFilterSetup(wxCommandEvent& event) +{ + GetisOrdMapCanvas* lc = (GetisOrdMapCanvas*)template_canvas; + int t = template_canvas->cat_data.GetCurrentCanvasTmStep(); + double* p_val_t; + if (map_type == Gi_clus_perm || map_type == Gi_sig_perm) { + p_val_t = gs_coord->pseudo_p_vecs[t]; + } else if (map_type == Gi_clus_norm || map_type == Gi_sig_norm) { + p_val_t = gs_coord->p_vecs[t]; + } else if (map_type == GiStar_clus_perm || map_type == GiStar_sig_perm) { + p_val_t = gs_coord->pseudo_p_star_vecs[t]; + } else { // (map_type == GiStar_clus_norm || map_type == GiStar_sig_norm) + p_val_t = gs_coord->p_star_vecs[t]; + } + int n = gs_coord->num_obs; + + wxString ttl = _("Inference Settings"); + ttl << " (" << gs_coord->permutations << " perm)"; + + double user_sig = gs_coord->significance_cutoff; + if (gs_coord->GetSignificanceFilter()<0) user_sig = gs_coord->user_sig_cutoff; + + if (gs_coord->is_local_joint_count) { + int new_n = 0; + for (int i=0; inum_obs; i++) { + if (gs_coord->x_vecs[t][i] == 1) { + new_n += 1; + } + } + int j= 0; + double* p_val = new double[new_n]; + for (int i=0; inum_obs; i++) { + if (gs_coord->x_vecs[t][i] == 1) { + p_val[j++] = p_val_t[i]; + } + } + InferenceSettingsDlg dlg(this, user_sig, p_val, new_n, ttl); + if (dlg.ShowModal() == wxID_OK) { + gs_coord->SetSignificanceFilter(-1); + gs_coord->significance_cutoff = dlg.GetAlphaLevel(); + gs_coord->user_sig_cutoff = dlg.GetUserInput(); + gs_coord->notifyObservers(); + gs_coord->bo = dlg.GetBO(); + gs_coord->fdr = dlg.GetFDR(); + UpdateOptionMenuItems(); + } + delete[] p_val; + } else { + InferenceSettingsDlg dlg(this, user_sig, p_val_t, n, ttl); + if (dlg.ShowModal() == wxID_OK) { + gs_coord->SetSignificanceFilter(-1); + gs_coord->significance_cutoff = dlg.GetAlphaLevel(); + gs_coord->user_sig_cutoff = dlg.GetUserInput(); + gs_coord->notifyObservers(); + gs_coord->bo = dlg.GetBO(); + gs_coord->fdr = dlg.GetFDR(); + UpdateOptionMenuItems(); + } + } +} + + + void GetisOrdMapFrame::OnSaveGetisOrd(wxCommandEvent& event) { int t = template_canvas->cat_data.GetCurrentCanvasTmStep(); @@ -651,6 +851,12 @@ void GetisOrdMapFrame::OnSaveGetisOrd(wxCommandEvent& event) wxString g_label = is_gi ? "G" : "G*"; wxString g_field_default = is_gi ? "G" : "G_STR"; + + if (gs_coord->is_local_joint_count) { + title = "Save Results: Local Join Count-stats"; + g_label = "JC"; + g_field_default = "JC"; + } std::vector c_val; gs_coord->FillClusterCats(t, is_gi, is_perm, c_val); @@ -678,28 +884,34 @@ void GetisOrdMapFrame::OnSaveGetisOrd(wxCommandEvent& event) } for (int i=0; inum_obs; i++) p_val[i] = p_val_t[i]; - std::vector data(is_perm ? 3 : 4); + int num_data = is_perm ? 3: 4; + // drop C_ID for local JC, add NN and NN_1 + std::vector data(num_data); std::vector undefs(gs_coord->num_obs, false); + std::vector c_undefs(gs_coord->num_obs, true); for (size_t i=0; ix_undefs.size(); i++) { for (size_t j=0; jx_undefs[i].size(); j++) { undefs[j] = undefs[j] || gs_coord->x_undefs[i][j]; } } + int data_i = 0; + std::vector nn_1_val; - int data_i = 0; - data[data_i].d_val = &g_val; - data[data_i].label = g_label; - data[data_i].field_default = g_field_default; - data[data_i].type = GdaConst::double_type; - data[data_i].undefined = &undefs; - data_i++; - data[data_i].l_val = &c_val; - data[data_i].label = c_label; - data[data_i].field_default = c_field_default; - data[data_i].type = GdaConst::long64_type; - data[data_i].undefined = &undefs; - data_i++; + if (gs_coord->is_local_joint_count == false) { + data[data_i].d_val = &g_val; + data[data_i].label = g_label; + data[data_i].field_default = g_field_default; + data[data_i].type = GdaConst::double_type; + data[data_i].undefined = &undefs; + data_i++; + data[data_i].l_val = &c_val; + data[data_i].label = c_label; + data[data_i].field_default = c_field_default; + data[data_i].type = GdaConst::long64_type; + data[data_i].undefined = &undefs; + data_i++; + } if (!is_perm) { data[data_i].d_val = &z_val; data[data_i].label = "z-score"; @@ -708,12 +920,46 @@ void GetisOrdMapFrame::OnSaveGetisOrd(wxCommandEvent& event) data[data_i].undefined = &undefs; data_i++; } - data[data_i].d_val = &p_val; - data[data_i].label = p_label; - data[data_i].field_default = p_field_default; - data[data_i].type = GdaConst::double_type; - data[data_i].undefined = &undefs; - data_i++; + if (gs_coord->is_local_joint_count == false) { + data[data_i].d_val = &p_val; + data[data_i].label = p_label; + data[data_i].field_default = p_field_default; + data[data_i].type = GdaConst::double_type; + data[data_i].undefined = &undefs; + data_i++; + } else { + + + for (int i=0; inum_obs; i++) { + nn_1_val.push_back( gs_coord->num_neighbors_1[t][i]); + } + + data[data_i].l_val = &nn_1_val; + data[data_i].label = g_label; + data[data_i].field_default = g_field_default; + data[data_i].type = GdaConst::long64_type; + data[data_i].undefined = &undefs; + data_i++; + + data[data_i].l_val = &gs_coord->num_neighbors; + data[data_i].label = "Number of Neighbors"; + data[data_i].field_default = "NN"; + data[data_i].type = GdaConst::long64_type; + data[data_i].undefined = &undefs; + data_i++; + + for (size_t i=0; inum_obs; i++) { + if (gs_coord->num_neighbors_1[t][i] > 0 && + gs_coord->x_vecs[t][i] == 1) + c_undefs[i] = false; + } + data[data_i].d_val = &p_val; + data[data_i].label = p_label; + data[data_i].field_default = p_field_default; + data[data_i].type = GdaConst::double_type; + data[data_i].undefined = &c_undefs; + data_i++; + } SaveToTableDlg dlg(project, this, data, title, wxDefaultPosition, wxSize(400,400)); @@ -743,7 +989,7 @@ void GetisOrdMapFrame::CoreSelectHelper(const std::vector& elem) void GetisOrdMapFrame::OnSelectCores(wxCommandEvent& event) { - LOG_MSG("Entering GetisOrdMapFrame::OnSelectCores"); + wxLogMessage("Entering GetisOrdMapFrame::OnSelectCores"); std::vector elem(gs_coord->num_obs, false); int ts = template_canvas->cat_data.GetCurrentCanvasTmStep(); @@ -756,12 +1002,12 @@ void GetisOrdMapFrame::OnSelectCores(wxCommandEvent& event) } CoreSelectHelper(elem); - LOG_MSG("Exiting GetisOrdMapFrame::OnSelectCores"); + wxLogMessage("Exiting GetisOrdMapFrame::OnSelectCores"); } void GetisOrdMapFrame::OnSelectNeighborsOfCores(wxCommandEvent& event) { - LOG_MSG("Entering GetisOrdMapFrame::OnSelectNeighborsOfCores"); + wxLogMessage("Entering GetisOrdMapFrame::OnSelectNeighborsOfCores"); std::vector elem(gs_coord->num_obs, false); int ts = template_canvas->cat_data.GetCurrentCanvasTmStep(); @@ -786,12 +1032,12 @@ void GetisOrdMapFrame::OnSelectNeighborsOfCores(wxCommandEvent& event) } CoreSelectHelper(elem); - LOG_MSG("Exiting GetisOrdMapFrame::OnSelectNeighborsOfCores"); + wxLogMessage("Exiting GetisOrdMapFrame::OnSelectNeighborsOfCores"); } void GetisOrdMapFrame::OnSelectCoresAndNeighbors(wxCommandEvent& event) { - LOG_MSG("Entering GetisOrdMapFrame::OnSelectCoresAndNeighbors"); + wxLogMessage("Entering GetisOrdMapFrame::OnSelectCoresAndNeighbors"); std::vector elem(gs_coord->num_obs, false); int ts = template_canvas->cat_data.GetCurrentCanvasTmStep(); @@ -810,43 +1056,7 @@ void GetisOrdMapFrame::OnSelectCoresAndNeighbors(wxCommandEvent& event) } CoreSelectHelper(elem); - LOG_MSG("Exiting GetisOrdMapFrame::OnSelectCoresAndNeighbors"); -} - -void GetisOrdMapFrame::OnAddNeighborToSelection(wxCommandEvent& event) -{ - int ts = template_canvas->cat_data.GetCurrentCanvasTmStep(); - GalWeight* gal_weights = gs_coord->Gal_vecs_orig[ts]; - - HighlightState& hs = *project->GetHighlightState(); - std::vector& h = hs.GetHighlight(); - int nh_cnt = 0; - std::vector add_elem(gal_weights->num_obs, false); - - std::vector new_highlight_ids; - - for (int i=0; inum_obs; i++) { - if (h[i]) { - GalElement& e = gal_weights->gal[i]; - for (int j=0, jend=e.Size(); j 0) { - hs.SetEventType(HLStateInt::delta); - hs.notifyObservers(); - } + wxLogMessage("Exiting GetisOrdMapFrame::OnSelectCoresAndNeighbors"); } void GetisOrdMapFrame::OnShowAsConditionalMap(wxCommandEvent& event) @@ -883,11 +1093,12 @@ void GetisOrdMapFrame::update(GStatCoordinator* o) if (template_legend) template_legend->Recreate(); SetTitle(lc->GetCanvasTitle()); lc->Refresh(); + lc->UpdateStatusBar(); } void GetisOrdMapFrame::closeObserver(GStatCoordinator* o) { - LOG_MSG("In GetisOrdMapFrame::closeObserver(GStatCoordinator*)"); + wxLogMessage("In GetisOrdMapFrame::closeObserver(GStatCoordinator*)"); if (gs_coord) { gs_coord->removeObserver(this); gs_coord = 0; diff --git a/Explore/GetisOrdMapNewView.h b/Explore/GetisOrdMapNewView.h index 994e86b9a..610ccac2c 100644 --- a/Explore/GetisOrdMapNewView.h +++ b/Explore/GetisOrdMapNewView.h @@ -20,6 +20,7 @@ #ifndef __GEODA_CENTER_GETIS_ORD_MAP_NEW_VIEW_H__ #define __GEODA_CENTER_GETIS_ORD_MAP_NEW_VIEW_H__ +#include #include "../GdaConst.h" #include "MapNewView.h" @@ -40,6 +41,7 @@ class GetisOrdMapCanvas : public MapCanvas virtual ~GetisOrdMapCanvas(); virtual void DisplayRightClickMenu(const wxPoint& pos); virtual wxString GetCanvasTitle(); + virtual wxString GetVariableNames(); virtual bool ChangeMapType(CatClassification::CatClassifType new_map_theme, SmoothingType new_map_smoothing); virtual void SetCheckMarks(wxMenu* menu); @@ -47,6 +49,11 @@ class GetisOrdMapCanvas : public MapCanvas void SyncVarInfoFromCoordinator(); virtual void CreateAndUpdateCategories(); virtual void TimeSyncVariableToggle(int var_index); + virtual void UpdateStatusBar(); + virtual void SetWeightsId(boost::uuids::uuid id) { weights_id = id; } + + double bo; + double fdr; protected: GStatCoordinator* gs_coord; @@ -55,6 +62,16 @@ class GetisOrdMapCanvas : public MapCanvas bool is_perm; // true = pseudo-p-val, false = normal distribution p-val bool row_standardize; // true = row standardize, false = binary + wxString str_not_sig; + wxString str_high; + wxString str_low; + wxString str_undefined; + wxString str_neighborless; + wxString str_p005; + wxString str_p001; + wxString str_p0001; + wxString str_p00001; + DECLARE_EVENT_TABLE() }; @@ -86,6 +103,7 @@ class GetisOrdMapFrame : public MapFrame virtual void MapMenus(); virtual void UpdateOptionMenuItems(); virtual void UpdateContextMenuItems(wxMenu* menu); + virtual void update(WeightsManState* o){} void RanXPer(int permutation); void OnRan99Per(wxCommandEvent& event); @@ -102,14 +120,14 @@ class GetisOrdMapFrame : public MapFrame void OnSigFilter01(wxCommandEvent& event); void OnSigFilter001(wxCommandEvent& event); void OnSigFilter0001(wxCommandEvent& event); + void OnSigFilterSetup(wxCommandEvent& event); void OnSaveGetisOrd(wxCommandEvent& event); void OnSelectCores(wxCommandEvent& event); void OnSelectNeighborsOfCores(wxCommandEvent& event); void OnSelectCoresAndNeighbors(wxCommandEvent& event); - void OnAddNeighborToSelection(wxCommandEvent& event); - + void OnShowAsConditionalMap(wxCommandEvent& event); virtual void update(GStatCoordinator* o); diff --git a/Explore/HistogramView.cpp b/Explore/HistogramView.cpp index 9a2fc00e2..6694f6c86 100644 --- a/Explore/HistogramView.cpp +++ b/Explore/HistogramView.cpp @@ -41,7 +41,6 @@ #include "../GeoDa.h" #include "../Project.h" #include "../FramesManager.h" -#include "../ShapeOperations/ShapeUtils.h" #include "CatClassifManager.h" #include "CatClassifState.h" #include "HistogramView.h" @@ -90,41 +89,72 @@ custom_classif_state(0), is_custom_category(false) data_stats.resize(col_time_steps); hinge_stats.resize(col_time_steps); data_sorted.resize(col_time_steps); + s_data_sorted.resize(col_time_steps); + + min_ival_val.resize(col_time_steps); + max_ival_val.resize(col_time_steps); + max_num_obs_in_ival.resize(col_time_steps); + ival_to_obs_ids.resize(col_time_steps); + VAR_STRING.resize(col_time_steps); bool has_init = false; for (int t=0; t sel_data; std::vector sel_undefs; - table_int->GetColData(col_id, t, sel_data); table_int->GetColUndefined(col_id, t, sel_undefs); undef_tms.push_back(sel_undefs); - data_sorted[t].resize(num_obs); - // data_sorted is a pair value {double value: index} - for (int i=0; iGetColType(col_id, t); + IS_VAR_STRING.push_back(f_type == GdaConst::string_type); - data_stats[t].CalculateFromSample(data_sorted[t], sel_undefs); - hinge_stats[t].CalculateHingeStats(data_sorted[t], sel_undefs); - - if (!has_init) { - data_min_over_time = data_stats[t].min; - data_max_over_time = data_stats[t].max; - has_init = true; + if (f_type == GdaConst::string_type) { + std::vector sel_data; + table_int->GetColData(col_id, t, sel_data); + s_data_sorted[t].resize(num_obs); + std::map unique_dict; + // data_sorted is a pair value {string value: index} + for (int i=0; i sel_data; + table_int->GetColData(col_id, t, sel_data); + data_sorted[t].resize(num_obs); + // data_sorted is a pair value {double value: index} + for (int i=0; i data_max_over_time) { + // sort data_sorted by value + std::sort(data_sorted[t].begin(),data_sorted[t].end(),Gda::dbl_int_pair_cmp_less); + + data_stats[t].CalculateFromSample(data_sorted[t], sel_undefs); + hinge_stats[t].CalculateHingeStats(data_sorted[t], sel_undefs); + + if (!has_init) { + data_min_over_time = data_stats[t].min; data_max_over_time = data_stats[t].max; + has_init = true; + } else { + // get min max values + if (data_stats[t].min < data_min_over_time) { + data_min_over_time = data_stats[t].min; + } + if (data_stats[t].max > data_max_over_time) { + data_max_over_time = data_stats[t].max; + } } + max_intervals = std::min(MAX_INTERVALS, num_obs); + cur_intervals = std::min(max_intervals, default_intervals); } } @@ -135,20 +165,6 @@ custom_classif_state(0), is_custom_category(false) } obs_id_to_ival.resize(boost::extents[col_time_steps][num_obs]); - max_intervals = GenUtils::min(MAX_INTERVALS, num_obs); - cur_intervals = GenUtils::min(max_intervals, default_intervals); - /* - if (num_obs > 49) { - int c = sqrt((double) num_obs); - cur_intervals = GenUtils::min(max_intervals, c); - cur_intervals = GenUtils::min(cur_intervals, 25); - } - */ - min_ival_val.resize(col_time_steps); - max_ival_val.resize(col_time_steps); - max_num_obs_in_ival.resize(col_time_steps); - ival_to_obs_ids.resize(col_time_steps); - highlight_color = GdaConst::highlight_color; last_scale_trans.SetFixedAspectRatio(false); @@ -223,6 +239,10 @@ void HistogramCanvas::AddTimeVariantOptionsToMenu(wxMenu* menu) int HistogramCanvas::AddClassificationOptionsToMenu(wxMenu* menu, CatClassifManager* ccm) { + if (!IS_VAR_STRING.empty()) { + if(IS_VAR_STRING[0]) + return 0; + } std::vector titles; ccm->GetTitles(titles); @@ -236,7 +256,7 @@ int HistogramCanvas::AddClassificationOptionsToMenu(wxMenu* menu, CatClassifMana wxMenuItem* mi = menu2->Append(xrcid_hist_classification+j+1, titles[j]); } s = _("Histogram Classification"); - menu->Prepend(wxID_ANY, s, menu2, s); + menu->Insert(1, wxID_ANY, s, menu2, s); return titles.size(); } @@ -297,6 +317,12 @@ void HistogramCanvas::SetCheckMarks(wxMenu* menu) IsDisplayStats()); GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_SHOW_AXES"), IsShowAxes()); + + int t = var_info[0].time; + + GeneralWxUtils::EnableMenuItem(menu, XRCID("ID_DISPLAY_STATISTICS"), !IS_VAR_STRING[t]); + GeneralWxUtils::EnableMenuItem(menu, XRCID("ID_HISTOGRAM_INTERVALS"), !IS_VAR_STRING[t]); + if (var_info[0].is_time_variant) { GeneralWxUtils::CheckMenuItem(menu, @@ -384,19 +410,18 @@ void HistogramCanvas::UpdateSelection(bool shiftdown, bool pointsel) } } if ( selection_changed ) { - highlight_state->SetEventType(HLStateInt::delta); - highlight_state->notifyObservers(this); - } - - if ( selection_changed ) { + int total_highlighted = 0; // used for MapCanvas::Drawlayer1 + for (int i=0; iSetTotalHighlighted(total_highlighted); + highlight_timer->Start(50); + // re-paint highlight layer (layer1_bm) layer1_valid = false; UpdateIvalSelCnts(); DrawLayers(); - } Refresh(); - UpdateStatusBar(); + UpdateStatusBar(); } void HistogramCanvas::DrawSelectableShapes(wxMemoryDC &dc) @@ -441,9 +466,7 @@ void HistogramCanvas::update(HLStateInt* o) ResetFadedLayer(); } - //layer0_valid = false; layer1_valid = false; - //layer2_valid = false; UpdateIvalSelCnts(); Refresh(); @@ -457,6 +480,13 @@ wxString HistogramCanvas::GetCanvasTitle() return s; } +wxString HistogramCanvas::GetVariableNames() +{ + wxString s; + s << GetNameWithTime(0); + return s; +} + wxString HistogramCanvas::GetNameWithTime(int var) { if (var < 0 || var >= var_info.size()) return wxEmptyString; @@ -533,13 +563,16 @@ void HistogramCanvas::PopulateCanvas() interval_gap_const * (cur_intervals-1); double y_min = 0; double y_max = scale_y_over_time ? overall_max_num_obs_in_ival : max_num_obs_in_ival[time]; + + // some exceptional case: e.g. variable is not valid + if (y_min == 0 && y_max == 0) return; last_scale_trans.SetData(x_min, y_min, x_max, y_max); if (show_axes) { axis_scale_y = AxisScale(0, y_max, 5, axis_display_precision); y_max = axis_scale_y.scale_max; - y_axis = new GdaAxis("Frequency", axis_scale_y, + y_axis = new GdaAxis(_("Frequency"), axis_scale_y, wxRealPoint(0,0), wxRealPoint(0, y_max), -9, 0); foreground_shps.push_back(y_axis); @@ -581,13 +614,24 @@ void HistogramCanvas::PopulateCanvas() tic_str << axis_scale_x.data_min; axis_scale_x.tics_str[i] = tic_str; - GdaShapeText* brk = - new GdaShapeText(GenUtils::DblToStr(axis_scale_x.data_min, - axis_display_precision), - *GdaConst::small_font, - wxRealPoint(x0, y0), 0, - GdaShapeText::h_center, - GdaShapeText::v_center, 0, 25); + GdaShapeText* brk; + if (IS_VAR_STRING[time]) + brk = + new GdaShapeText("", + *GdaConst::small_font, + wxRealPoint(x0 /2.0 + x1 /2.0, y0), 0, + GdaShapeText::h_center, + GdaShapeText::v_center, 0, 25); + + else + brk = + new GdaShapeText(GenUtils::DblToStr(axis_scale_x.data_min, + axis_display_precision), + *GdaConst::small_font, + wxRealPoint(x0, y0), 0, + GdaShapeText::h_center, + GdaShapeText::v_center, 0, 25); + foreground_shps.push_back(brk); } if (isetNudge(0, 10); foreground_shps.push_back(xdline); @@ -646,11 +708,11 @@ void HistogramCanvas::PopulateCanvas() int cols = 1; int rows = 5; std::vector vals(rows); - vals[0] << "from"; - vals[1] << "to"; - vals[2] << "#obs"; - vals[3] << "% of total"; - vals[4] << "sd from mean"; + vals[0] << _("from"); + vals[1] << _("to"); + vals[2] << _("#obs"); + vals[3] << _("% of total"); + vals[4] << _("sd from mean"); std::vector attribs(0); // undefined s = new GdaShapeTable(vals, attribs, rows, cols, *GdaConst::small_font, @@ -662,6 +724,11 @@ void HistogramCanvas::PopulateCanvas() wxClientDC dc(this); ((GdaShapeTable*) s)->GetSize(dc, table_w, table_h); + // get row gap in multi-language case + wxSize sz_0 = dc.GetTextExtent(vals[0]); + wxSize sz_1 = dc.GetTextExtent("0.0"); + int row_gap = 3 + sz_0.GetHeight() - sz_1.GetHeight(); + for (int i=0; i vals(rows); @@ -689,17 +756,17 @@ void HistogramCanvas::PopulateCanvas() wxRealPoint(orig_x_pos[i], 0), GdaShapeText::h_center, GdaShapeText::top, GdaShapeText::h_center, GdaShapeText::v_center, - 3, 10, 0, 53+y_d); + row_gap, 10, 0, 53+y_d); foreground_shps.push_back(s); } wxString sts; - sts << "min: " << data_stats[time].min; - sts << ", max: " << data_stats[time].max; - sts << ", median: " << hinge_stats[time].Q2; - sts << ", mean: " << data_stats[time].mean; - sts << ", s.d.: " << data_stats[time].sd_with_bessel; - sts << ", #obs: " << num_obs; + sts << _("min:") << " " << data_stats[time].min; + sts << ", " << _("max:") << " " << data_stats[time].max; + sts << ", " << _("median:") << " " << hinge_stats[time].Q2; + sts << ", " << _("mean:") << " " << data_stats[time].mean; + sts << ", " << _("s.d.:") << " " << data_stats[time].sd_with_bessel; + sts << ", " << _("#obs:") << " " << num_obs; s = new GdaShapeText(sts, *GdaConst::small_font, wxRealPoint(x_max/2.0, 0), 0, @@ -731,7 +798,7 @@ void HistogramCanvas::PopulateCanvas() double x1 = orig_x_pos_right[i]; double y0 = 0; double y1 = ival_obs_cnt[time][i]; - selectable_shps[i] = new GdaRectangle(wxRealPoint(x0, 0), + selectable_shps[i] = new GdaRectangle(wxRealPoint(x0, y0), wxRealPoint(x1, y1)); if (!is_custom_category) { @@ -868,6 +935,7 @@ void HistogramCanvas::InitIntervals() std::vector& hs = highlight_state->GetHighlight(); int ts = obs_id_to_ival.shape()[0]; + s_ival_breaks.resize(boost::extents[ts][cur_intervals]); ival_breaks.resize(boost::extents[ts][cur_intervals-1]); ival_obs_cnt.resize(boost::extents[ts][cur_intervals]); ival_obs_sel_cnt.resize(boost::extents[ts][cur_intervals]); @@ -886,82 +954,134 @@ void HistogramCanvas::InitIntervals() } for (int t=0; t& undefs = undef_tms[t]; - bool has_init = false; - for (size_t ii=0; ii unique_dict; + // data_sorted is a pair value {string value: index} + for (int i=0; i::iterator it; + for (it=unique_dict.begin(); it!=unique_dict.end();it++){ + wxString lbl = it->first; + for (int idx=0; idx min_ival_val[t] ) { + } + cur_ival += 1; + } + } else { + if (scale_x_over_time) { + min_ival_val[t] = data_min_over_time; + max_ival_val[t] = data_max_over_time; + } else { + const std::vector& undefs = undef_tms[t]; + bool has_init = false; + for (size_t ii=0; ii min_ival_val[t]) { + max_ival_val[t] = val; + } } } } - } - if (min_ival_val[t] == max_ival_val[t]) { - if (min_ival_val[t] == 0) { - max_ival_val[t] = 1; - } else { - max_ival_val[t] += fabs(max_ival_val[t])/2.0; - } - } - double range = max_ival_val[t] - min_ival_val[t]; - double ival_size = range/((double) cur_intervals); - - if (!is_custom_category) { - cat_classif_def.breaks.resize(cur_intervals-1); - for (int i=0; i& undefs = undef_tms[t]; + + if (!is_custom_category) { + cat_classif_def.breaks.resize(cur_intervals-1); + for (int i=0; i& data_item = data_sorted[t][i]; + double val = data_item.first; + int idx = data_item.second; + if (undefs[idx]) + continue; + // detect if need to jump to next interval + while (cur_ival <= cur_intervals-2 && + val >= ival_breaks[t][cur_ival]) + { + cur_ival++; + } + // add current [id] to ival_to_obs_ids + ival_to_obs_ids[t][cur_ival].push_front(idx); + obs_id_to_ival[t][idx] = cur_ival; + ival_obs_cnt[t][cur_ival]++; + + if (hs[data_sorted[t][i].second]) { + ival_obs_sel_cnt[t][cur_ival]++; + } + } + } else { + for (int i=0; i& data_item = data_sorted[t][i]; + double val = data_item.first; + int idx = data_item.second; + if (undefs[idx]) continue; + // detect if need to jump to next interval + if (cur_ival <= cur_intervals-2) { + if ( (cur_ival == num_breaks_lower &&val > ival_breaks[t][cur_ival]) || (cur_ival != num_breaks_lower &&val >= ival_breaks[t][cur_ival]) ) + cur_ival++; + } + // add current [id] to ival_to_obs_ids + ival_to_obs_ids[t][cur_ival].push_front(idx); + obs_id_to_ival[t][idx] = cur_ival; + ival_obs_cnt[t][cur_ival]++; + + if (hs[data_sorted[t][i].second]) { + ival_obs_sel_cnt[t][cur_ival]++; + } + } } } + } - const std::vector& undefs = undef_tms[t]; - - for (int i=0, cur_ival=0; i& data_item = data_sorted[t][i]; - double val = data_item.first; - int idx = data_item.second; - - if (undefs[idx]) - continue; - - // detect if need to jump to next interval - while (cur_ival <= cur_intervals-2 && - val >= ival_breaks[t][cur_ival]) - { - cur_ival++; - } - - // add current [id] to ival_to_obs_ids - ival_to_obs_ids[t][cur_ival].push_front(idx); - obs_id_to_ival[t][idx] = cur_ival; - ival_obs_cnt[t][cur_ival]++; - - if (hs[data_sorted[t][i].second]) { - ival_obs_sel_cnt[t][cur_ival]++; - } - } - } overall_max_num_obs_in_ival = 0; for (int t=0; tGetTotalHighlighted()> 0) { int n_total_hl = highlight_state->GetTotalHighlighted(); - s << "#selected=" << n_total_hl << " "; + s << _("#selected=") << n_total_hl << " "; int n_undefs = 0; for (int i=0; i 0) { - s << "(undefined:" << n_undefs << ") "; + s << _("undefined: ") << n_undefs << ") "; } } sb->SetStatusText(s); return; } + + if (ival-1 >= ival_breaks[t].size()) return; wxString s; double ival_min = (ival == 0) ? min_ival_val[t] : ival_breaks[t][ival-1]; @@ -1151,7 +1275,7 @@ void HistogramFrame::MapMenus() ((HistogramCanvas*) template_canvas)->AddClassificationOptionsToMenu(optMenu, project->GetCatClassifManager()); ((HistogramCanvas*) template_canvas)->SetCheckMarks(optMenu); - GeneralWxUtils::ReplaceMenu(mb, "Options", optMenu); + GeneralWxUtils::ReplaceMenu(mb, _("Options"), optMenu); UpdateOptionMenuItems(); } @@ -1159,7 +1283,7 @@ void HistogramFrame::UpdateOptionMenuItems() { TemplateFrame::UpdateOptionMenuItems(); // set common items first wxMenuBar* mb = GdaFrame::GetGdaFrame()->GetMenuBar(); - int menu = mb->FindMenu("Options"); + int menu = mb->FindMenu(_("Options")); if (menu == wxNOT_FOUND) { } else { ((HistogramCanvas*) template_canvas)->SetCheckMarks(mb->GetMenu(menu)); diff --git a/Explore/HistogramView.h b/Explore/HistogramView.h index 879a9219b..f76e80562 100644 --- a/Explore/HistogramView.h +++ b/Explore/HistogramView.h @@ -34,6 +34,7 @@ class HistogramCanvas; class HistogramFrame; +typedef boost::multi_array s_array_type; typedef boost::multi_array d_array_type; typedef boost::multi_array i_array_type; @@ -53,6 +54,7 @@ class HistogramCanvas : public TemplateCanvas, public CatClassifStateObserver virtual void AddTimeVariantOptionsToMenu(wxMenu* menu); virtual void update(HLStateInt* o); virtual wxString GetCanvasTitle(); + virtual wxString GetVariableNames(); virtual wxString GetNameWithTime(int var); virtual void SetCheckMarks(wxMenu* menu); virtual void DetermineMouseHoverObjects(wxPoint pt); @@ -100,13 +102,17 @@ class HistogramCanvas : public TemplateCanvas, public CatClassifStateObserver int cur_intervals; std::vector var_info; -protected: virtual void UpdateStatusBar(); + +protected: int num_obs; int num_time_vals; int ref_var_index; + std::vector IS_VAR_STRING; + std::vector > VAR_STRING; + std::vector s_data_sorted; std::vector data_sorted; std::vector data_stats; std::vector hinge_stats; @@ -123,6 +129,7 @@ class HistogramCanvas : public TemplateCanvas, public CatClassifStateObserver bool show_axes; bool display_stats; + s_array_type s_ival_breaks; double data_min_over_time; double data_max_over_time; d_array_type ival_breaks; // size = time_steps * cur_num_intervals-1 diff --git a/Explore/LineChartCanvas.cpp b/Explore/LineChartCanvas.cpp index b221302e5..c601de697 100644 --- a/Explore/LineChartCanvas.cpp +++ b/Explore/LineChartCanvas.cpp @@ -57,7 +57,7 @@ LineChartCanvas::LineChartCanvas(wxWindow *parent, TemplateFrame* t_frame, : TemplateCanvas(parent, t_frame, project, project->GetHighlightState(), pos, size, false, true), lcs(lcs_), lc_canv_cb(lc_canv_cb_), summ_avg_circs(4, (GdaCircle*) 0), -y_axis_precision(1) +y_axis_precision(2), fixed_scale_over_change(true), prev_y_axis_min(DBL_MIN), prev_y_axis_max(DBL_MAX) { LOG_MSG("Entering LineChartCanvas::LineChartCanvas"); last_scale_trans.SetFixedAspectRatio(false); @@ -69,7 +69,7 @@ y_axis_precision(1) PopulateCanvas(); ResizeSelectableShps(); - SetBackgroundStyle(wxBG_STYLE_CUSTOM); // default style + SetBackgroundStyle(wxBG_STYLE_PAINT); // default style Bind(wxEVT_LEFT_DCLICK, &LineChartCanvas::OnDblClick, this); @@ -365,6 +365,15 @@ void LineChartCanvas::PopulateCanvas() if (y_min >= 0 && axis_min < 0) axis_min = 0; + // support "Fixed Scale over change + if (fixed_scale_over_change && prev_y_axis_min != DBL_MIN && prev_y_axis_max != DBL_MAX) { + axis_min = prev_y_axis_min; + axis_max = prev_y_axis_max; + } + + prev_y_axis_min = axis_min; + prev_y_axis_max = axis_max; + if (!def_y_min.IsEmpty()) def_y_min.ToDouble(&axis_min); @@ -373,9 +382,8 @@ void LineChartCanvas::PopulateCanvas() axis_scale_y = AxisScale(axis_min, axis_max, 4, y_axis_precision); - //LOG_MSG(wxString(axis_scale_y.ToString().c_str(), wxConvUTF8)); scaleY = 100.0 / (axis_scale_y.scale_range); - + TableInterface* table_int = project->GetTableInt(); // create axes std::vector tm_strs; diff --git a/Explore/LineChartCanvas.h b/Explore/LineChartCanvas.h index eaf0e0e6a..9323b637c 100644 --- a/Explore/LineChartCanvas.h +++ b/Explore/LineChartCanvas.h @@ -51,6 +51,8 @@ class LineChartCanvas : public TemplateCanvas virtual void UpdateAll(); + virtual wxString GetVariableNames() { return wxEmptyString;} + void UpdateYAxis(wxString y_min="", wxString y_max=""); void UpdateYAxisPrecision(int precision_s); @@ -58,6 +60,8 @@ class LineChartCanvas : public TemplateCanvas double GetYAxisMinVal() {return axis_scale_y.scale_min;} double GetYAxisMaxVal() {return axis_scale_y.scale_max;} + bool fixed_scale_over_change; + protected: void OnDblClick(wxMouseEvent& event); @@ -74,6 +78,9 @@ class LineChartCanvas : public TemplateCanvas double scaleY; int y_axis_precision; + double prev_y_axis_min; + double prev_y_axis_max; + double y_axis_min; double y_axis_max; diff --git a/Explore/LineChartView.cpp b/Explore/LineChartView.cpp index e8eb569b7..f70fe8995 100644 --- a/Explore/LineChartView.cpp +++ b/Explore/LineChartView.cpp @@ -53,6 +53,7 @@ bool classicalRegression(GalElement *g, int num_obs, double * Y, bool do_white_test); BEGIN_EVENT_TABLE(LineChartFrame, TemplateFrame) +EVT_CLOSE(LineChartFrame::OnClose ) EVT_ACTIVATE(LineChartFrame::OnActivate) END_EVENT_TABLE() @@ -81,12 +82,17 @@ tms_subset1(project->GetTableInt()->GetTimeSteps(), false), tms_subset0_tm_inv(1, true), tms_subset1_tm_inv(1, false), regReportDlg(0), -def_y_precision(1), +def_y_precision(2), use_def_y_range(false), has_selection(1), -has_excluded(1) +has_excluded(1), +export_dlg(NULL), +mem_table_int(NULL), +fixed_scale_over_change(true) { wxLogMessage("Open LineChartFrame(Average Charts)."); + + SetMinSize(wxSize(680,420)); // Init variables supports_timeline_changes = true; @@ -202,11 +208,8 @@ has_excluded(1) wxSize(380,-1)); message_win->Bind(wxEVT_RIGHT_UP, &LineChartFrame::OnMouseEvent, this); - bag_szr = new wxGridBagSizer(0, 0); // 0 vgap, 0 hgap - bag_szr->Add(message_win, wxGBPosition(0,0), wxGBSpan(1,1), wxEXPAND); - bag_szr->SetFlexibleDirection(wxBOTH); - bag_szr->AddGrowableCol(0, 1); - bag_szr->AddGrowableRow(0, 1); + bag_szr = new wxBoxSizer(wxVERTICAL); + bag_szr->Add(message_win, 1, wxEXPAND); panel_v_szr = new wxBoxSizer(wxVERTICAL); panel_v_szr->Add(bag_szr, 1, wxEXPAND); @@ -255,18 +258,42 @@ has_excluded(1) Connect(XRCID("ID_ADJUST_Y_AXIS_PRECISION"), wxEVT_MENU, wxCommandEventHandler(LineChartFrame::OnAdjustYAxisPrecision)); + Connect(XRCID("ID_LINE_CHART_FIXED_SCALE_OVER_TIME"), + wxEVT_MENU, + wxCommandEventHandler(LineChartFrame::OnFixedScaleOverChange)); } LineChartFrame::~LineChartFrame() { + wxLogMessage("Exit LineChartFrame(Average Charts)."); highlight_state->removeObserver(this); if (HasCapture()) ReleaseMouse(); DeregisterAsActive(); + + if (export_dlg) { + export_dlg->Destroy(); + delete export_dlg; + } + + if (mem_table_int) { + delete mem_table_int; + mem_table_int = NULL; + } +} + +void LineChartFrame::OnClose(wxCloseEvent& event) +{ + wxLogMessage("LineChartFrame::OnClose()"); + if (export_dlg) { + export_dlg->Close(); + } + event.Skip(); } void LineChartFrame::InitVariableChoiceCtrl() { + wxLogMessage("LineChartFrame::InitVariableChoiceCtrl()"); TableInterface* table_int = project->GetTableInt(); if (table_int == NULL) { wxLogMessage("ERROR: Table interface NULL."); @@ -300,6 +327,8 @@ void LineChartFrame::InitVariableChoiceCtrl() void LineChartFrame::InitGroupsChoiceCtrl() { + wxLogMessage("LineChartFrame::InitGroupsChoiceCtrl()"); + choice_groups->Append(_("Selected vs. Unselected")); choice_groups->Append(_("All")); choice_groups->SetSelection(0); @@ -317,6 +346,8 @@ void LineChartFrame::InitGroupsChoiceCtrl() void LineChartFrame::InitTimeChoiceCtrl() { + wxLogMessage("LineChartFrame::InitTimeChoiceCtrl()"); + std::vector tm_strs; project->GetTableInt()->GetTimeStrings(tm_strs); @@ -507,27 +538,19 @@ void LineChartFrame::OnTime1Choice(wxCommandEvent& event) choice_time2->SetSelection(time1_selection); } else { // sel vs sel or excl vs excl - if (time2_selection == time1_selection || + if (time1_selection == time2_selection || time1_selection > time2_selection) { - if (time1_selection +1 < time_count) { - choice_time2->SetSelection(time1_selection+1); - } else { - wxMessageBox("Please select Period 1 < Period 2."); - choice_time1->SetSelection(time_count-2); - choice_time2->SetSelection(time_count-1); - } + wxMessageBox(("Please select Period 2 > Period 1.")); + choice_time1->SetSelection(0); + choice_time2->SetSelection(1); } } } else { - if (time2_selection == time1_selection|| + if (time1_selection == time2_selection || time1_selection > time2_selection) { - if (time1_selection +1 < time_count) { - choice_time2->SetSelection(time1_selection+1); - } else { - wxMessageBox("Please select Period 1 < Period 2."); - choice_time1->SetSelection(time_count-2); - choice_time2->SetSelection(time_count-1); - } + wxMessageBox(("Please select Period 2 > Period 1.")); + choice_time1->SetSelection(0); + choice_time2->SetSelection(1); } } @@ -544,22 +567,19 @@ void LineChartFrame::OnTime2Choice(wxCommandEvent& event) int time_count = choice_time1->GetCount(); if (group_selection == 0 ) { - if (time1_selection > time2_selection) { - if (time2_selection - 1 >=0 ) { - choice_time1->SetSelection(time2_selection-1); - } else { - wxMessageBox(_("Please select Period 2 > Period 1.")); + if (choice_group1->GetSelection() != choice_group2->GetSelection()) { + } else { + if (time1_selection == time2_selection || + time1_selection > time2_selection) { + wxMessageBox(("Please select Period 2 > Period 1.")); choice_time1->SetSelection(0); choice_time2->SetSelection(1); } } - } else { - if (time2_selection == time1_selection|| + if (time2_selection == time1_selection || time1_selection > time2_selection) { - if (time2_selection - 1 >=0 ) { - choice_time1->SetSelection(time2_selection-1); - } else { + if (time2_selection >=0 && time1_selection == time2_selection) { wxMessageBox(("Please select Period 2 > Period 1.")); choice_time1->SetSelection(0); choice_time2->SetSelection(1); @@ -667,9 +687,6 @@ void LineChartFrame::OnGroup2Choice(wxCommandEvent& event) } } } - - - // } else { choice_time2->SetSelection(choice_time1->GetSelection()); } @@ -682,23 +699,23 @@ void LineChartFrame::InitGroup12ChoiceCtrl() int group_selection = choice_groups->GetSelection(); if (group_selection == 0 ) { choice_group1->Clear(); - choice_group1->Append("Selected"); - choice_group1->Append("Unselected"); + choice_group1->Append(_("Selected")); + choice_group1->Append(_("Unselected")); choice_group1->SetSelection(0); choice_group1->Enable(true); choice_group2->Clear(); - choice_group2->Append("Selected"); - choice_group2->Append("Unselected"); + choice_group2->Append(_("Selected")); + choice_group2->Append(_("Unselected")); choice_group2->SetSelection(1); choice_group2->Enable(true); } else { choice_group1->Clear(); - choice_group1->Append("All"); + choice_group1->Append(_("All")); choice_group1->Enable(false); choice_group2->Clear(); - choice_group2->Append("All"); + choice_group2->Append(_("All")); choice_group2->Enable(false); } } @@ -746,7 +763,7 @@ void LineChartFrame::MapMenus() optMenu = wxXmlResource::Get()->LoadMenu("ID_LINE_CHART_MENU_OPTIONS"); LineChartFrame::UpdateContextMenuItems(optMenu); - GeneralWxUtils::ReplaceMenu(mb, "Options", optMenu); + GeneralWxUtils::ReplaceMenu(mb, _("Options"), optMenu); UpdateOptionMenuItems(); } @@ -754,7 +771,7 @@ void LineChartFrame::UpdateOptionMenuItems() { //TemplateFrame::UpdateOptionMenuItems(); // set common items first wxMenuBar* mb = GdaFrame::GetGdaFrame()->GetMenuBar(); - int menu = mb->FindMenu("Options"); + int menu = mb->FindMenu(_("Options")); if (menu == wxNOT_FOUND) { } else { LineChartFrame::UpdateContextMenuItems(mb->GetMenu(menu)); @@ -780,6 +797,9 @@ void LineChartFrame::UpdateContextMenuItems(wxMenu* menu) use_def_y_range); GeneralWxUtils::EnableMenuItem(menu, XRCID("ID_ADJUST_Y_AXIS"), use_def_y_range); + GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_LINE_CHART_FIXED_SCALE_OVER_TIME"), + fixed_scale_over_change); + if (var_man.IsAnyTimeVariant() == false) { GeneralWxUtils::EnableMenuItem(menu, XRCID("ID_COMPARE_TIME_PERIODS"), false); GeneralWxUtils::EnableMenuItem(menu, XRCID("ID_COMPARE_REG_AND_TM_PER"), false); @@ -787,6 +807,16 @@ void LineChartFrame::UpdateContextMenuItems(wxMenu* menu) TemplateFrame::UpdateContextMenuItems(menu); // set common items } +void LineChartFrame::OnFixedScaleOverChange(wxCommandEvent& event) +{ + wxLogMessage("In LineChartFrame:OnFixedScaleOverChange()"); + fixed_scale_over_change = !fixed_scale_over_change; + + for (size_t i=0, sz=line_charts.size(); ifixed_scale_over_change = fixed_scale_over_change; + } +} + void LineChartFrame::OnUseAdjustYAxis(wxCommandEvent& event) { wxLogMessage("In LineChartFrame:OnUseAdjustYAxis()"); @@ -842,6 +872,9 @@ void LineChartFrame::OnAdjustYAxisPrecision(wxCommandEvent& event) line_charts[i]->UpdateAll(); } + for (size_t i=0, sz=stats_wins.size(); iAddOGRColumn(interact_col); } - if (save_did) { if (m_yhat1 != 0 && m_resid1 != 0) { std::vector yhat; @@ -1180,10 +1215,15 @@ void LineChartFrame::SaveDataAndResults(bool save_weights, bool save_did, } // export - ExportDataDlg dlg(this, (TableInterface*)mem_table_int); - if (dlg.ShowModal() == wxID_OK) { + if (export_dlg != NULL) { + export_dlg->Destroy(); + delete export_dlg; + } + export_dlg = new ExportDataDlg(this, (TableInterface*)mem_table_int); + + if (export_dlg->ShowModal() == wxID_OK) { if (save_weights) { - wxString ds_name = dlg.GetDatasourceName(); + wxString ds_name = export_dlg->GetDatasourceName(); wxFileName wx_fn(ds_name); // save weights @@ -1206,11 +1246,8 @@ void LineChartFrame::SaveDataAndResults(bool save_weights, bool save_did, } } } - - // clean memory - delete mem_table_int; - } + void LineChartFrame::OnSaveDummyTable(wxCommandEvent& event) { wxLogMessage("Start LineChartFrame::OnSaveDummyTable"); @@ -1592,10 +1629,12 @@ void LineChartFrame::update(HLStateInt* o) lc_stats[i]->UpdateOtherStats(); } for (size_t i=0, sz=line_charts.size(); iUpdateYAxis(def_y_min, def_y_max); - else + } else { line_charts[i]->UpdateYAxis(); + } line_charts[i]->UpdateAll(); } for (size_t i=0, sz=stats_wins.size(); iClear(); panel_v_szr->Remove(bag_szr); // bag_szr is deleted automatically - bag_szr = new wxGridBagSizer(0, 0); // 0 vgap, 0 hgap + bag_szr = new wxBoxSizer(wxVERTICAL); for (size_t i=0, sz=line_charts.size(); iDestroy(); @@ -1810,14 +1849,9 @@ void LineChartFrame::SetupPanelForNumVariables(int num_vars) if (num_vars < 1) { message_win = new wxHtmlWindow(panel, wxID_ANY, wxDefaultPosition, wxSize(200,-1)); message_win->Bind(wxEVT_RIGHT_UP, &LineChartFrame::OnMouseEvent, this); - bag_szr->Add(message_win, wxGBPosition(0,0), wxGBSpan(1,1), wxEXPAND); - bag_szr->SetFlexibleDirection(wxBOTH); - if (bag_szr->IsColGrowable(0)) bag_szr->RemoveGrowableCol(0); - bag_szr->AddGrowableCol(0, 1); - if (bag_szr->IsRowGrowable(0)) bag_szr->RemoveGrowableRow(0); - bag_szr->AddGrowableRow(0, 1); - + bag_szr->Add(message_win, 1, wxEXPAND); } else { + // num_vars should be 1 for (int row=0; rowfixed_scale_over_change = fixed_scale_over_change; if (use_def_y_range) { canvas->UpdateYAxis(def_y_min, def_y_max); canvas->UpdateAll(); } - if (def_y_precision !=1) { + if (def_y_precision !=2) { canvas->UpdateYAxisPrecision(def_y_precision); canvas->UpdateAll(); } - bag_szr->Add(canvas, wxGBPosition(row, 0), wxGBSpan(1,1), wxEXPAND); + bag_szr->Add(canvas, 1, wxEXPAND); line_charts.push_back(canvas); } - int col0_proportion = 1; - - int col1_proportion = 1; - bag_szr->SetFlexibleDirection(wxBOTH); - if (bag_szr->IsColGrowable(0)) - bag_szr->RemoveGrowableCol(0); - bag_szr->AddGrowableCol(0, col0_proportion); - - for (int i=0; iIsRowGrowable(i)) - bag_szr->RemoveGrowableRow(i); - bag_szr->AddGrowableRow(i, 1); - } } - //panel_v_szr->AddSpacer(5); panel_v_szr->Add(bag_szr, 1, wxEXPAND); panel_h_szr->RecalcSizes(); @@ -2066,7 +2088,7 @@ void LineChartFrame::UpdateStatsWinContent(int var) } stringstream _s; - _s << std::fixed << std::setprecision(2); + _s << std::fixed << std::setprecision(def_y_precision); wxString td_s0_mean; if (lcs.s0.mean_v) { @@ -2167,10 +2189,18 @@ void LineChartFrame::UpdateStatsWinContent(int var) s<< "
    PropertyValue" << _("Property") << "" << _("Value") << "
    "; s<< ""; - s<< ""; - s<< ""; - s<< ""; - s<< ""; + s<< ""; + s<< ""; + s<< ""; + s<< ""; s<< ""; if (single_sample) { @@ -2183,10 +2213,17 @@ void LineChartFrame::UpdateStatsWinContent(int var) } else { s<< ""; - if (cmp_r) - s<< ""; - if (cmp_t) - s<< ""; + if (cmp_r) { + s<< ""; + } + if (cmp_t) { + s<< ""; + + } if (cmp_r || cmp_t) { if (cmp_r) @@ -2201,14 +2238,22 @@ void LineChartFrame::UpdateStatsWinContent(int var) if (cmp_r_t) { if (choice_group1->GetSelection() == 0) { - s<< ""; + s<< ""; s<< ""; s<< td_s0_mean; s<< ""; s<< ""; s<< ""; } else { - s<< ""; + s<< ""; s<< ""; s<< td_s1_mean; @@ -2219,10 +2264,16 @@ void LineChartFrame::UpdateStatsWinContent(int var) } - if (cmp_r) - s<< ""; - if (cmp_t) - s<< ""; + if (cmp_r) { + s<< ""; + } + if (cmp_t) { + s<< ""; + } if (cmp_r || cmp_t) { if (cmp_r) @@ -2236,14 +2287,22 @@ void LineChartFrame::UpdateStatsWinContent(int var) if (cmp_r_t) { if (choice_group2->GetSelection() == 0) { - s<< ""; + s<< ""; s<< ""; s<< td_s2_mean; s<< ""; s<< ""; } else { - s<< ""; + s<< ""; s<< ""; s<< td_s3_mean; s<< ""; @@ -2257,10 +2316,14 @@ void LineChartFrame::UpdateStatsWinContent(int var) s<< "
    Group Obs.  Mean  S.D. "; + s<< _("Group"); + s<< " "; + s<< _("Obs."); + s<< "  "; + s<< _("Mean"); + s<< "  "; + s<< _("S.D"); + s<< ". 
    SelectedPeriod 1"; + s<< _("Selected"); + s<< ""; + s<< _("Period 1"); + s<< "Selected/Period 1"; + s<< _("Selected"); + s<< "/"; + s<< _("Period 1"); + s<< "" << lcs.sel_sz_i << "" << sd0 << "
    Unselected/Period 1"; + s<< _("Unselected"); + s<< "/"; + s<< _("Period 1"); + s<< "" << lcs.excl_sz_i << "UnselectedPeriod 2"; + s<< _("Unselected"); + s<< ""; + s<< _("Period 2"); + s<< "Selected/Period 2"; + s<< _("Selected"); + s<< "/"; + s<< _("Period 2"); + s<< "" << lcs.sel_sz_i << "" << sd2 << "
    Unselected/Period 2"; + s<< _("Unselected"); + s<< "/"; + s<< _("Period 2"); + s<< "" << lcs.excl_sz_i << "" << sd3 << "
    \n"; if (lcs.test_stat_valid && !cmp_r_t) { - s<< "
    Do Means Differ? (ANOVA)

    "; + s<< "
    "; + s<< _("Do Means Differ? (ANOVA)"); + s<< "

    "; s<< ""; s<< ""; - s<< ""; + s<< ""; stringstream _s; if (choice_groups->GetSelection() == 0) _s << (int)lcs.deg_free -1; @@ -2287,7 +2350,9 @@ void LineChartFrame::UpdateStatsWinContent(int var) } if (cmp_r_t) { - s<< "
    Do Means Differ? (ANOVA)

    "; + s<< "
    "; + s<< _("Do Means Differ? (ANOVA)"); + s<< "

    "; s<< "
    D.F. "; + s<< _("D.F."); + s<< " 
    "; s<< ""; s<< ""; diff --git a/Explore/LineChartView.h b/Explore/LineChartView.h index a4cc62ddb..3a99aef9b 100644 --- a/Explore/LineChartView.h +++ b/Explore/LineChartView.h @@ -41,6 +41,7 @@ class HighlightState; class LineChartCanvas; class Project; +class ExportDataDlg; typedef std::map data_map_type; typedef std::map > data_map_undef_type; @@ -121,7 +122,8 @@ public HighlightStateObserver, public LineChartCanvasCallbackInt void OnUseAdjustYAxis(wxCommandEvent& event); void OnAdjustYAxis(wxCommandEvent& event); void OnAdjustYAxisPrecision(wxCommandEvent& event); - + void OnFixedScaleOverChange(wxCommandEvent& event); + void OnSaveDummyTable(wxCommandEvent& event); void OnReportClose(wxWindowDestroyEvent& event); @@ -171,7 +173,8 @@ public HighlightStateObserver, public LineChartCanvasCallbackInt wxChoice* choice_time2; //wxCheckBox* chk_run_test; wxCheckBox* chk_save_did; - + ExportDataDlg* export_dlg; + int has_selection; int has_excluded; @@ -189,7 +192,7 @@ public HighlightStateObserver, public LineChartCanvasCallbackInt void OnTime1Choice(wxCommandEvent& event); void OnTime2Choice(wxCommandEvent& event); void OnApplyButton(wxCommandEvent& event); - + void OnClose(wxCloseEvent& event); wxString logReport; RegressionReportDlg *regReportDlg; @@ -215,15 +218,16 @@ public HighlightStateObserver, public LineChartCanvasCallbackInt wxBoxSizer* ctrls_h_szr; wxBoxSizer* title1_h_szr; wxBoxSizer* title2_h_szr; - wxGridBagSizer* bag_szr; + wxBoxSizer* bag_szr; wxPanel* panel; wxHtmlWindow* message_win; + OGRTable* mem_table_int; int def_y_precision; bool use_def_y_range; wxString def_y_min; wxString def_y_max; - + bool fixed_scale_over_change; //bool show_regimes; bool display_stats; diff --git a/Explore/LisaCoordinator.cpp b/Explore/LisaCoordinator.cpp index 648d8bf0c..ba944a983 100644 --- a/Explore/LisaCoordinator.cpp +++ b/Explore/LisaCoordinator.cpp @@ -22,8 +22,11 @@ #include #include +#include #include #include +#include + #include "../DataViewer/TableInterface.h" #include "../ShapeOperations/RateSmoothing.h" #include "../ShapeOperations/Randik.h" @@ -32,54 +35,9 @@ #include "../VarCalc/WeightsManInterface.h" #include "../logger.h" #include "../Project.h" -#include "LisaCoordinatorObserver.h" #include "LisaCoordinator.h" -LisaWorkerThread::LisaWorkerThread(const GalElement* W_, - const std::vector& undefs_, - int obs_start_s, int obs_end_s, - uint64_t seed_start_s, - LisaCoordinator* lisa_coord_s, - wxMutex* worker_list_mutex_s, - wxCondition* worker_list_empty_cond_s, - std::list *worker_list_s, - int thread_id_s) -: wxThread(), -W(W_), -undefs(undefs_), -obs_start(obs_start_s), obs_end(obs_end_s), seed_start(seed_start_s), -lisa_coord(lisa_coord_s), -worker_list_mutex(worker_list_mutex_s), -worker_list_empty_cond(worker_list_empty_cond_s), -worker_list(worker_list_s), -thread_id(thread_id_s) -{ -} - -LisaWorkerThread::~LisaWorkerThread() -{ -} - -wxThread::ExitCode LisaWorkerThread::Entry() -{ - LOG_MSG(wxString::Format("LisaWorkerThread %d started", thread_id)); - - // call work for assigned range of observations - lisa_coord->CalcPseudoP_range(W, undefs, obs_start, obs_end, seed_start); - - wxMutexLocker lock(*worker_list_mutex); - - // remove ourself from the list - worker_list->remove(this); - - // if empty, signal on empty condition since only main thread - // should be waiting on this condition - if (worker_list->empty()) { - worker_list_empty_cond->Signal(); - } - - return NULL; -} +#include "../Algorithms/gpu_lisa.h" /** Since the user has the ability to synchronise either variable over time, @@ -115,42 +73,16 @@ LisaCoordinator(boost::uuids::uuid weights_id, LisaType lisa_type_s, bool calc_significances_s, bool row_standardize_s) -: w_man_state(project->GetWManState()), -w_man_int(project->GetWManInt()), -w_id(weights_id), -num_obs(project->GetNumRecords()), -permutations(999), +: AbstractCoordinator(weights_id, project, var_info_s, col_ids, calc_significances_s, row_standardize_s), lisa_type(lisa_type_s), -calc_significances(calc_significances_s), -isBivariate(lisa_type_s == bivariate), -var_info(var_info_s), -data(var_info_s.size()), -undef_data(var_info_s.size()), -last_seed_used(0), reuse_last_seed(false), -row_standardize(row_standardize_s) +isBivariate(lisa_type_s == bivariate) { - reuse_last_seed = GdaConst::use_gda_user_seed; - if ( GdaConst::use_gda_user_seed) { - last_seed_used = GdaConst::gda_user_seed; - } - - TableInterface* table_int = project->GetTableInt(); + wxLogMessage("Entering LisaCoordinator::LisaCoordinator()."); for (int i=0; iGetColData(col_ids[i], data[i]); - table_int->GetColUndefined(col_ids[i], undef_data[i]); var_info[i].is_moran = true; } - - undef_tms.resize(var_info_s[0].time_max - var_info_s[0].time_min + 1); - - weight_name = w_man_int->GetLongDispName(w_id); - - weights = w_man_int->GetGal(w_id); - - SetSignificanceFilter(1); - - InitFromVarInfo(); - w_man_state->registerObserver(this); + InitFromVarInfo(); // call to init calculation + wxLogMessage("Exiting LisaCoordinator::LisaCoordinator()."); } @@ -163,7 +95,9 @@ LisaCoordinator(wxString weights_path, int permutations_s, bool calc_significances_s, bool row_standardize_s) +: AbstractCoordinator() { + wxLogMessage("Entering LisaCoordinator::LisaCoordinator()2."); num_obs = n; num_time_vals = 1; permutations = permutations_s; @@ -242,18 +176,18 @@ LisaCoordinator(wxString weights_path, SetSignificanceFilter(1); InitFromVarInfo(); + wxLogMessage("Exiting LisaCoordinator::LisaCoordinator()2."); } LisaCoordinator::~LisaCoordinator() { - if (w_man_state) { - w_man_state->removeObserver(this); - } + wxLogMessage("In LisaCoordinator::~LisaCoordinator()."); DeallocateVectors(); } void LisaCoordinator::DeallocateVectors() { + wxLogMessage("Entering LisaCoordinator::DeallocateVectors()"); for (int i=0; igal; + for (int t=0; t undefs; bool has_undef = false; + bool has_isolate = false; for (int i=0; i t) + if (undef_data[1].size() > t) { is_undef = is_undef || undef_data[1][t][i]; + } } if (is_undef && !has_undef) { has_undef = true; } + if (weights->gal[i].Size() == 0) { + is_undef = true; + has_isolate = true; + } undefs.push_back(is_undef); } has_undefined[t] = has_undef; // local weights copy GalWeight* gw = NULL; - if ( has_undef ) { + if ( has_undef || has_isolate ) { gw = new GalWeight(*weights); gw->Update(undefs); } else { gw = weights; } GalElement* W = gw->gal; - Gal_vecs.push_back(gw); - Gal_vecs_orig.push_back(weights); + Gal_vecs[t] = gw; + Gal_vecs_orig[t] = weights; for (int i=0; i 0) { - if (data1[i] > 0 && Wdata < 0) cluster[i] = 4; - else if (data1[i] < 0 && Wdata > 0) cluster[i] = 3; - else if (data1[i] < 0 && Wdata < 0) cluster[i] = 2; - else cluster[i] = 1; //data1[i] > 0 && Wdata > 0 - } else { - has_isolates[t] = true; - cluster[i] = 5; // neighborless - } + //if (W[i].Size() > 0) { + if (data1[i] > 0 && Wdata < 0) cluster[i] = 4; + else if (data1[i] < 0 && Wdata > 0) cluster[i] = 3; + else if (data1[i] < 0 && Wdata < 0) cluster[i] = 2; + else cluster[i] = 1; //data1[i] > 0 && Wdata > 0 } } + wxLogMessage("Exiting LisaCoordinator::Calc()"); } void LisaCoordinator::CalcPseudoP() { - if (!calc_significances) return; - wxStopWatch sw; - int nCPUs = wxThread::GetCPUCount(); - - // To ensure thread safety, only work on one time slice of data - // at a time. For each time period t: - // 1. copy data for time period t into data1 and data2 arrays - // 2. Perform multi-threaded computation - // 3. copy results into results array - - - for (int t=0; t& undefs = undef_tms[t]; - data1 = data1_vecs[t]; - if (isBivariate) { - data2 = data2_vecs[0]; - if (var_info[1].is_time_variant && - var_info[1].sync_with_global_time) - data2 = data2_vecs[t]; - } - lags = lags_vecs[t]; - localMoran = local_moran_vecs[t]; - sigLocalMoran = sig_local_moran_vecs[t]; - sigCat = sig_cat_vecs[t]; - cluster = cluster_vecs[t]; - - if (nCPUs <= 1 || num_obs <= nCPUs * 10) { - if (!reuse_last_seed) { - last_seed_used = time(0); + wxStopWatch sw_vd; + + if (GdaConst::gda_use_gpu == false) { + if (!calc_significances) + return; + CalcPseudoP_threaded(); + + } else { + double* values = data1_vecs[0]; + double* local_moran = local_moran_vecs[0]; + GalElement* w = weights->gal; + double* _sigLocal = sig_local_vecs[0]; + + wxString exePath = GenUtils::GetBasemapCacheDir(); + wxString clPath = exePath + "lisa_kernel.cl"; + bool flag = gpu_lisa(clPath.mb_str(), num_obs, permutations, last_seed_used, values, local_moran, w, _sigLocal); + + if (flag) { + for (int cnt=0; cntgal, undefs, - 0, num_obs-1, last_seed_used); + } } else { - CalcPseudoP_threaded(Gal_vecs[t]->gal, undefs); - //CalcPseudoP_range(Gal_vecs[t]->gal, undefs, - // 0, num_obs-1, last_seed_used); + wxMessageDialog dlg(NULL, "GeoDa can't configure GPU device. Default CPU solution will be used instead.", _("Error"), wxOK | wxICON_ERROR); + dlg.ShowModal(); + if (!calc_significances) + return; + CalcPseudoP_threaded(); } - } - - - { - wxString m; - m << "LISA on " << num_obs << " obs with " << permutations; - m << " perms over " << num_time_vals << " time periods took "; - m << sw.Time() << " ms. Last seed used: " << last_seed_used; - } - LOG_MSG("Exiting LisaCoordinator::CalcPseudoP"); -} - -void LisaCoordinator::CalcPseudoP_threaded(const GalElement* W, - const std::vector& undefs) -{ - int nCPUs = wxThread::GetCPUCount(); - - // mutext protects access to the worker_list - wxMutex worker_list_mutex; - // signals that worker_list is empty - wxCondition worker_list_empty_cond(worker_list_mutex); - // mutex should be initially locked - worker_list_mutex.Lock(); - - // List of all the threads currently alive. As soon as the thread - // terminates, it removes itself from the list. - std::list worker_list; - - // divide up work according to number of observations - // and number of CPUs - int work_chunk = num_obs / nCPUs; - - if (work_chunk == 0) { - work_chunk = 1; } - - int obs_start = 0; - int obs_end = obs_start + work_chunk; - - bool is_thread_error = false; - int quotient = num_obs / nCPUs; - int remainder = num_obs % nCPUs; - int tot_threads = (quotient > 0) ? nCPUs : remainder; - - boost::thread_group threadPool; - - if (!reuse_last_seed) - last_seed_used = time(0); - for (int i=0; i" << b; - msg << ", seed: " << seed_start << "->" << seed_end; - - /* - LisaWorkerThread* thread = - new LisaWorkerThread(W, undefs, a, b, seed_start, this, - &worker_list_mutex, - &worker_list_empty_cond, - &worker_list, thread_id); - if ( thread->Create() != wxTHREAD_NO_ERROR ) { - delete thread; - is_thread_error = true; - } else { - worker_list.push_front(thread); - } - */ - boost::thread* worker = new boost::thread(boost::bind(&LisaCoordinator::CalcPseudoP_range,this, W, undefs, a, b, seed_start)); - threadPool.add_thread(worker); - } - threadPool.join_all(); - /* - if (is_thread_error) { - // fall back to single thread calculation mode - CalcPseudoP_range(W, undefs, 0, num_obs-1, last_seed_used); - } else { - std::list::iterator it; - for (it = worker_list.begin(); it != worker_list.end(); it++) { - (*it)->Run(); - } - - while (!worker_list.empty()) { - // wait until thread_list might be empty - worker_list_empty_cond.Wait(); - // We have been woken up. If this was not a false - // alarm (sprious signal), the loop will exit. - } - } - */ + LOG_MSG(wxString::Format("GPU took %ld ms", sw_vd.Time())); } -void LisaCoordinator::CalcPseudoP_range(const GalElement* W, - const std::vector& undefs, - int obs_start, int obs_end, - uint64_t seed_start) +void LisaCoordinator::ComputeLarger(int cnt, std::vector permNeighbors, std::vector& countLarger) { - GeoDaSet workPermutation(num_obs); - //Randik rng; - int max_rand = num_obs-1; - for (int cnt=obs_start; cnt<=obs_end; cnt++) { + // for each time step, reuse permuation + for (int t=0; t& undefs = undef_tms[t]; - if (undefs[cnt]) - continue; + data1 = data1_vecs[t]; + if (isBivariate) { + data2 = data2_vecs[0]; + if (var_info[1].is_time_variant && var_info[1].sync_with_global_time) + data2 = data2_vecs[t]; + } - const int numNeighbors = W[cnt].Size(); - - uint64_t countLarger = 0; - for (int perm=0; perm= localMoran[cnt]) { - countLarger++; + } else { + for (int cp=0; cp0.05 1: 0.05, 2: 0.01, 3: 0.001, 4: 0.0001 - if (filter_id < 1 || filter_id > 4) return; - significance_filter = filter_id; - if (filter_id == 1) significance_cutoff = 0.05; - if (filter_id == 2) significance_cutoff = 0.01; - if (filter_id == 3) significance_cutoff = 0.001; - if (filter_id == 4) significance_cutoff = 0.0001; -} - -void LisaCoordinator::update(WeightsManState* o) -{ - if (w_man_int) { - weight_name = w_man_int->GetLongDispName(w_id); + } + + //NOTE: we shouldn't have to row-standardize or + // multiply by data1[cnt] + if (validNeighbors > 0 && row_standardize) { + permutedLag /= validNeighbors; + } + const double localMoranPermuted = permutedLag * data1[cnt]; + if (localMoranPermuted >= localMoran[cnt]) { + countLarger[t]++; + } } } - -int LisaCoordinator::numMustCloseToRemove(boost::uuids::uuid id) const -{ - return id == w_id ? observers.size() : 0; -} - -void LisaCoordinator::closeObserver(boost::uuids::uuid id) -{ - if (numMustCloseToRemove(id) == 0) return; - std::list obs_cpy = observers; - for (std::list::iterator i=obs_cpy.begin(); - i != obs_cpy.end(); ++i) { - (*i)->closeObserver(this); - } -} - -void LisaCoordinator::registerObserver(LisaCoordinatorObserver* o) -{ - observers.push_front(o); -} - -void LisaCoordinator::removeObserver(LisaCoordinatorObserver* o) -{ - LOG_MSG("Entering LisaCoordinator::removeObserver"); - observers.remove(o); - LOG(observers.size()); - if (observers.size() == 0) { - delete this; - } - LOG_MSG("Exiting LisaCoordinator::removeObserver"); -} - -void LisaCoordinator::notifyObservers() -{ - for (std::list::iterator it=observers.begin(); - it != observers.end(); ++it) { - (*it)->update(this); - } -} - diff --git a/Explore/LisaCoordinator.h b/Explore/LisaCoordinator.h index 45cebf1b2..726072d46 100644 --- a/Explore/LisaCoordinator.h +++ b/Explore/LisaCoordinator.h @@ -26,50 +26,14 @@ #include #include #include "../VarTools.h" -#include "../ShapeOperations/GeodaWeight.h" -#include "../ShapeOperations/GalWeight.h" -#include "../ShapeOperations/WeightsManStateObserver.h" -#include "../ShapeOperations/OGRDataAdapter.h" +#include "AbstractCoordinator.h" -class LisaCoordinatorObserver; -class LisaCoordinator; class Project; -class WeightsManState; -typedef boost::multi_array d_array_type; -typedef boost::multi_array b_array_type; -class LisaWorkerThread : public wxThread +class LisaCoordinator : public AbstractCoordinator { public: - LisaWorkerThread(const GalElement* W, - const std::vector& undefs, - int obs_start, int obs_end, uint64_t seed_start, - LisaCoordinator* lisa_coord, - wxMutex* worker_list_mutex, - wxCondition* worker_list_empty_cond, - std::list *worker_list, - int thread_id); - virtual ~LisaWorkerThread(); - virtual void* Entry(); // thread execution starts here - - const GalElement* W; - const std::vector& undefs; - int obs_start; - int obs_end; - uint64_t seed_start; - int thread_id; - - LisaCoordinator* lisa_coord; - wxMutex* worker_list_mutex; - wxCondition* worker_list_empty_cond; - std::list *worker_list; -}; - -class LisaCoordinator : public WeightsManStateObserver -{ -public: - // #9 enum LisaType { univariate, bivariate, eb_rate_standardized, differential }; LisaCoordinator(boost::uuids::uuid weights_id, @@ -91,144 +55,33 @@ class LisaCoordinator : public WeightsManStateObserver virtual ~LisaCoordinator(); - bool IsOk() { return true; } - wxString GetErrorMessage() { return "Error Message"; } - int significance_filter; // 0: >0.05 1: 0.05, 2: 0.01, 3: 0.001, 4: 0.0001 - - double significance_cutoff; // either 0.05, 0.01, 0.001 or 0.0001 - - void SetSignificanceFilter(int filter_id); - - int GetSignificanceFilter() { return significance_filter; } - - int permutations; // any number from 9 to 99999, 99 will be default - - uint64_t GetLastUsedSeed() { return last_seed_used; } - - void SetLastUsedSeed(uint64_t seed) { - reuse_last_seed = true; - last_seed_used = seed; - // update global one - GdaConst::use_gda_user_seed = true; - OGRDataAdapter::GetInstance().AddEntry("use_gda_user_seed", "1"); - GdaConst::gda_user_seed = last_seed_used; - wxString val; - val << last_seed_used; - OGRDataAdapter::GetInstance().AddEntry("gda_user_seed", val.ToStdString()); - } - - bool IsReuseLastSeed() { return reuse_last_seed; } - - void SetReuseLastSeed(bool reuse) { - reuse_last_seed = reuse; - // update global one - GdaConst::use_gda_user_seed = reuse; - if (reuse) { - last_seed_used = GdaConst::gda_user_seed; - OGRDataAdapter::GetInstance().AddEntry("use_gda_user_seed", "1"); - } else { - OGRDataAdapter::GetInstance().AddEntry("use_gda_user_seed", "0"); - } - } - - /** Implementation of WeightsManStateObserver interface */ - virtual void update(WeightsManState* o); - - virtual int numMustCloseToRemove(boost::uuids::uuid id) const; - - virtual void closeObserver(boost::uuids::uuid id); - protected: // The following seven are just temporary pointers into the corresponding // space-time data arrays below double* lags; double* localMoran; // The LISA double* sigLocalMoran; // The significances / pseudo p-vals - // The significance category, generated from sigLocalMoran and - // significance cuttoff values below. When saving results to Table, - // only results below significance_cuttoff are non-zero, but sigCat - // results themeslves never change. - //0: >0.05 1: 0.05, 2: 0.01, 3: 0.001, 4: 0.0001 - int* sigCat; - // not-sig=0 HH=1, LL=2, HL=3, LH=4, isolate=5, undef=6. Note: value of - // 0 never appears in cluster itself, it only appears when - // saving results to the Table and indirectly in the map legend - int* cluster; - double* data1; - double* data2; - + public: std::vector lags_vecs; std::vector local_moran_vecs; - std::vector sig_local_moran_vecs; - std::vector sig_cat_vecs; - std::vector cluster_vecs; std::vector data1_vecs; std::vector data2_vecs; - - boost::uuids::uuid w_id; - std::vector Gal_vecs; - std::vector Gal_vecs_orig; - //const GalElement* W; - - wxString weight_name; + bool isBivariate; LisaType lisa_type; - int num_obs; // total # obs including neighborless obs - int num_time_vals; // number of valid time periods based on var_info - - // These two variables should be empty for LisaMapCanvas - std::vector data; // data[variable][time][obs] - std::vector undef_data; // undef_data[variable][time][obs] - std::vector > undef_tms; - - // All LisaMapCanvas objects synchronize themselves - // from the following 6 variables. - int ref_var_index; - std::vector var_info; - bool is_any_time_variant; - bool is_any_sync_with_global_time; - std::vector map_valid; - std::vector map_error_message; - - bool GetHasIsolates(int time) { return has_isolates[time]; } - bool GetHasUndefined(int time) { return has_undefined[time]; } - - void registerObserver(LisaCoordinatorObserver* o); - void removeObserver(LisaCoordinatorObserver* o); - void notifyObservers(); - /** The list of registered observer objects. */ - std::list observers; - - void CalcPseudoP(); - void CalcPseudoP_range(const GalElement* W, const std::vector& undefs, - int obs_start, int obs_end, uint64_t seed_start); - - void InitFromVarInfo(); - void VarInfoAttributeChange(); + virtual void ComputeLarger(int cnt, std::vector permNeighbors, + std::vector& countLarger); + virtual void Init(); + virtual void Calc(); + virtual void DeallocateVectors(); + virtual void AllocateVectors(); + virtual void CalcPseudoP(); void GetRawData(int time, double* data1, double* data2); - -protected: - void DeallocateVectors(); - void AllocateVectors(); - - void CalcPseudoP_threaded(const GalElement* W, const std::vector& undefs); - void CalcLisa(); void StandardizeData(); - std::vector has_undefined; - std::vector has_isolates; - bool row_standardize; - bool calc_significances; // if false, then p-vals will never be needed - uint64_t last_seed_used; - bool reuse_last_seed; - - WeightsManState* w_man_state; - WeightsManInterface* w_man_int; - - GalWeight* weights; }; #endif diff --git a/Explore/LisaMapNewView.cpp b/Explore/LisaMapNewView.cpp index c6c8cdef0..f61879907 100644 --- a/Explore/LisaMapNewView.cpp +++ b/Explore/LisaMapNewView.cpp @@ -32,13 +32,16 @@ #include "../DialogTools/PermutationCounterDlg.h" #include "../DialogTools/SaveToTableDlg.h" #include "../DialogTools/VariableSettingsDlg.h" +#include "../DialogTools/RandomizationDlg.h" +#include "../VarCalc/WeightsManInterface.h" + #include "ConditionalClusterMapView.h" #include "LisaCoordinator.h" #include "LisaMapNewView.h" -#include "../ShpFile.h" -IMPLEMENT_CLASS(LisaMapCanvas, MapCanvas) -BEGIN_EVENT_TABLE(LisaMapCanvas, MapCanvas) + +IMPLEMENT_CLASS(LisaMapCanvas, AbstractMapCanvas) +BEGIN_EVENT_TABLE(LisaMapCanvas, AbstractMapCanvas) EVT_PAINT(TemplateCanvas::OnPaint) EVT_ERASE_BACKGROUND(TemplateCanvas::OnEraseBackground) EVT_MOUSE_EVENTS(TemplateCanvas::OnMouseEvent) @@ -51,65 +54,50 @@ LisaMapCanvas::LisaMapCanvas(wxWindow *parent, TemplateFrame* t_frame, Project* project, LisaCoordinator* lisa_coordinator, CatClassification::CatClassifType theme_type_s, - bool isBivariate, bool isEBRate, + bool isClust, + bool isBivariate, + bool isEBRate, + wxString menu_xrcid_s, const wxPoint& pos, const wxSize& size) -:MapCanvas(parent, t_frame, project, - vector(0), vector(0), - CatClassification::no_theme, - no_smoothing, 1, boost::uuids::nil_uuid(), pos, size), +: AbstractMapCanvas(parent, t_frame, project, lisa_coordinator, theme_type_s, isClust), lisa_coord(lisa_coordinator), -is_clust(theme_type_s==CatClassification::lisa_categories), is_bi(isBivariate), is_rate(isEBRate), is_diff(lisa_coordinator->lisa_type == LisaCoordinator::differential) { - LOG_MSG("Entering LisaMapCanvas::LisaMapCanvas"); + wxLogMessage("Entering LisaMapCanvas::LisaMapCanvas"); + + menu_xrcid = menu_xrcid_s; + str_highhigh = _("High-High"); + str_highlow = _("High-Low"); + str_lowlow = _("Low-Low"); + str_lowhigh= _("Low-High"); + + SetPredefinedColor(str_highhigh, wxColour(255, 0, 0)); + SetPredefinedColor(str_highlow, wxColour(255, 150, 150)); + SetPredefinedColor(str_lowlow, wxColour(0, 0, 255)); + SetPredefinedColor(str_lowhigh, wxColour(150, 150, 255)); - cat_classif_def.cat_classif_type = theme_type_s; - // must set var_info times from LisaCoordinator initially - var_info = lisa_coordinator->var_info; - template_frame->ClearAllGroupDependencies(); - for (int t=0, sz=var_info.size(); tAddGroupDependancy(var_info[t].name); - } CreateAndUpdateCategories(); - - LOG_MSG("Exiting LisaMapCanvas::LisaMapCanvas"); -} -LisaMapCanvas::~LisaMapCanvas() -{ - LOG_MSG("In LisaMapCanvas::~LisaMapCanvas"); + wxLogMessage("Exiting LisaMapCanvas::LisaMapCanvas"); } -void LisaMapCanvas::DisplayRightClickMenu(const wxPoint& pos) +LisaMapCanvas::~LisaMapCanvas() { - LOG_MSG("Entering LisaMapCanvas::DisplayRightClickMenu"); - // Workaround for right-click not changing window focus in OSX / wxW 3.0 - wxActivateEvent ae(wxEVT_NULL, true, 0, wxActivateEvent::Reason_Mouse); - ((LisaMapFrame*) template_frame)->OnActivate(ae); - - wxMenu* optMenu = wxXmlResource::Get()-> - LoadMenu("ID_LISAMAP_NEW_VIEW_MENU_OPTIONS"); - AddTimeVariantOptionsToMenu(optMenu); - SetCheckMarks(optMenu); - - template_frame->UpdateContextMenuItems(optMenu); - template_frame->PopupMenu(optMenu, pos + GetPosition()); - template_frame->UpdateOptionMenuItems(); - LOG_MSG("Exiting LisaMapCanvas::DisplayRightClickMenu"); + wxLogMessage("In LisaMapCanvas::~LisaMapCanvas"); } wxString LisaMapCanvas::GetCanvasTitle() { wxString lisa_t; - if (is_clust && !is_bi) lisa_t = " LISA Cluster Map"; - if (is_clust && is_bi) lisa_t = " BiLISA Cluster Map"; - if (is_clust && is_diff) lisa_t = " Differential LISA Cluster Map"; + if (is_clust && !is_bi) lisa_t = _(" LISA Cluster Map"); + if (is_clust && is_bi) lisa_t = _(" BiLISA Cluster Map"); + if (is_clust && is_diff) lisa_t = _(" Differential LISA Cluster Map"); - if (!is_clust && !is_bi) lisa_t = " LISA Significance Map"; - if (!is_clust && is_bi) lisa_t = " BiLISA Significance Map"; - if (!is_clust && is_diff) lisa_t = " Differential Significance Map"; + if (!is_clust && !is_bi) lisa_t = _(" LISA Significance Map"); + if (!is_clust && is_bi) lisa_t = _(" BiLISA Significance Map"); + if (!is_clust && is_diff) lisa_t = _(" Differential Significance Map"); wxString field_t; if (is_bi) { @@ -125,511 +113,140 @@ wxString LisaMapCanvas::GetCanvasTitle() } wxString ret; - ret << lisa_t << ": " << lisa_coord->weight_name << ", "; - ret << field_t << " (" << lisa_coord->permutations << " perm)"; + ret << lisa_t << ": " << lisa_coord->GetWeightsName() << ", "; + ret << field_t << " (" << lisa_coord->GetNumPermutations() << " perm)"; return ret; } -/** This method definition is empty. It is here to override any call - to the parent-class method since smoothing and theme changes are not - supported by LISA maps */ -bool -LisaMapCanvas::ChangeMapType(CatClassification::CatClassifType new_map_theme, - SmoothingType new_map_smoothing) +wxString LisaMapCanvas::GetVariableNames() { - LOG_MSG("In LisaMapCanvas::ChangeMapType"); - return false; -} - -void LisaMapCanvas::SetCheckMarks(wxMenu* menu) -{ - // Update the checkmarks and enable/disable state for the - // following menu items if they were specified for this particular - // view in the xrc file. Items that cannot be enable/disabled, - // or are not checkable do not appear. - - MapCanvas::SetCheckMarks(menu); - - int sig_filter = lisa_coord->GetSignificanceFilter(); - - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_SIGNIFICANCE_FILTER_05"), - sig_filter == 1); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_SIGNIFICANCE_FILTER_01"), - sig_filter == 2); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_SIGNIFICANCE_FILTER_001"), - sig_filter == 3); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_SIGNIFICANCE_FILTER_0001"), - sig_filter == 4); - - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_USE_SPECIFIED_SEED"), - lisa_coord->IsReuseLastSeed()); -} + wxString field_t; + if (is_bi) { + field_t << GetNameWithTime(0) << "," << GetNameWithTime(1); + } else if (is_diff) { + field_t << GetNameWithTime(0) << " - " << GetNameWithTime(1); + }else { + field_t << GetNameWithTime(0); + } + if (is_rate) { + field_t << GetNameWithTime(0); + field_t << " / " << GetNameWithTime(1); + } -void LisaMapCanvas::TimeChange() -{ - LOG_MSG("Entering LisaMapCanvas::TimeChange"); - if (!is_any_sync_with_global_time) return; - - int cts = project->GetTimeState()->GetCurrTime(); - int ref_time = var_info[ref_var_index].time; - int ref_time_min = var_info[ref_var_index].time_min; - int ref_time_max = var_info[ref_var_index].time_max; - - if ((cts == ref_time) || - (cts > ref_time_max && ref_time == ref_time_max) || - (cts < ref_time_min && ref_time == ref_time_min)) return; - if (cts > ref_time_max) { - ref_time = ref_time_max; - } else if (cts < ref_time_min) { - ref_time = ref_time_min; - } else { - ref_time = cts; - } - for (int i=0; iGetHasIsolates(t)) - num_cats++; - if (lisa_coord->GetHasUndefined(t)) - num_cats++; - if (is_clust) { - num_cats += 5; - } else { - // significance map - // 0: >0.05 1: 0.05, 2: 0.01, 3: 0.001, 4: 0.0001 - int s_f = lisa_coord->GetSignificanceFilter(); - num_cats += 6 - s_f; - - // issue #474 only show significance levels that can be mapped for the given number of permutations, e.g., for 99 it would stop at 0.01, for 999 at 0.001, etc. - double sig_cutoff = lisa_coord->significance_cutoff; - int set_perm = lisa_coord->permutations; - stop_sig = 1.0 / (1.0 + set_perm); - - if ( sig_cutoff >= 0.0001 && stop_sig > 0.0001) { - num_cats -= 1; - } - if ( sig_cutoff >= 0.001 && stop_sig > 0.001 ) { - num_cats -= 1; - } - if ( sig_cutoff >= 0.01 && stop_sig > 0.01 ) { - num_cats -= 1; - } - } - cat_data.CreateCategoriesAtCanvasTm(num_cats, t); - - Shapefile::Header& hdr = project->main_data.header; - - if (is_clust) { - cat_data.SetCategoryLabel(t, 0, "Not Significant"); - - if (hdr.shape_type == Shapefile::POINT_TYP) { - cat_data.SetCategoryColor(t, 0, wxColour(190, 190, 190)); - } else { - cat_data.SetCategoryColor(t, 0, wxColour(240, 240, 240)); - } - cat_data.SetCategoryLabel(t, 1, "High-High"); - cat_data.SetCategoryColor(t, 1, wxColour(255, 0, 0)); - cat_data.SetCategoryLabel(t, 2, "Low-Low"); - cat_data.SetCategoryColor(t, 2, wxColour(0, 0, 255)); - cat_data.SetCategoryLabel(t, 3, "Low-High"); - cat_data.SetCategoryColor(t, 3, wxColour(150, 150, 255)); - cat_data.SetCategoryLabel(t, 4, "High-Low"); - cat_data.SetCategoryColor(t, 4, wxColour(255, 150, 150)); - if (lisa_coord->GetHasIsolates(t) && - lisa_coord->GetHasUndefined(t)) { - isolates_cat = 5; - undefined_cat = 6; - } else if (lisa_coord->GetHasUndefined(t)) { - undefined_cat = 5; - } else if (lisa_coord->GetHasIsolates(t)) { - isolates_cat = 5; - } - } else { - // 0: >0.05 1: 0.05, 2: 0.01, 3: 0.001, 4: 0.0001 - int s_f = lisa_coord->GetSignificanceFilter(); - cat_data.SetCategoryLabel(t, 0, "Not Significant"); - - if (hdr.shape_type == Shapefile::POINT_TYP) { - cat_data.SetCategoryColor(t, 0, wxColour(190, 190, 190)); - } else { - cat_data.SetCategoryColor(t, 0, wxColour(240, 240, 240)); - } - - int skip_cat = 0; - if (s_f <=4 && stop_sig <= 0.0001) { - cat_data.SetCategoryLabel(t, 5-s_f, "p = 0.0001"); - cat_data.SetCategoryColor(t, 5-s_f, wxColour(1, 70, 3)); - } else skip_cat++; - - if (s_f <= 3 && stop_sig <= 0.001) { - cat_data.SetCategoryLabel(t, 4-s_f, "p = 0.001"); - cat_data.SetCategoryColor(t, 4-s_f, wxColour(3, 116, 6)); - } else skip_cat++; - - if (s_f <= 2 && stop_sig <= 0.01) { - cat_data.SetCategoryLabel(t, 3-s_f, "p = 0.01"); - cat_data.SetCategoryColor(t, 3-s_f, wxColour(6, 196, 11)); - } else skip_cat++; - - if (s_f <= 1) { - cat_data.SetCategoryLabel(t, 2-s_f, "p = 0.05"); - cat_data.SetCategoryColor(t, 2-s_f, wxColour(75, 255, 80)); - } - if (lisa_coord->GetHasIsolates(t) && - lisa_coord->GetHasUndefined(t)) { - isolates_cat = 6 - s_f - skip_cat; - undefined_cat = 7 - s_f - skip_cat; - - } else if (lisa_coord->GetHasUndefined(t)) { - undefined_cat = 6 -s_f - skip_cat; - - } else if (lisa_coord->GetHasIsolates(t)) { - isolates_cat = 6 - s_f -skip_cat; - - } - } - if (undefined_cat != -1) { - cat_data.SetCategoryLabel(t, undefined_cat, "Undefined"); - cat_data.SetCategoryColor(t, undefined_cat, wxColour(70, 70, 70)); - } - if (isolates_cat != -1) { - cat_data.SetCategoryLabel(t, isolates_cat, "Neighborless"); - cat_data.SetCategoryColor(t, isolates_cat, wxColour(140, 140, 140)); - } - - double cuttoff = lisa_coord->significance_cutoff; - double* p = lisa_coord->sig_local_moran_vecs[t]; - int* cluster = lisa_coord->cluster_vecs[t]; - int* sigCat = lisa_coord->sig_cat_vecs[t]; - - if (is_clust) { - for (int i=0, iend=lisa_coord->num_obs; i cuttoff && cluster[i] != 5 && cluster[i] != 6) { - cat_data.AppendIdToCategory(t, 0, i); // not significant - } else if (cluster[i] == 5) { - cat_data.AppendIdToCategory(t, isolates_cat, i); - } else if (cluster[i] == 6) { - cat_data.AppendIdToCategory(t, undefined_cat, i); - } else { - cat_data.AppendIdToCategory(t, cluster[i], i); - } - } - } else { - int s_f = lisa_coord->GetSignificanceFilter(); - for (int i=0, iend=lisa_coord->num_obs; i cuttoff && cluster[i] != 5 && cluster[i] != 6) { - cat_data.AppendIdToCategory(t, 0, i); // not significant - } else if (cluster[i] == 5) { - cat_data.AppendIdToCategory(t, isolates_cat, i); - } else if (cluster[i] == 6) { - cat_data.AppendIdToCategory(t, undefined_cat, i); - } else { - cat_data.AppendIdToCategory(t, (sigCat[i]-s_f)+1, i); - } - } - } - for (int cat=0; catmy_times(var_info.size()); - for (int t=0; tvar_info; - template_frame->ClearAllGroupDependencies(); - for (int t=0; tAddGroupDependancy(var_info[t].name); - } - is_any_time_variant = lisa_coord->is_any_time_variant; - is_any_sync_with_global_time = lisa_coord->is_any_sync_with_global_time; - ref_var_index = lisa_coord->ref_var_index; - num_time_vals = lisa_coord->num_time_vals; - map_valid = lisa_coord->map_valid; - map_error_message = lisa_coord->map_error_message; -} - -void LisaMapCanvas::TimeSyncVariableToggle(int var_index) +void LisaMapCanvas::SetLabelsAndColorForClusters(int& num_cats, int t, CatClassifData& cat_data) { - LOG_MSG("In LisaMapCanvas::TimeSyncVariableToggle"); - lisa_coord->var_info[var_index].sync_with_global_time = - !lisa_coord->var_info[var_index].sync_with_global_time; - for (int i=0; ivar_info[i].time = var_info[i].time; - } - lisa_coord->VarInfoAttributeChange(); - lisa_coord->InitFromVarInfo(); - lisa_coord->notifyObservers(); + // NotSig LL HH LH HL + num_cats += 5; + cat_data.CreateCategoriesAtCanvasTm(num_cats, t); + + int undefined_cat = -1; + int isolates_cat = -1; + bool has_isolates = a_coord->GetHasIsolates(t); + bool has_undefined = a_coord->GetHasUndefined(t); + double sig_cutoff = a_coord->GetSignificanceCutoff(); + double* p = a_coord->GetLocalSignificanceValues(t); + int* cluster = a_coord->GetClusterIndicators(t); + + wxColour not_sig_clr = clr_not_sig_polygon; + if (project->IsPointTypeData()) not_sig_clr = clr_not_sig_point; + cat_data.SetCategoryColor(t, 0, not_sig_clr); + cat_data.SetCategoryLabel(t, 0, str_not_sig); + + cat_data.SetCategoryLabel(t, 1, str_highhigh); + cat_data.SetCategoryColor(t, 1, lbl_color_dict[str_highhigh]); + cat_data.SetCategoryLabel(t, 2, str_lowlow); + cat_data.SetCategoryColor(t, 2, lbl_color_dict[str_lowlow]); + cat_data.SetCategoryLabel(t, 3, str_lowhigh); + cat_data.SetCategoryColor(t, 3, lbl_color_dict[str_lowhigh]); + cat_data.SetCategoryLabel(t, 4, str_highlow); + cat_data.SetCategoryColor(t, 4, lbl_color_dict[str_highlow]); + + if (has_isolates && has_undefined) { + isolates_cat = 5; + undefined_cat = 6; + } else if (has_undefined) { + undefined_cat = 5; + } else if (has_isolates) { + isolates_cat = 5; + } + if (undefined_cat != -1) { + cat_data.SetCategoryLabel(t, undefined_cat, str_undefined); + cat_data.SetCategoryColor(t, undefined_cat, lbl_color_dict[str_undefined]); + } + if (isolates_cat != -1) { + cat_data.SetCategoryLabel(t, isolates_cat, str_neighborless); + cat_data.SetCategoryColor(t, isolates_cat, lbl_color_dict[str_neighborless]); + } + for (int i=0; i sig_cutoff && cluster[i] != 5 && cluster[i] != 6) { + cat_data.AppendIdToCategory(t, 0, i); // not significant + } else if (cluster[i] == 5) { + cat_data.AppendIdToCategory(t, isolates_cat, i); + } else if (cluster[i] == 6) { + cat_data.AppendIdToCategory(t, undefined_cat, i); + } else { + cat_data.AppendIdToCategory(t, cluster[i], i); + } + } } - -IMPLEMENT_CLASS(LisaMapFrame, MapFrame) - BEGIN_EVENT_TABLE(LisaMapFrame, MapFrame) +IMPLEMENT_CLASS(LisaMapFrame, AbstractMapFrame) + BEGIN_EVENT_TABLE(LisaMapFrame, AbstractMapFrame) EVT_ACTIVATE(LisaMapFrame::OnActivate) END_EVENT_TABLE() LisaMapFrame::LisaMapFrame(wxFrame *parent, Project* project, LisaCoordinator* lisa_coordinator, - bool isClusterMap, bool isBivariate, + bool isClusterMap, + bool isBivariate, bool isEBRate, const wxPoint& pos, const wxSize& size, const long style) -: MapFrame(parent, project, pos, size, style), -lisa_coord(lisa_coordinator) +: AbstractMapFrame(parent, project, lisa_coordinator), +lisa_coord(lisa_coordinator), +is_clust(isClusterMap), +is_bivariate(isBivariate), +is_ebrate(isEBRate) { - LOG_MSG("Entering LisaMapFrame::LisaMapFrame"); - - int width, height; - GetClientSize(&width, &height); - - wxSplitterWindow* splitter_win = new wxSplitterWindow(this,-1, - wxDefaultPosition, wxDefaultSize, - wxSP_3D|wxSP_LIVE_UPDATE|wxCLIP_CHILDREN); - splitter_win->SetMinimumPaneSize(10); - - CatClassification::CatClassifType theme_type_s = isClusterMap ? CatClassification::lisa_categories : CatClassification::lisa_significance; - - wxPanel* rpanel = new wxPanel(splitter_win); - template_canvas = new LisaMapCanvas(rpanel, this, project, - lisa_coordinator, - theme_type_s, - isBivariate, - isEBRate, - wxDefaultPosition, - wxDefaultSize); - template_canvas->SetScrollRate(1,1); - wxBoxSizer* rbox = new wxBoxSizer(wxVERTICAL); - rbox->Add(template_canvas, 1, wxEXPAND); - rpanel->SetSizer(rbox); - - wxPanel* lpanel = new wxPanel(splitter_win); - template_legend = new MapNewLegend(lpanel, template_canvas, - wxPoint(0,0), wxSize(0,0)); - wxBoxSizer* lbox = new wxBoxSizer(wxVERTICAL); - template_legend->GetContainingSizer()->Detach(template_legend); - lbox->Add(template_legend, 1, wxEXPAND); - lpanel->SetSizer(lbox); - - splitter_win->SplitVertically(lpanel, rpanel, GdaConst::map_default_legend_width); - - wxPanel* toolbar_panel = new wxPanel(this,-1, wxDefaultPosition); - wxBoxSizer* toolbar_sizer= new wxBoxSizer(wxVERTICAL); - wxToolBar* tb = wxXmlResource::Get()->LoadToolBar(toolbar_panel, "ToolBar_MAP"); - SetupToolbar(); - toolbar_sizer->Add(tb, 0, wxEXPAND|wxALL); - toolbar_panel->SetSizerAndFit(toolbar_sizer); - - wxBoxSizer* sizer = new wxBoxSizer(wxVERTICAL); - sizer->Add(toolbar_panel, 0, wxEXPAND|wxALL); - sizer->Add(splitter_win, 1, wxEXPAND|wxALL); - SetSizer(sizer); - //splitter_win->SetSize(wxSize(width,height)); - SetAutoLayout(true); - - DisplayStatusBar(true); - SetTitle(template_canvas->GetCanvasTitle()); - - - lisa_coord->registerObserver(this); - Show(true); - LOG_MSG("Exiting LisaMapFrame::LisaMapFrame"); + wxLogMessage("Entering LisaMapFrame::LisaMapFrame"); + no_update_weights = true; + Init(); + wxLogMessage("Exiting LisaMapFrame::LisaMapFrame"); } LisaMapFrame::~LisaMapFrame() { - LOG_MSG("In LisaMapFrame::~LisaMapFrame"); - if (lisa_coord) { - lisa_coord->removeObserver(this); - lisa_coord = 0; - } -} - -void LisaMapFrame::OnActivate(wxActivateEvent& event) -{ - LOG_MSG("In LisaMapFrame::OnActivate"); - if (event.GetActive()) { - RegisterAsActive("LisaMapFrame", GetTitle()); - } - if ( event.GetActive() && template_canvas ) template_canvas->SetFocus(); -} - -void LisaMapFrame::MapMenus() -{ - LOG_MSG("In LisaMapFrame::MapMenus"); - wxMenuBar* mb = GdaFrame::GetGdaFrame()->GetMenuBar(); - // Map Options Menus - wxMenu* optMenu = wxXmlResource::Get()-> - LoadMenu("ID_LISAMAP_NEW_VIEW_MENU_OPTIONS"); - ((MapCanvas*) template_canvas)-> - AddTimeVariantOptionsToMenu(optMenu); - ((MapCanvas*) template_canvas)->SetCheckMarks(optMenu); - GeneralWxUtils::ReplaceMenu(mb, "Options", optMenu); - UpdateOptionMenuItems(); -} - -void LisaMapFrame::UpdateOptionMenuItems() -{ - TemplateFrame::UpdateOptionMenuItems(); // set common items first - wxMenuBar* mb = GdaFrame::GetGdaFrame()->GetMenuBar(); - int menu = mb->FindMenu("Options"); - if (menu == wxNOT_FOUND) { - LOG_MSG("LisaMapFrame::UpdateOptionMenuItems: " - "Options menu not found"); - } else { - ((LisaMapCanvas*) template_canvas)->SetCheckMarks(mb->GetMenu(menu)); - } -} - -void LisaMapFrame::UpdateContextMenuItems(wxMenu* menu) -{ - // Update the checkmarks and enable/disable state for the - // following menu items if they were specified for this particular - // view in the xrc file. Items that cannot be enable/disabled, - // or are not checkable do not appear. - - TemplateFrame::UpdateContextMenuItems(menu); // set common items -} - -void LisaMapFrame::RanXPer(int permutation) -{ - if (permutation < 9) permutation = 9; - if (permutation > 99999) permutation = 99999; - lisa_coord->permutations = permutation; - lisa_coord->CalcPseudoP(); - lisa_coord->notifyObservers(); -} - -void LisaMapFrame::OnRan99Per(wxCommandEvent& event) -{ - RanXPer(99); -} - -void LisaMapFrame::OnRan199Per(wxCommandEvent& event) -{ - RanXPer(199); -} - -void LisaMapFrame::OnRan499Per(wxCommandEvent& event) -{ - RanXPer(499); + wxLogMessage("In LisaMapFrame::~LisaMapFrame"); + // the following code block will be exceuted in AbstractClusterMapFrame + //if (lisa_coord) { + // lisa_coord->removeObserver(this); + // lisa_coord = 0; + //} } -void LisaMapFrame::OnRan999Per(wxCommandEvent& event) +CatClassification::CatClassifType LisaMapFrame::GetThemeType() { - RanXPer(999); -} - -void LisaMapFrame::OnRanOtherPer(wxCommandEvent& event) -{ - PermutationCounterDlg dlg(this); - if (dlg.ShowModal() == wxID_OK) { - long num; - dlg.m_number->GetValue().ToLong(&num); - RanXPer(num); - } -} - -void LisaMapFrame::OnUseSpecifiedSeed(wxCommandEvent& event) -{ - lisa_coord->SetReuseLastSeed(!lisa_coord->IsReuseLastSeed()); -} - -void LisaMapFrame::OnSpecifySeedDlg(wxCommandEvent& event) -{ - uint64_t last_seed = lisa_coord->GetLastUsedSeed(); - wxString m; - m << "The last seed used by the pseudo random\nnumber "; - m << "generator was " << last_seed << ".\n"; - m << "\nEnter a seed value to use between\n0 and "; - m << std::numeric_limits::max() << "."; - long long unsigned int val; - wxString dlg_val; - wxString cur_val; - cur_val << last_seed; - - wxTextEntryDialog dlg(NULL, m, "Enter a seed value", cur_val); - if (dlg.ShowModal() != wxID_OK) return; - dlg_val = dlg.GetValue(); - dlg_val.Trim(true); - dlg_val.Trim(false); - if (dlg_val.IsEmpty()) return; - if (dlg_val.ToULongLong(&val)) { - if (!lisa_coord->IsReuseLastSeed()) lisa_coord->SetLastUsedSeed(true); - uint64_t new_seed_val = val; - lisa_coord->SetLastUsedSeed(new_seed_val); - } else { - wxString m; - m << "\"" << dlg_val << "\" is not a valid seed. Seed unchanged."; - wxMessageDialog dlg(NULL, m, "Error", wxOK | wxICON_ERROR); - dlg.ShowModal(); - } + theme_type = is_clust ? CatClassification::lisa_categories : CatClassification::lisa_significance; + return theme_type; } -void LisaMapFrame::SetSigFilterX(int filter) +TemplateCanvas* LisaMapFrame::CreateMapCanvas(wxPanel* panel) { - if (filter == lisa_coord->GetSignificanceFilter()) return; - lisa_coord->SetSignificanceFilter(filter); - lisa_coord->notifyObservers(); - UpdateOptionMenuItems(); + menu_xrcid = "ID_LISAMAP_NEW_VIEW_MENU_OPTIONS"; + return new LisaMapCanvas(panel, this, project, + lisa_coord, + theme_type, + is_clust, + is_bivariate, + is_ebrate, + menu_xrcid); } -void LisaMapFrame::OnSigFilter05(wxCommandEvent& event) -{ - SetSigFilterX(1); -} - -void LisaMapFrame::OnSigFilter01(wxCommandEvent& event) -{ - SetSigFilterX(2); -} - -void LisaMapFrame::OnSigFilter001(wxCommandEvent& event) -{ - SetSigFilterX(3); -} - -void LisaMapFrame::OnSigFilter0001(wxCommandEvent& event) -{ - SetSigFilterX(4); -} - -void LisaMapFrame::OnSaveLisa(wxCommandEvent& event) +void LisaMapFrame::OnSaveResult(wxCommandEvent& event) { int t = template_canvas->cat_data.GetCurrentCanvasTmStep(); @@ -658,9 +275,9 @@ void LisaMapFrame::OnSaveLisa(wxCommandEvent& event) data[0].type = GdaConst::double_type; data[0].undefined = &undefs; - double cuttoff = lisa_coord->significance_cutoff; - double* p = lisa_coord->sig_local_moran_vecs[t]; - int* cluster = lisa_coord->cluster_vecs[t]; + double cuttoff = lisa_coord->GetSignificanceCutoff(); + double* p = lisa_coord->GetLocalSignificanceValues(t); + int* cluster = lisa_coord->GetClusterIndicators(t); std::vector clust(lisa_coord->num_obs); for (int i=0, iend=lisa_coord->num_obs; i cuttoff && cluster[i] != 5 && cluster[i] != 6) { @@ -709,149 +326,14 @@ void LisaMapFrame::OnSaveLisa(wxCommandEvent& event) dlg.ShowModal(); } -void LisaMapFrame::CoreSelectHelper(const std::vector& elem) -{ - HighlightState* highlight_state = project->GetHighlightState(); - std::vector& hs = highlight_state->GetHighlight(); - bool selection_changed = false; - - for (int i=0; inum_obs; i++) { - if (!hs[i] && elem[i]) { - hs[i] = true; - selection_changed = true; - } else if (hs[i] && !elem[i]) { - hs[i] = false; - selection_changed = true; - } - } - if (selection_changed) { - highlight_state->SetEventType(HLStateInt::delta); - highlight_state->notifyObservers(); - } -} - -void LisaMapFrame::OnSelectCores(wxCommandEvent& event) -{ - LOG_MSG("Entering LisaMapFrame::OnSelectCores"); - - std::vector elem(lisa_coord->num_obs, false); - int ts = template_canvas->cat_data.GetCurrentCanvasTmStep(); - int* clust = lisa_coord->cluster_vecs[ts]; - int* sig_cat = lisa_coord->sig_cat_vecs[ts]; - int sf = lisa_coord->significance_filter; - - // add all cores to elem list. - for (int i=0; inum_obs; i++) { - if (clust[i] >= 1 && clust[i] <= 4 && sig_cat[i] >= sf) { - elem[i] = true; - } - } - CoreSelectHelper(elem); - - LOG_MSG("Exiting LisaMapFrame::OnSelectCores"); -} - -void LisaMapFrame::OnSelectNeighborsOfCores(wxCommandEvent& event) -{ - LOG_MSG("Entering LisaMapFrame::OnSelectNeighborsOfCores"); - - std::vector elem(lisa_coord->num_obs, false); - int ts = template_canvas->cat_data.GetCurrentCanvasTmStep(); - int* clust = lisa_coord->cluster_vecs[ts]; - int* sig_cat = lisa_coord->sig_cat_vecs[ts]; - int sf = lisa_coord->significance_filter; - const GalElement* W = lisa_coord->Gal_vecs_orig[ts]->gal; - - // add all cores and neighbors of cores to elem list - for (int i=0; inum_obs; i++) { - if (clust[i] >= 1 && clust[i] <= 4 && sig_cat[i] >= sf) { - elem[i] = true; - const GalElement& e = W[i]; - for (int j=0, jend=e.Size(); jnum_obs; i++) { - if (clust[i] >= 1 && clust[i] <= 4 && sig_cat[i] >= sf) { - elem[i] = false; - } - } - CoreSelectHelper(elem); - - LOG_MSG("Exiting LisaMapFrame::OnSelectNeighborsOfCores"); -} - -void LisaMapFrame::OnSelectCoresAndNeighbors(wxCommandEvent& event) -{ - LOG_MSG("Entering LisaMapFrame::OnSelectCoresAndNeighbors"); - - std::vector elem(lisa_coord->num_obs, false); - int ts = template_canvas->cat_data.GetCurrentCanvasTmStep(); - int* clust = lisa_coord->cluster_vecs[ts]; - int* sig_cat = lisa_coord->sig_cat_vecs[ts]; - int sf = lisa_coord->significance_filter; - const GalElement* W = lisa_coord->Gal_vecs_orig[ts]->gal; - - // add all cores and neighbors of cores to elem list - for (int i=0; inum_obs; i++) { - if (clust[i] >= 1 && clust[i] <= 4 && sig_cat[i] >= sf) { - elem[i] = true; - const GalElement& e = W[i]; - for (int j=0, jend=e.Size(); jcat_data.GetCurrentCanvasTmStep(); - GalWeight* gal_weights = lisa_coord->Gal_vecs_orig[ts]; - - HighlightState& hs = *project->GetHighlightState(); - std::vector& h = hs.GetHighlight(); - int nh_cnt = 0; - std::vector add_elem(gal_weights->num_obs, false); - - std::vector new_highlight_ids; - - for (int i=0; inum_obs; i++) { - if (h[i]) { - GalElement& e = gal_weights->gal[i]; - for (int j=0, jend=e.Size(); j 0) { - hs.SetEventType(HLStateInt::delta); - hs.notifyObservers(); - } -} - void LisaMapFrame::OnShowAsConditionalMap(wxCommandEvent& event) { VariableSettingsDlg dlg(project, VariableSettingsDlg::bivariate, false, false, _("Conditional LISA Map Variables"), - _("Horizontal Cells"), - _("Vertical Cells")); + _("Horizontal Cells"), _("Vertical Cells"), + "", "", false, false, false, // default + true, true, false, false); if (dlg.ShowModal() != wxID_OK) { return; @@ -865,39 +347,3 @@ void LisaMapFrame::OnShowAsConditionalMap(wxCommandEvent& event) title, wxDefaultPosition, GdaConst::cond_view_default_size); } - -/** Called by LisaCoordinator to notify that state has changed. State changes - can include: - - variable sync change and therefore all lisa categories have changed - - significance level has changed and therefore categories have changed - - new randomization for p-vals and therefore categories have changed */ -void LisaMapFrame::update(LisaCoordinator* o) -{ - LisaMapCanvas* lc = (LisaMapCanvas*) template_canvas; - lc->SyncVarInfoFromCoordinator(); - lc->CreateAndUpdateCategories(); - if (template_legend) template_legend->Recreate(); - SetTitle(lc->GetCanvasTitle()); - lc->Refresh(); -} - -void LisaMapFrame::closeObserver(LisaCoordinator* o) -{ - LOG_MSG("In LisaMapFrame::closeObserver(LisaCoordinator*)"); - if (lisa_coord) { - lisa_coord->removeObserver(this); - lisa_coord = 0; - } - Close(true); -} - -void LisaMapFrame::GetVizInfo(std::vector& clusters) -{ - if (lisa_coord) { - if(lisa_coord->sig_cat_vecs.size()>0) { - for (int i=0; inum_obs;i++) { - clusters.push_back(lisa_coord->sig_cat_vecs[0][i]); - } - } - } -} diff --git a/Explore/LisaMapNewView.h b/Explore/LisaMapNewView.h index be99e63eb..22dcc7a73 100644 --- a/Explore/LisaMapNewView.h +++ b/Explore/LisaMapNewView.h @@ -21,97 +21,75 @@ #define __GEODA_CENTER_LISA_MAP_NEW_VIEW_H__ #include "MapNewView.h" -#include "LisaCoordinatorObserver.h" +#include "AbstractClusterMap.h" #include "../GdaConst.h" class LisaMapFrame; class LisaMapCanvas; class LisaCoordinator; -class LisaMapCanvas : public MapCanvas +class LisaMapCanvas : public AbstractMapCanvas { DECLARE_CLASS(LisaMapCanvas) public: - LisaMapCanvas(wxWindow *parent, TemplateFrame* t_frame, - Project* project, - LisaCoordinator* lisa_coordinator, - CatClassification::CatClassifType theme_type, - bool isBivariate, bool isEBRate, - const wxPoint& pos = wxDefaultPosition, - const wxSize& size = wxDefaultSize); + LisaMapCanvas(wxWindow *parent, TemplateFrame* t_frame, + Project* project, + LisaCoordinator* lisa_coordinator, + CatClassification::CatClassifType theme_type, + bool isClust, + bool isBivariate, + bool isEBRate, + wxString menu_xrcid, + const wxPoint& pos = wxDefaultPosition, + const wxSize& size = wxDefaultSize); virtual ~LisaMapCanvas(); - virtual void DisplayRightClickMenu(const wxPoint& pos); + + virtual void SetLabelsAndColorForClusters(int& num_cats, int t, + CatClassifData& cat_data); + virtual wxString GetCanvasTitle(); - virtual bool ChangeMapType(CatClassification::CatClassifType new_map_theme, - SmoothingType new_map_smoothing); - virtual void SetCheckMarks(wxMenu* menu); - virtual void TimeChange(); - void SyncVarInfoFromCoordinator(); - virtual void CreateAndUpdateCategories(); - virtual void TimeSyncVariableToggle(int var_index); - + virtual wxString GetVariableNames(); bool is_diff; protected: LisaCoordinator* lisa_coord; - bool is_clust; // true = Cluster Map, false = Significance Map bool is_bi; // true = Bivariate, false = Univariate bool is_rate; // true = Moran Empirical Bayes Rate Smoothing + wxString str_highhigh; + wxString str_highlow; + wxString str_lowlow; + wxString str_lowhigh; + DECLARE_EVENT_TABLE() }; -class LisaMapFrame : public MapFrame, public LisaCoordinatorObserver +class LisaMapFrame : public AbstractMapFrame { DECLARE_CLASS(LisaMapFrame) public: LisaMapFrame(wxFrame *parent, Project* project, - LisaCoordinator* lisa_coordinator, - bool isClusterMap, bool isBivariate, - bool isEBRate, - const wxPoint& pos = wxDefaultPosition, - const wxSize& size = GdaConst::map_default_size, - const long style = wxDEFAULT_FRAME_STYLE); + LisaCoordinator* lisa_coordinator, + bool isClusterMap, + bool isBivariate, + bool isEBRate, + const wxPoint& pos = wxDefaultPosition, + const wxSize& size = GdaConst::map_default_size, + const long style = wxDEFAULT_FRAME_STYLE); virtual ~LisaMapFrame(); - void OnActivate(wxActivateEvent& event); - virtual void MapMenus(); - virtual void UpdateOptionMenuItems(); - virtual void UpdateContextMenuItems(wxMenu* menu); - - void RanXPer(int permutation); - void OnRan99Per(wxCommandEvent& event); - void OnRan199Per(wxCommandEvent& event); - void OnRan499Per(wxCommandEvent& event); - void OnRan999Per(wxCommandEvent& event); - void OnRanOtherPer(wxCommandEvent& event); - - void OnUseSpecifiedSeed(wxCommandEvent& event); - void OnSpecifySeedDlg(wxCommandEvent& event); - - void SetSigFilterX(int filter); - void OnSigFilter05(wxCommandEvent& event); - void OnSigFilter01(wxCommandEvent& event); - void OnSigFilter001(wxCommandEvent& event); - void OnSigFilter0001(wxCommandEvent& event); - - void OnSaveLisa(wxCommandEvent& event); - - void OnSelectCores(wxCommandEvent& event); - void OnSelectNeighborsOfCores(wxCommandEvent& event); - void OnSelectCoresAndNeighbors(wxCommandEvent& event); - void OnAddNeighborToSelection(wxCommandEvent& event); - - void OnShowAsConditionalMap(wxCommandEvent& event); - - virtual void update(LisaCoordinator* o); - virtual void closeObserver(LisaCoordinator* o); - - void GetVizInfo(std::vector& clusters); + virtual CatClassification::CatClassifType GetThemeType(); + virtual TemplateCanvas* CreateMapCanvas(wxPanel* rpanel); + virtual void OnSaveResult(wxCommandEvent& event); + virtual void OnShowAsConditionalMap(wxCommandEvent& event); + protected: - void CoreSelectHelper(const std::vector& elem); LisaCoordinator* lisa_coord; - + CatClassification::CatClassifType theme_type; + bool is_clust; + bool is_bivariate; + bool is_ebrate; + DECLARE_EVENT_TABLE() }; diff --git a/Explore/LisaScatterPlotView.cpp b/Explore/LisaScatterPlotView.cpp index 39706287d..0736c756a 100644 --- a/Explore/LisaScatterPlotView.cpp +++ b/Explore/LisaScatterPlotView.cpp @@ -36,7 +36,7 @@ #include "../DialogTools/PermutationCounterDlg.h" #include "../DialogTools/RandomizationDlg.h" #include "../DialogTools/SaveToTableDlg.h" -#include "../ShapeOperations/ShapeUtils.h" + #include "LisaCoordinator.h" #include "LisaScatterPlotView.h" @@ -97,11 +97,13 @@ LisaScatterPlotCanvas::~LisaScatterPlotCanvas() if (rand_dlg) { rand_dlg->Destroy(); } + pre_foreground_shps.clear(); } void LisaScatterPlotCanvas::ShowRegimesRegression(bool flag) { is_show_regimes_regression = flag; + isResize = true; PopulateCanvas(); } @@ -132,8 +134,8 @@ void LisaScatterPlotCanvas::AddTimeVariantOptionsToMenu(wxMenu* menu) wxMenu* menu1 = new wxMenu(wxEmptyString); for (int i=0; iAppendCheckItem(GdaConst::ID_TIME_SYNC_VAR1+i, s, s); mi->Check(var_info[i].sync_with_global_time); @@ -141,8 +143,8 @@ void LisaScatterPlotCanvas::AddTimeVariantOptionsToMenu(wxMenu* menu) } menu->AppendSeparator(); - menu->Append(wxID_ANY, "Time Variable Options", menu1, - "Time Variable Options"); + menu->Append(wxID_ANY, _("Time Variable Options"), menu1, + _("Time Variable Options")); } wxString LisaScatterPlotCanvas::GetCanvasTitle() @@ -163,21 +165,54 @@ wxString LisaScatterPlotCanvas::GetCanvasTitle() v1 << ")"; } } - wxString w(lisa_coord->weight_name); + wxString w(lisa_coord->GetWeightsName()); if (is_bi) { - s << "Bivariate Moran's I (" << w << "): "; - s << v0 << " and lagged " << v1; + s = _("Bivariate Moran's I (%s): %s and lagged %s"); + s = wxString::Format(s, w, v0, v1); } else if (is_rate) { - s << "Emp Bayes Rate Std Moran's I (" << w << "): "; - s << v0 << " / " << v1; + s = _("Emp Bayes Rate Std Moran's I (%s): %s / %s"); + s = wxString::Format(s, w, v0, v1); } else if (is_diff) { - s << "Differential Moran's I (" << w << "): " << v0 << " - " << v1; + s = _("Differential Moran's I (%s): %s - %s"); + s = wxString::Format(s, w, v0, v1); } else { - s << "Moran's I (" << w << "): " << v0; + s = _("Moran's I (%s): %s"); + s = wxString::Format(s, w, v0); } return s; } +wxString LisaScatterPlotCanvas::GetVariableNames() +{ + wxString s; + wxString v0(var_info_orig[0].name); + if (var_info_orig[0].is_time_variant) { + v0 << " (" << project->GetTableInt()-> + GetTimeString(var_info_orig[0].time); + v0 << ")"; + } + wxString v1; + if (is_bi || is_rate || is_diff) { + v1 << var_info_orig[1].name; + if (var_info_orig[1].is_time_variant) { + v1 << " (" << project->GetTableInt()-> + GetTimeString(var_info_orig[1].time); + v1 << ")"; + } + } + + if (is_bi) { + s << v0 << ", " << v1; + } else if (is_rate) { + s << v0 << " / " << v1; + } else if (is_diff) { + s << v0 << " - " << v1; + } else { + s << v0; + } + return s; +} + /** This virtual function will be called by the Scatter Plot base class to determine x and y axis labels. */ @@ -271,8 +306,9 @@ void LisaScatterPlotCanvas::TimeChange() sp_var_info[1].time = var_info[ref_var_index].time; //SetCurrentCanvasTmStep(ref_time - ref_time_min); invalidateBms(); - PopulateCanvas(); - Refresh(); + isResize = true; + //PopulateCanvas(); + Refresh(); } /** Copy everything in var_info except for current time field for each @@ -317,6 +353,9 @@ void LisaScatterPlotCanvas::SyncVarInfoFromCoordinator() x_undef_data.resize(extents[num_time_vals][num_obs]); y_undef_data.resize(extents[num_time_vals][num_obs]); + GalWeight* w = lisa_coord->Gal_vecs[t_ind]; + GalElement* gal = w->gal; + for (int t=0; tnum_time_vals; t++) { double x_min, x_max, y_min, y_max; @@ -329,6 +368,11 @@ void LisaScatterPlotCanvas::SyncVarInfoFromCoordinator() x_undef_data[t][i] = lisa_coord->undef_data[0][t][i]; y_undef_data[t][i] = lisa_coord->undef_data[0][t][i]; + if (gal[i].Size() == 0) { + x_undef_data[t][i] = true; + y_undef_data[t][i] = true; + } + if (x_undef_data[t][i] || y_undef_data[t][i]) continue; @@ -380,6 +424,10 @@ void LisaScatterPlotCanvas::SyncVarInfoFromCoordinator() sp_var_info[i].max_over_time = sp_var_info[i].max[t]; } } + + if (is_diff) { + sp_var_info[i].time = sp_var_info[i].time_min; + } } } @@ -403,7 +451,7 @@ void LisaScatterPlotCanvas::FixedScaleVariableToggle(int var_index) void LisaScatterPlotCanvas::OnIdle(wxIdleEvent& event) { if (isResize) { - isResize = false; + int vs_w, vs_h; @@ -417,6 +465,8 @@ void LisaScatterPlotCanvas::OnIdle(wxIdleEvent& event) PopulateCanvas(); + isResize = false; + event.RequestMore(); // render continuously, not only once on idle } @@ -462,8 +512,26 @@ void LisaScatterPlotCanvas::PopulateCanvas() var_info_orig = var_info; var_info = sp_var_info; - - ScatterNewPlotCanvas::PopulateCanvas(); + if (selectable_shps.empty() || isResize) { + + ScatterNewPlotCanvas::PopulateCanvas(); + pre_foreground_shps.clear(); + BOOST_FOREACH( GdaShape* shp, foreground_shps ) { + pre_foreground_shps[shp] = true; + } + } else { + // popup previous foreground_shps + std::list tmp_shps; + BOOST_FOREACH( GdaShape* shp, foreground_shps ) { + if ( pre_foreground_shps.find(shp) == pre_foreground_shps.end()) { + delete shp; + } else { + tmp_shps.push_back(shp); + } + } + foreground_shps.clear(); + foreground_shps = tmp_shps; + } int n_hl = highlight_state->GetTotalHighlighted(); @@ -482,8 +550,8 @@ void LisaScatterPlotCanvas::PopulateCanvas() GdaScaleTrans sub_scale; sub_scale = last_scale_trans; - sub_scale.right_margin= sub_scale.screen_width - sub_scale.trans_x + 50; - sub_scale.left_margin = 40; + sub_scale.right_margin= sub_scale.screen_width - sub_scale.trans_x + 65; + sub_scale.left_margin = 45; sub_scale.calcAffineParams(); for (int i=0; isetPen(wxPen(wxColour(100,100,100))); pt->setBrush(*wxTRANSPARENT_BRUSH); pt->applyScaleTrans(ex_scale); @@ -523,6 +590,9 @@ void LisaScatterPlotCanvas::PopulateCanvas() UpdateRegSelectedLine(); UpdateRegExcludedLine(); + + //GdaSpline* lowess_reg_line_sel = new GdaSpline; + //foreground_shps.push_back(lowess_reg_line_sel); GdaAxis* x_baseline = new GdaAxis(GetNameWithTime(0), axis_scale_x, @@ -588,7 +658,7 @@ void LisaScatterPlotCanvas::PopulateCanvas() y_axis_through_origin1->applyScaleTrans(ex_scale); } - wxString str = wxString::Format("selected: %.4f", + wxString str = wxString::Format( _("selected: %.4f"), regressionXYselected.beta); morans_sel_text = new GdaShapeText(str, *GdaConst::small_font, @@ -600,7 +670,7 @@ void LisaScatterPlotCanvas::PopulateCanvas() morans_sel_text->setPen(wxPen(*wxRED)); morans_sel_text->applyScaleTrans(sub_scale); - wxString str1 = wxString::Format("unselected: %.4f", + wxString str1 = wxString::Format(_("unselected: %.4f"), regressionXYexcluded.beta); morans_unsel_text = new GdaShapeText(str1, *GdaConst::small_font, @@ -635,8 +705,8 @@ void LisaScatterPlotCanvas::UpdateRegSelectedLine() *pens.GetRegSelPen()); GdaScaleTrans sub_scale; sub_scale = last_scale_trans; - sub_scale.right_margin= sub_scale.screen_width - sub_scale.trans_x + 50; - sub_scale.left_margin = 40; + sub_scale.right_margin= sub_scale.screen_width - sub_scale.trans_x + 65; + sub_scale.left_margin = 45; sub_scale.calcAffineParams(); reg_line_selected->applyScaleTrans(sub_scale); @@ -664,7 +734,7 @@ void LisaScatterPlotCanvas::UpdateRegExcludedLine() GdaScaleTrans ex_scale; ex_scale = last_scale_trans; ex_scale.left_margin= ex_scale.trans_x + ex_scale.data_x_max * ex_scale.scale_x + 45; - ex_scale.right_margin = 5; + ex_scale.right_margin = 35; ex_scale.calcAffineParams(); @@ -706,6 +776,10 @@ void LisaScatterPlotCanvas::RegimeMoran(std::vector& undefs, for (int i=0; iisBivariate) { @@ -735,76 +809,7 @@ void LisaScatterPlotCanvas::UpdateSelection(bool shiftdown, bool pointsel) int n_hl = highlight_state->GetTotalHighlighted(); if (n_hl > 0 && is_show_regimes_regression) { - /* - const std::vector& hl = highlight_state->GetHighlight(); - - int t = project->GetTimeState()->GetCurrTime(); - int num_obs = lisa_coord->num_obs; - - std::vector undefs(num_obs, false); - for (int i=0; iundef_tms[t][i] || !hl[i]; - foreground_shps.pop_front(); - } - std::vector X; - std::vector Y; - RegimeMoran(undefs, regressionXYselected, X, Y); - - GdaScaleTrans sub_scale; - sub_scale = last_scale_trans; - sub_scale.right_margin= sub_scale.screen_width - sub_scale.trans_x + 50; - sub_scale.left_margin = 40; - sub_scale.calcAffineParams(); - - for (int i=0; isetPen(wxPen(wxColour(245,140,140))); - pt->setBrush(*wxTRANSPARENT_BRUSH); - pt->applyScaleTrans(sub_scale); - - foreground_shps.insert(foreground_shps.begin(), pt); - } - - undefs.clear(); - undefs.resize(num_obs, false); - for (int i=0; iundef_tms[t][i] || hl[i]; - } - std::vector X_ex; - std::vector Y_ex; - RegimeMoran(undefs, regressionXYexcluded, X_ex, Y_ex); - - GdaScaleTrans ex_scale; - ex_scale = last_scale_trans; - ex_scale.left_margin= ex_scale.trans_x + ex_scale.data_x_max * ex_scale.scale_x + 45; - ex_scale.right_margin = 5; - ex_scale.calcAffineParams(); - - for (int i=0; isetPen(wxPen(wxColour(100,100,100))); - pt->setBrush(*wxTRANSPARENT_BRUSH); - pt->applyScaleTrans(ex_scale); - foreground_shps.insert(foreground_shps.begin(),pt); - } - - - UpdateRegSelectedLine(); - UpdateRegExcludedLine(); - - if (morans_sel_text) { - wxString str = wxString::Format("selected: %.4f", regressionXYselected.beta); - morans_sel_text->setText(str); - } - if (morans_unsel_text) { - wxString str1 = wxString::Format("unselected: %.4f", regressionXYexcluded.beta); - morans_unsel_text->setText(str1); - } - //Refresh(); - */ + isResize = true; PopulateCanvas(); } TemplateCanvas::UpdateSelection(shiftdown, pointsel); @@ -817,16 +822,32 @@ void LisaScatterPlotCanvas::update(HLStateInt* o) PopulateCanvas(); // Call TemplateCanvas::update to redraw objects as needed. - TemplateCanvas::update(o); - - Refresh(); + TemplateCanvas::update(o); } void LisaScatterPlotCanvas::PopCanvPreResizeShpsHook() { // if has highlighted, then the text will be added after RegimeMoran() wxString s("Moran's I: "); s << regressionXY.beta; - morans_i_text = new GdaShapeText(s, *GdaConst::small_font, + + int t = project->GetTimeState()->GetCurrTime(); + if (t >= lisa_coord->Gal_vecs.size()) { + return; + } + GalWeight* w = lisa_coord->Gal_vecs[t]; + GalElement* gal = w->gal; + bool has_island = false; + for (int i=0; i raw_data1(num_obs); int xt = var_info_orig[0].time-var_info_orig[0].time_min; + if (is_diff) { + // in case its differential moran, there is only one grouped variable + xt = 0; + } for (int i=0; idata1_vecs[xt][i]; } @@ -872,6 +897,7 @@ void LisaScatterPlotCanvas::ShowRandomizationDialog(int permutation) lisa_coord->Gal_vecs[cts], lisa_coord->undef_tms[cts], highlight_state->GetHighlight(), + is_show_regimes_regression, permutation, reuse_last_seed, last_used_seed, this); @@ -889,6 +915,7 @@ void LisaScatterPlotCanvas::ShowRandomizationDialog(int permutation) rand_dlg = new RandomizationDlg(raw_data1, lisa_coord->Gal_vecs[cts], lisa_coord->undef_tms[cts], highlight_state->GetHighlight(), + is_show_regimes_regression, permutation, reuse_last_seed, last_used_seed, this); @@ -901,7 +928,7 @@ void LisaScatterPlotCanvas::ShowRandomizationDialog(int permutation) void LisaScatterPlotCanvas::SaveMoranI() { - wxString title = "Save Results: Moran's I"; + wxString title = _("Save Results: Moran's I"); std::vector std_data(num_obs); std::vector lag(num_obs); std::vector diff(num_obs); @@ -931,20 +958,20 @@ void LisaScatterPlotCanvas::SaveMoranI() } data[0].d_val = &std_data; - data[0].label = "Standardized Data"; + data[0].label = _("Standardized Data"); data[0].field_default = "MORAN_STD"; data[0].type = GdaConst::double_type; data[0].undefined = &XYZ_undef; data[1].d_val = &lag; - data[1].label = "Spatial Lag"; + data[1].label = _("Spatial Lag"); data[1].field_default = "MORAN_LAG"; data[1].type = GdaConst::double_type; data[1].undefined = &XYZ_undef; if (is_diff) { data[2].d_val = &diff; - data[2].label = "Diff Values"; + data[2].label = _("Diff Values"); data[2].field_default = "DIFF_VAL"; data[2].type = GdaConst::double_type; data[2].undefined = &XYZ_undef; @@ -968,7 +995,7 @@ LisaScatterPlotFrame::LisaScatterPlotFrame(wxFrame *parent, Project* project, : ScatterNewPlotFrame(parent, project, pos, size, style), lisa_coord(lisa_coordinator) { - LOG_MSG("Entering LisaScatterPlotFrame::LisaScatterPlotFrame"); + wxLogMessage("Entering LisaScatterPlotFrame::LisaScatterPlotFrame"); int width, height; GetClientSize(&width, &height); @@ -979,17 +1006,17 @@ lisa_coord(lisa_coordinator) template_canvas->SetScrollRate(1,1); DisplayStatusBar(true); SetTitle(template_canvas->GetCanvasTitle()); - lisa_coord->registerObserver(this); + //lisa_coord->registerObserver(this); Show(true); - LOG_MSG("Exiting LisaScatterPlotFrame::LisaScatterPlotFrame"); + wxLogMessage("Exiting LisaScatterPlotFrame::LisaScatterPlotFrame"); } LisaScatterPlotFrame::~LisaScatterPlotFrame() { LOG_MSG("In LisaScatterPlotFrame::~LisaScatterPlotFrame"); if (lisa_coord) { - lisa_coord->removeObserver(this); + //lisa_coord->removeObserver(this); lisa_coord = 0; } } @@ -1009,17 +1036,19 @@ void LisaScatterPlotFrame::OnUseSpecifiedSeed(wxCommandEvent& event) void LisaScatterPlotFrame::OnSpecifySeedDlg(wxCommandEvent& event) { uint64_t last_seed = lisa_coord->GetLastUsedSeed(); - wxString m; - m << "The last seed used by the pseudo random\nnumber "; - m << "generator was " << last_seed << ".\n"; - m << "Enter a seed value to use between\n0 and "; - m << std::numeric_limits::max() << "."; + wxString m = _("The last seed used by the pseudo random\nnumber generator was "); + //wxLongLongFmtSpec + m << last_seed; + m << _(".\nEnter a seed value to use between\n0 and "); + m << std::numeric_limits::max(); + m << "."; + long long unsigned int val; wxString dlg_val; wxString cur_val; cur_val << last_seed; - wxTextEntryDialog dlg(NULL, m, "Enter a seed value", cur_val); + wxTextEntryDialog dlg(NULL, m, _("Enter a seed value"), cur_val); if (dlg.ShowModal() != wxID_OK) return; dlg_val = dlg.GetValue(); dlg_val.Trim(true); @@ -1031,9 +1060,9 @@ void LisaScatterPlotFrame::OnSpecifySeedDlg(wxCommandEvent& event) uint64_t new_seed_val = val; lisa_coord->SetLastUsedSeed(new_seed_val); } else { - wxString m; - m << "\"" << dlg_val << "\" is not a valid seed. Seed unchanged."; - wxMessageDialog dlg(NULL, m, "Error", wxOK | wxICON_ERROR); + wxString m = _("\"%s\" is not a valid seed. Seed unchanged."); + m = wxString::Format(m, dlg_val); + wxMessageDialog dlg(NULL, m, _("Error"), wxOK | wxICON_ERROR); dlg.ShowModal(); } } @@ -1055,7 +1084,7 @@ void LisaScatterPlotFrame::MapMenus() ((ScatterNewPlotCanvas*) template_canvas)-> AddTimeVariantOptionsToMenu(optMenu); ((ScatterNewPlotCanvas*) template_canvas)->SetCheckMarks(optMenu); - GeneralWxUtils::ReplaceMenu(mb, "Options", optMenu); + GeneralWxUtils::ReplaceMenu(mb, _("Options"), optMenu); UpdateOptionMenuItems(); } @@ -1063,7 +1092,7 @@ void LisaScatterPlotFrame::UpdateOptionMenuItems() { TemplateFrame::UpdateOptionMenuItems(); // set common items first wxMenuBar* mb = GdaFrame::GetGdaFrame()->GetMenuBar(); - int menu = mb->FindMenu("Options"); + int menu = mb->FindMenu(_("Options")); if (menu == wxNOT_FOUND) { LOG_MSG("LisaScatterPlotFrame::UpdateOptionMenuItems: " "Options menu not found"); @@ -1110,16 +1139,20 @@ void LisaScatterPlotFrame::OnRan999Per(wxCommandEvent& event) void LisaScatterPlotFrame::OnRanOtherPer(wxCommandEvent& event) { + wxLogMessage("LisaScatterPlotFrame::OnRanOtherPer"); PermutationCounterDlg dlg(this); if (dlg.ShowModal() == wxID_OK) { long num; - dlg.m_number->GetValue().ToLong(&num); + wxString input = dlg.m_number->GetValue(); + wxLogMessage(input); + input.ToLong(&num); RanXPer(num); } } void LisaScatterPlotFrame::OnSaveMoranI(wxCommandEvent& event) { + wxLogMessage("LisaScatterPlotFrame::OnSaveMoranI"); LisaScatterPlotCanvas* lc = (LisaScatterPlotCanvas*) template_canvas; lc->SaveMoranI(); } @@ -1140,10 +1173,95 @@ void LisaScatterPlotFrame::update(LisaCoordinator* o) void LisaScatterPlotFrame::closeObserver(LisaCoordinator* o) { if (lisa_coord) { - lisa_coord->removeObserver(this); + //lisa_coord->removeObserver(this); lisa_coord = 0; } Close(true); } +void LisaScatterPlotFrame::ExportImage(TemplateCanvas* canvas, const wxString& type) +{ + wxLogMessage("Entering LisaScatterPlotFrame::ExportImage"); + + wxString default_fname(project->GetProjectTitle() + type); + wxString filter = "BMP|*.bmp|PNG|*.png"; + int filter_index = 1; + wxFileDialog dialog(canvas, _("Save Image to File"), wxEmptyString, + default_fname, filter, + wxFD_SAVE | wxFD_OVERWRITE_PROMPT); + dialog.SetFilterIndex(filter_index); + + if (dialog.ShowModal() != wxID_OK) return; + + wxSize sz = canvas->GetDrawingSize(); + int new_bmp_w = sz.x + canvas->GetMarginLeft() + canvas->GetMarginRight(); + int new_bmp_h = sz.y + canvas->GetMarginTop() + canvas->GetMarginBottom(); + + int offset_x = 0; + + if (template_legend) { + int legend_width = template_legend->GetDrawingWidth(); + new_bmp_w += legend_width; + offset_x += legend_width; + } + + wxFileName fname = wxFileName(dialog.GetPath()); + wxString str_fname = fname.GetPathWithSep() + fname.GetName(); + + switch (dialog.GetFilterIndex()) { + case 0: + { + wxLogMessage("BMP selected"); + wxBitmap bitmap(new_bmp_w, new_bmp_h); + wxMemoryDC dc; + dc.SelectObject(bitmap); + dc.SetBackground(*wxWHITE_BRUSH); + dc.Clear(); + dc.DrawBitmap(*template_canvas->GetLayer2(), offset_x, 0); + if (template_legend) { + template_legend->RenderToDC(dc, 1.0); + } + dc.SelectObject( wxNullBitmap ); + + wxImage image = bitmap.ConvertToImage(); + if ( !image.SaveFile( str_fname + ".bmp", wxBITMAP_TYPE_BMP )) { + wxMessageBox(_("GeoDa was unable to save the file.")); + } + image.Destroy(); + } + break; + + case 1: + { + wxLogMessage("PNG selected"); + wxBitmap bitmap(new_bmp_w, new_bmp_h); + wxMemoryDC dc; + dc.SelectObject(bitmap); + dc.SetBackground(*wxWHITE_BRUSH); + dc.Clear(); + dc.DrawBitmap(*template_canvas->GetLayer2(), offset_x, 0); + if (template_legend) { + template_legend->RenderToDC(dc, 1.0); + } + dc.SelectObject( wxNullBitmap ); + + wxImage image = bitmap.ConvertToImage(); + if ( !image.SaveFile( str_fname + ".png", wxBITMAP_TYPE_PNG )) { + wxMessageBox(_("GeoDa was unable to save the file.")); + } + + image.Destroy(); + } + break; + + default: + { + LOG_MSG("Error: A non-recognized type selected."); + } + break; + } + return; + + LOG_MSG("Exiting LisaScatterPlotFrame::ExportImage"); +} diff --git a/Explore/LisaScatterPlotView.h b/Explore/LisaScatterPlotView.h index 54887ae8b..fa676cd0d 100644 --- a/Explore/LisaScatterPlotView.h +++ b/Explore/LisaScatterPlotView.h @@ -40,6 +40,7 @@ class LisaScatterPlotCanvas : public ScatterNewPlotCanvas virtual void DisplayRightClickMenu(const wxPoint& pos); virtual void AddTimeVariantOptionsToMenu(wxMenu* menu); virtual wxString GetCanvasTitle(); + virtual wxString GetVariableNames(); virtual wxString GetNameWithTime(int var); virtual void SetCheckMarks(wxMenu* menu); virtual void TimeChange(); @@ -82,6 +83,7 @@ class LisaScatterPlotCanvas : public ScatterNewPlotCanvas GdaShapeText* morans_sel_text; GdaShapeText* morans_unsel_text; + std::map pre_foreground_shps; DECLARE_EVENT_TABLE() }; @@ -96,8 +98,10 @@ class LisaScatterPlotFrame : public ScatterNewPlotFrame, const wxSize& size = wxSize(600, 360), const long style = wxDEFAULT_FRAME_STYLE); virtual ~LisaScatterPlotFrame(); - + void OnActivate(wxActivateEvent& event); + + virtual void ExportImage(TemplateCanvas* canvas, const wxString& type); virtual void MapMenus(); virtual void UpdateOptionMenuItems(); virtual void UpdateContextMenuItems(wxMenu* menu); diff --git a/Explore/LocalGearyCoordinator.cpp b/Explore/LocalGearyCoordinator.cpp index f76ee65fa..c15a9cfd8 100644 --- a/Explore/LocalGearyCoordinator.cpp +++ b/Explore/LocalGearyCoordinator.cpp @@ -19,6 +19,7 @@ #include #include +#include #include #include #include "../DataViewer/TableInterface.h" @@ -33,18 +34,16 @@ #include "LocalGearyCoordinatorObserver.h" #include "LocalGearyCoordinator.h" -LocalGearyWorkerThread::LocalGearyWorkerThread(const GalElement* W_, - const std::vector& undefs_, - int obs_start_s, int obs_end_s, - uint64_t seed_start_s, - LocalGearyCoordinator* local_geary_coord_s, - wxMutex* worker_list_mutex_s, - wxCondition* worker_list_empty_cond_s, - std::list *worker_list_s, - int thread_id_s) +using namespace std; + +LocalGearyWorkerThread::LocalGearyWorkerThread(int obs_start_s, int obs_end_s, + uint64_t seed_start_s, + LocalGearyCoordinator* local_geary_coord_s, + wxMutex* worker_list_mutex_s, + wxCondition* worker_list_empty_cond_s, + std::list *worker_list_s, + int thread_id_s) : wxThread(), -W(W_), -undefs(undefs_), obs_start(obs_start_s), obs_end(obs_end_s), seed_start(seed_start_s), local_geary_coord(local_geary_coord_s), worker_list_mutex(worker_list_mutex_s), @@ -60,59 +59,26 @@ LocalGearyWorkerThread::~LocalGearyWorkerThread() wxThread::ExitCode LocalGearyWorkerThread::Entry() { - LOG_MSG(wxString::Format("LocalGearyWorkerThread %d started", thread_id)); - - // call work for assigned range of observations - local_geary_coord->CalcPseudoP_range(W, undefs, obs_start, obs_end, seed_start); - - wxMutexLocker lock(*worker_list_mutex); + LOG_MSG(wxString::Format("LocalGearyWorkerThread %d started", thread_id)); + + // call work for assigned range of observations + local_geary_coord->CalcPseudoP_range(obs_start, obs_end, seed_start); + + wxMutexLocker lock(*worker_list_mutex); + + // remove ourself from the list + worker_list->remove(this); - // remove ourself from the list - worker_list->remove(this); - // if empty, signal on empty condition since only main thread - // should be waiting on this condition - if (worker_list->empty()) { - worker_list_empty_cond->Signal(); - } - - return NULL; + // should be waiting on this condition + if (worker_list->empty()) { + worker_list_empty_cond->Signal(); + } + + return NULL; } -/** - Since the user has the ability to synchronise either variable over time, - we must be able to reapply weights and recalculate local_geary values as needed. - - 1. We will have original data as complete space-time data for both variables - - 2. From there we will work from info in var_info for both variables. Must - determine number of time_steps for canvas. - - 3. Adjust data1(2)_vecs sizes and initialize from data. - - 3.5. Resize localGeary, siglocalGeary, sigCat, and cluster arrays - - 4. If rates, then calculate rates for working_data1 - - 5. Standardize working_data1 (and 2 if bivariate) - - 6. Compute LocalGeary for all time-stesp and save in localGeary sp/time array - - 7. Calc Pseudo P for all time periods. Results saved in siglocalGeary, - sigCat and cluster arrays - - 8. Notify clients that values have been updated. - - */ - -LocalGearyCoordinator:: -LocalGearyCoordinator(boost::uuids::uuid weights_id, - Project* project, - const std::vector& var_info_s, - const std::vector& col_ids, - LocalGearyType local_geary_type_s, - bool calc_significances_s, - bool row_standardize_s) +LocalGearyCoordinator::LocalGearyCoordinator(boost::uuids::uuid weights_id, Project* project, const vector& var_info_s, const vector& col_ids, LocalGearyType local_geary_type_s, bool calc_significances_s, bool row_standardize_s) : w_man_state(project->GetWManState()), w_man_int(project->GetWManInt()), w_id(weights_id), @@ -124,46 +90,36 @@ isBivariate(local_geary_type_s == bivariate), var_info(var_info_s), data(var_info_s.size()), undef_data(var_info_s.size()), -last_seed_used(0), reuse_last_seed(false), +last_seed_used(123456789), +reuse_last_seed(true), row_standardize(row_standardize_s) { + wxLogMessage("In LocalGearyCoordinator::LocalGearyCoordinator()"); reuse_last_seed = GdaConst::use_gda_user_seed; if ( GdaConst::use_gda_user_seed) { last_seed_used = GdaConst::gda_user_seed; } - TableInterface* table_int = project->GetTableInt(); for (int i=0; iGetColData(col_ids[i], data[i]); table_int->GetColUndefined(col_ids[i], undef_data[i]); var_info[i].is_moran = true; } - num_vars = var_info.size(); - weight_name = w_man_int->GetLongDispName(w_id); - weights = w_man_int->GetGal(w_id); - SetSignificanceFilter(1); - InitFromVarInfo(); w_man_state->registerObserver(this); } -LocalGearyCoordinator:: -LocalGearyCoordinator(wxString weights_path, - int n, - std::vector >& vars, - int permutations_s, - bool calc_significances_s, - bool row_standardize_s) +LocalGearyCoordinator::LocalGearyCoordinator(wxString weights_path, int n, vector >& vars, int permutations_s, bool calc_significances_s, bool row_standardize_s) { + wxLogMessage("In LocalGearyCoordinator::LocalGearyCoordinator()2"); reuse_last_seed = GdaConst::use_gda_user_seed; if ( GdaConst::use_gda_user_seed) { last_seed_used = GdaConst::gda_user_seed; } - isBivariate = false; num_obs = n; num_time_vals = 1; @@ -172,8 +128,6 @@ LocalGearyCoordinator(wxString weights_path, row_standardize = row_standardize_s; last_seed_used = 0; reuse_last_seed = false; - - // std::vector var_info; num_vars = vars.size(); if (num_vars == 1) { @@ -197,14 +151,12 @@ LocalGearyCoordinator(wxString weights_path, var_info[i].time_max = 0; var_info[i].time_min = 0; } - for (int i=0; i < num_vars; i++) { for (int j=0; jnum_obs = num_obs; weights->wflnm = weights_path; @@ -229,6 +180,7 @@ LocalGearyCoordinator(wxString weights_path, LocalGearyCoordinator::~LocalGearyCoordinator() { + wxLogMessage("In LocalGearyCoordinator::~LocalGearyCoordinator()"); if (w_man_state) { w_man_state->removeObserver(this); } @@ -237,6 +189,7 @@ LocalGearyCoordinator::~LocalGearyCoordinator() void LocalGearyCoordinator::DeallocateVectors() { + wxLogMessage("In LocalGearyCoordinator::DeallocateVectors()"); for (int i=0; i undef_res(num_obs, false); + vector undef_res(num_obs, false); double* smoothed_results = new double[num_obs]; double* E = new double[num_obs]; // E corresponds to var_info[0] double* P = new double[num_obs]; // P corresponds to var_info[1] @@ -487,6 +442,7 @@ void LocalGearyCoordinator::InitFromVarInfo() void LocalGearyCoordinator::GetRawData(int time, double* data1, double* data2) { + wxLogMessage("In LocalGearyCoordinator::GetRawData()"); if (local_geary_type == differential) { int t=0; for (int i=0; i undef_res(num_obs, false); + vector undef_res(num_obs, false); double* smoothed_results = new double[num_obs]; double* E = new double[num_obs]; // E corresponds to var_info[0] double* P = new double[num_obs]; // P corresponds to var_info[1] @@ -517,9 +473,7 @@ void LocalGearyCoordinator::GetRawData(int time, double* data1, double* data2) for (int i=0; igal; if (local_geary_type == multivariate) { // get undef_tms across multi-variables for (int v=0; v undefs; + vector undefs; bool has_undef = false; for (int i=0; igal; - Gal_vecs.push_back(gw); - Gal_vecs_orig.push_back(weights); + Gal_vecs[t] = gw; + Gal_vecs_orig[t] = weights; // local geary - lags = lags_vecs[t]; - localGeary = local_geary_vecs[t]; - cluster = cluster_vecs[t]; + double* lags = lags_vecs[t]; has_isolates[t] = false; + int* cluster = cluster_vecs[t]; + double* localGeary = local_geary_vecs[t]; - std::vector local_t; + vector local_t; for (int v=0; v 0) { cluster[i] = 0; // don't assign cluster in multi-var settings - //if (data1[i] > 0 && lags[i] > 0) cluster[i] = 1; - //else if (data1[i] < 0 && lags[i] > 0) cluster[i] = 3; - //else if (data1[i] < 0 && lags[i] < 0) cluster[i] = 2; - //else cluster[i] = 4; //data1[i] > 0 && lags[i] < 0 } else { has_isolates[t] = true; cluster[i] = 2; // neighborless } } } + wxLogMessage("End LocalGearyCoordinator::CalcMultiLocalGeary()"); } /** assumes StandardizeData already called on data1 and data2 */ void LocalGearyCoordinator::CalcLocalGeary() { + wxLogMessage("In LocalGearyCoordinator::CalcLocalGeary()"); for (int t=0; t undefs; + vector undefs; bool has_undef = false; for (int i=0; igal; - Gal_vecs.push_back(gw); - Gal_vecs_orig.push_back(weights); + Gal_vecs[t] = gw; + Gal_vecs_orig[t] = weights; for (int i=0; i& undefs = undef_tms[t]; - - if (local_geary_type == multivariate) { - for (int v=0; vgal, undefs, 0, num_obs-1, last_seed_used); - } else { - CalcPseudoP_threaded(Gal_vecs[t]->gal, undefs); - } - } - + wxLogMessage("In LocalGearyCoordinator::CalcPseudoP()"); + if (!calc_significances) + return; - { - wxString m; - m << "LocalGeary on " << num_obs << " obs with " << permutations; - m << " perms over " << num_time_vals << " time periods took "; - m << sw.Time() << " ms. Last seed used: " << last_seed_used; - } - LOG_MSG("Exiting LocalGearyCoordinator::CalcPseudoP"); + CalcPseudoP_threaded(); + wxLogMessage("End LocalGearyCoordinator::CalcPseudoP()"); } -void LocalGearyCoordinator::CalcPseudoP_threaded(const GalElement* W, - const std::vector& undefs) +void LocalGearyCoordinator::CalcPseudoP_threaded() { - int nCPUs = wxThread::GetCPUCount(); + wxLogMessage("In LocalGearyCoordinator::CalcPseudoP_threaded()"); + int nCPUs = GdaConst::gda_cpu_cores; + if (!GdaConst::gda_set_cpu_cores) + nCPUs = wxThread::GetCPUCount(); // mutext protects access to the worker_list wxMutex worker_list_mutex; @@ -837,27 +755,22 @@ void LocalGearyCoordinator::CalcPseudoP_threaded(const GalElement* W, // List of all the threads currently alive. As soon as the thread // terminates, it removes itself from the list. - std::list worker_list; + list worker_list; // divide up work according to number of observations // and number of CPUs int work_chunk = num_obs / nCPUs; - - if (work_chunk == 0) { - work_chunk = 1; - } + if (work_chunk == 0) work_chunk = 1; int obs_start = 0; int obs_end = obs_start + work_chunk; - - bool is_thread_error = false; + + bool is_thread_error = false; int quotient = num_obs / nCPUs; int remainder = num_obs % nCPUs; int tot_threads = (quotient > 0) ? nCPUs : remainder; - - boost::thread_group threadPool; - if (!reuse_last_seed) last_seed_used = time(0); + for (int i=0; i" << b; - msg << ", seed: " << seed_start << "->" << seed_end; - - /* - LocalGearyWorkerThread* thread = - new LocalGearyWorkerThread(W, undefs, a, b, seed_start, this, - &worker_list_mutex, - &worker_list_empty_cond, - &worker_list, thread_id); - if ( thread->Create() != wxTHREAD_NO_ERROR ) { - delete thread; - is_thread_error = true; - } else { - worker_list.push_front(thread); - } - */ - boost::thread* worker = new boost::thread(boost::bind(&LocalGearyCoordinator::CalcPseudoP_range,this, W, undefs, a, b, seed_start)); - threadPool.add_thread(worker); - } - threadPool.join_all(); - /* - if (is_thread_error) { - // fall back to single thread calculation mode - CalcPseudoP_range(W, undefs, 0, num_obs-1, last_seed_used); - } else { - std::list::iterator it; - for (it = worker_list.begin(); it != worker_list.end(); it++) { - (*it)->Run(); - } - - while (!worker_list.empty()) { - // wait until thread_list might be empty - worker_list_empty_cond.Wait(); - // We have been woken up. If this was not a false - // alarm (sprious signal), the loop will exit. - } + int thread_id = i+1; + LocalGearyWorkerThread* thread = + new LocalGearyWorkerThread(a, b, seed_start, this, + &worker_list_mutex, + &worker_list_empty_cond, + &worker_list, thread_id); + if ( thread->Create() != wxTHREAD_NO_ERROR ) { + delete thread; + is_thread_error = true; + } else { + worker_list.push_front(thread); + } } - */ + if (is_thread_error) { + // fall back to single thread calculation mode + CalcPseudoP_range(0, num_obs-1, last_seed_used); + } else { + std::list::iterator it; + for (it = worker_list.begin(); it != worker_list.end(); it++) { + (*it)->Run(); + } + + while (!worker_list.empty()) { + // wait until thread_list might be empty + worker_list_empty_cond.Wait(); + // We have been woken up. If this was not a false + // alarm (sprious signal), the loop will exit. + } + } + wxLogMessage("End LocalGearyCoordinator::CalcPseudoP_threaded()"); } -void LocalGearyCoordinator::CalcPseudoP_range(const GalElement* W, - const std::vector& undefs, - int obs_start, int obs_end, - uint64_t seed_start) +void LocalGearyCoordinator::CalcPseudoP_range(int obs_start, int obs_end, uint64_t seed_start) { GeoDaSet workPermutation(num_obs); - //Randik rng; int max_rand = num_obs-1; + for (int cnt=obs_start; cnt<=obs_end; cnt++) { + std::vector countLarger(num_time_vals, 0); + std::vector > gci(num_time_vals); + std::vector gci_sum(num_time_vals, 0); - if (undefs[cnt]) - continue; - - uint64_t countLarger = 0; - const int numNeighbors = W[cnt].Size(); - - double *gci = new double[permutations]; - double gci_sum = 0.0; + for (int t=0; tgal; + if (w[cnt].Size() > numNeighbors) { + numNeighbors = w[cnt].Size(); + } + } + if (numNeighbors == 0) { + continue; + } + for (int perm=0; perm0) { workPermutation.Push(newRandom); rand++; } } - double permutedLag=0; - // use permutation to compute the lag - // compute the lag for binary weights - if (local_geary_type == multivariate) { - double* m_wwx = new double[num_vars]; - double* m_wwx2 = new double[num_vars]; - for (int v=0; v permNeighbors(numNeighbors); + for (int cp=0; cp& undefs = undef_tms[t]; + double* _data1 = NULL; + double* _data1_square = NULL; + double* _data2 = NULL; + vector current_data(num_vars); + vector current_data_square(num_vars); - for (int cp=0; cp 2 && _cluster[cnt] < 5) // ignore neighborless & undefined + _cluster[cnt] = 3; } } else { - // positive && high-high if (cluster[cnt] == 1) cluster[cnt] = 1; - // positive && low-low if (cluster[cnt] == 2) cluster[cnt] = 2; - // positive && but in outlier qudrant: other pos - if (cluster[cnt] > 2 && cluster[cnt] < 5) // ignore neighborless & undefined - cluster[cnt] = 3; - } - } else { - // negative lisasign[cnt] = -1 - for (int perm=0; perm localGeary[cnt]) { - countLarger++; + // negative lisasign[cnt] = -1 + for (int perm=0; perm _localGeary[cnt]) { + countLarger[t] += 1; + } + } + if (local_geary_type == multivariate) { + if (_cluster[cnt] < 2) // ignore neighborless & undefined + _cluster[cnt] = 0; // for multivar, only show significant positive (similar) + } else { + // negative + if (_cluster[cnt] < 5) // ignore neighborless & undefined + _cluster[cnt] = 4; } } - if (local_geary_type == multivariate) { - if (cluster[cnt] < 2) // ignore neighborless & undefined - cluster[cnt] = 0; // for multivar, only show significant positive (similar) - } else { - // negative - if (cluster[cnt] < 5) // ignore neighborless & undefined - cluster[cnt] = 4; + int kp = local_geary_type == multivariate ? num_vars : 1; + _siglocalGeary[cnt] = (countLarger[t]+1.0)/(permutations+1); + + // 'significance' of local Moran + if (_siglocalGeary[cnt] <= 0.0001) _sigCat[cnt] = 4; + else if (_siglocalGeary[cnt] <= 0.001) _sigCat[cnt] = 3; + else if (_siglocalGeary[cnt] <= 0.01) _sigCat[cnt] = 2; + else if (_siglocalGeary[cnt] <= 0.05) _sigCat[cnt]= 1; + else _sigCat[cnt]= 0; + + // observations with no neighbors get marked as isolates + // NOTE: undefined should be marked as well, however, since undefined_cat has covered undefined category, we don't need to handle here + if (numNeighbors == 0) { + _sigCat[cnt] = 5; } + } - - int kp = local_geary_type == multivariate ? num_vars : 1; - siglocalGeary[cnt] = (countLarger+1.0)/(permutations+1); - // 'significance' of local Moran - if (siglocalGeary[cnt] <= 0.0001 / kp) sigCat[cnt] = 4; - else if (siglocalGeary[cnt] <= 0.001 / kp) sigCat[cnt] = 3; - else if (siglocalGeary[cnt] <= 0.01 / kp) sigCat[cnt] = 2; - else if (siglocalGeary[cnt] <= 0.05 / kp) sigCat[cnt]= 1; - else sigCat[cnt]= 0; - - // observations with no neighbors get marked as isolates - // NOTE: undefined should be marked as well, however, since undefined_cat has covered undefined category, we don't need to handle here - if (numNeighbors == 0) { - sigCat[cnt] = 5; - } - } + } } void LocalGearyCoordinator::SetSignificanceFilter(int filter_id) { + wxLogMessage("In LocalGearyCoordinator::SetSignificanceFilter()"); + if (filter_id == -1) { + // user input cutoff + significance_filter = filter_id; + return; + } // 0: >0.05 1: 0.05, 2: 0.01, 3: 0.001, 4: 0.0001 if (filter_id < 1 || filter_id > 4) return; significance_filter = filter_id; - int kp = local_geary_type == multivariate ? num_vars : 1; + //int kp = local_geary_type == multivariate ? num_vars : 1; - if (filter_id == 1) significance_cutoff = 0.05 / kp; - if (filter_id == 2) significance_cutoff = 0.01 / kp; - if (filter_id == 3) significance_cutoff = 0.001 / kp; - if (filter_id == 4) significance_cutoff = 0.0001 / kp; + if (filter_id == 1) significance_cutoff = 0.05; + if (filter_id == 2) significance_cutoff = 0.01; + if (filter_id == 3) significance_cutoff = 0.001; + if (filter_id == 4) significance_cutoff = 0.0001; } void LocalGearyCoordinator::update(WeightsManState* o) { + wxLogMessage("In LocalGearyCoordinator::update(WeightsManState)"); if (w_man_int) { weight_name = w_man_int->GetLongDispName(w_id); } @@ -1083,14 +1039,16 @@ void LocalGearyCoordinator::update(WeightsManState* o) int LocalGearyCoordinator::numMustCloseToRemove(boost::uuids::uuid id) const { + wxLogMessage("In LocalGearyCoordinator::numMustCloseToRemove()"); return id == w_id ? observers.size() : 0; } void LocalGearyCoordinator::closeObserver(boost::uuids::uuid id) { + wxLogMessage("In LocalGearyCoordinator::closeObserver()"); if (numMustCloseToRemove(id) == 0) return; - std::list obs_cpy = observers; - for (std::list::iterator i=obs_cpy.begin(); + list obs_cpy = observers; + for (list::iterator i=obs_cpy.begin(); i != obs_cpy.end(); ++i) { (*i)->closeObserver(this); } @@ -1098,23 +1056,24 @@ void LocalGearyCoordinator::closeObserver(boost::uuids::uuid id) void LocalGearyCoordinator::registerObserver(LocalGearyCoordinatorObserver* o) { + wxLogMessage("In LocalGearyCoordinator::registerObserver()"); + observers.push_front(o); } void LocalGearyCoordinator::removeObserver(LocalGearyCoordinatorObserver* o) { - LOG_MSG("Entering LocalGearyCoordinator::removeObserver"); + wxLogMessage("In LocalGearyCoordinator::removeObserver()"); observers.remove(o); - LOG(observers.size()); if (observers.size() == 0) { delete this; } - LOG_MSG("Exiting LocalGearyCoordinator::removeObserver"); } void LocalGearyCoordinator::notifyObservers() { - for (std::list::iterator it=observers.begin(); + wxLogMessage("In LocalGearyCoordinator::notifyObservers()"); + for (list::iterator it=observers.begin(); it != observers.end(); ++it) { (*it)->update(this); } diff --git a/Explore/LocalGearyCoordinator.h b/Explore/LocalGearyCoordinator.h index 94eee7d47..623f3fd41 100644 --- a/Explore/LocalGearyCoordinator.h +++ b/Explore/LocalGearyCoordinator.h @@ -31,6 +31,7 @@ #include "../ShapeOperations/WeightsManStateObserver.h" #include "../ShapeOperations/OGRDataAdapter.h" +using namespace std; class LocalGearyCoordinatorObserver; class LocalGearyCoordinator; @@ -42,46 +43,47 @@ typedef boost::multi_array b_array_type; class LocalGearyWorkerThread : public wxThread { public: - LocalGearyWorkerThread(const GalElement* W, - const std::vector& undefs, - int obs_start, int obs_end, uint64_t seed_start, - LocalGearyCoordinator* local_geary_coord, - wxMutex* worker_list_mutex, - wxCondition* worker_list_empty_cond, - std::list *worker_list, - int thread_id); - virtual ~LocalGearyWorkerThread(); - virtual void* Entry(); // thread execution starts here - - const GalElement* W; - const std::vector& undefs; - int obs_start; - int obs_end; - uint64_t seed_start; - int thread_id; - - LocalGearyCoordinator* local_geary_coord; - wxMutex* worker_list_mutex; - wxCondition* worker_list_empty_cond; - std::list *worker_list; + LocalGearyWorkerThread(int obs_start, int obs_end, uint64_t seed_start, + LocalGearyCoordinator* local_geary_coord, + wxMutex* worker_list_mutex, + wxCondition* worker_list_empty_cond, + std::list *worker_list, + int thread_id); + virtual ~LocalGearyWorkerThread(); + virtual void* Entry(); // thread execution starts here + + int obs_start; + int obs_end; + uint64_t seed_start; + int thread_id; + + LocalGearyCoordinator* local_geary_coord; + wxMutex* worker_list_mutex; + wxCondition* worker_list_empty_cond; + std::list *worker_list; }; class LocalGearyCoordinator : public WeightsManStateObserver { public: // #9 - enum LocalGearyType { univariate, bivariate, eb_rate_standardized, differential, multivariate }; + enum LocalGearyType { + univariate, + bivariate, + eb_rate_standardized, + differential, + multivariate }; LocalGearyCoordinator(boost::uuids::uuid weights_id, Project* project, - const std::vector& var_info, - const std::vector& col_ids, + const vector& var_info, + const vector& col_ids, LocalGearyType local_geary_type, bool calc_significances = true, bool row_standardize_s = true); LocalGearyCoordinator(wxString weights_path, int n, - std::vector >& vars, + vector >& vars, int permutations_s = 599, bool calc_significances_s = true, bool row_standardize_s = true); @@ -100,6 +102,11 @@ class LocalGearyCoordinator : public WeightsManStateObserver int GetSignificanceFilter() { return significance_filter; } int permutations; // any number from 9 to 99999, 99 will be default + + double bo; //Bonferroni bound + + double fdr; //False Discovery Rate + double user_sig_cutoff; // user defined cutoff uint64_t GetLastUsedSeed() { return last_seed_used; } @@ -112,7 +119,7 @@ class LocalGearyCoordinator : public WeightsManStateObserver GdaConst::gda_user_seed = last_seed_used; wxString val; val << last_seed_used; - OGRDataAdapter::GetInstance().AddEntry("gda_user_seed", val.ToStdString()); + OGRDataAdapter::GetInstance().AddEntry("gda_user_seed", val); } bool IsReuseLastSeed() { return reuse_last_seed; } @@ -136,43 +143,20 @@ class LocalGearyCoordinator : public WeightsManStateObserver virtual void closeObserver(boost::uuids::uuid id); -protected: - // The following seven are just temporary pointers into the corresponding - // space-time data arrays below - double* lags; - double* localGeary; // The LocalGeary - double* siglocalGeary; // The significances / pseudo p-vals - // The significance category, generated from siglocalGeary and - // significance cuttoff values below. When saving results to Table, - // only results below significance_cuttoff are non-zero, but sigCat - // results themeslves never change. - //0: >0.05 1: 0.05, 2: 0.01, 3: 0.001, 4: 0.0001 - int* sigCat; - // not-sig=0 HH=1, LL=2, HL=3, LH=4, isolate=5, undef=6. Note: value of - // 0 never appears in cluster itself, it only appears when - // saving results to the Table and indirectly in the map legend - int* cluster; - double* data1; - double* data1_square; - double* data2; - - std::vector current_data; - std::vector current_data_square; - public: - std::vector lags_vecs; - std::vector local_geary_vecs; - std::vector sig_local_geary_vecs; - std::vector sig_cat_vecs; - std::vector cluster_vecs; - - std::vector data1_vecs; - std::vector data1_square_vecs; - std::vector data2_vecs; + vector lags_vecs; + vector local_geary_vecs; + vector sig_local_geary_vecs; + vector sig_cat_vecs; + vector cluster_vecs; + + vector data1_vecs; + vector data1_square_vecs; + vector data2_vecs; boost::uuids::uuid w_id; - std::vector Gal_vecs; - std::vector Gal_vecs_orig; + vector Gal_vecs; + vector Gal_vecs_orig; //const GalElement* W; wxString weight_name; @@ -184,23 +168,23 @@ class LocalGearyCoordinator : public WeightsManStateObserver int num_time_vals; // number of valid time periods based on var_info // These two variables should be empty for LocalGearyMapCanvas - std::vector data; // data[variable][time][obs] - std::vector undef_data; // undef_data[variable][time][obs] + vector data; // data[variable][time][obs] + vector undef_data; // undef_data[variable][time][obs] - std::vector > undef_tms; + vector > undef_tms; // These are for multi variable LocalGeary - std::vector > data_vecs; - std::vector > data_square_vecs; + vector > data_vecs; + vector > data_square_vecs; // All LocalGearyMapCanvas objects synchronize themselves // from the following 6 variables. int ref_var_index; - std::vector var_info; + vector var_info; bool is_any_time_variant; bool is_any_sync_with_global_time; - std::vector map_valid; - std::vector map_error_message; + vector map_valid; + vector map_error_message; bool GetHasIsolates(int time) { return has_isolates[time]; } bool GetHasUndefined(int time) { return has_undefined[time]; } @@ -209,11 +193,12 @@ class LocalGearyCoordinator : public WeightsManStateObserver void removeObserver(LocalGearyCoordinatorObserver* o); void notifyObservers(); /** The list of registered observer objects. */ - std::list observers; + list observers; void CalcPseudoP(); - void CalcPseudoP_range(const GalElement* W, const std::vector& undefs, - int obs_start, int obs_end, uint64_t seed_start); + void CalcPseudoP_range(int obs_start, + int obs_end, + uint64_t seed_start); void InitFromVarInfo(); void VarInfoAttributeChange(); @@ -224,12 +209,12 @@ class LocalGearyCoordinator : public WeightsManStateObserver void DeallocateVectors(); void AllocateVectors(); - void CalcPseudoP_threaded(const GalElement* W, const std::vector& undefs); + void CalcPseudoP_threaded(); void CalcLocalGeary(); void CalcMultiLocalGeary(); void StandardizeData(); - std::vector has_undefined; - std::vector has_isolates; + vector has_undefined; + vector has_isolates; bool row_standardize; bool calc_significances; // if false, then p-vals will never be needed uint64_t last_seed_used; diff --git a/Explore/LocalGearyMapNewView.cpp b/Explore/LocalGearyMapNewView.cpp index 8bea89a93..ef54ecd76 100644 --- a/Explore/LocalGearyMapNewView.cpp +++ b/Explore/LocalGearyMapNewView.cpp @@ -32,10 +32,13 @@ #include "../DialogTools/PermutationCounterDlg.h" #include "../DialogTools/SaveToTableDlg.h" #include "../DialogTools/VariableSettingsDlg.h" +#include "../DialogTools/RandomizationDlg.h" +#include "../VarCalc/WeightsManInterface.h" + #include "ConditionalClusterMapView.h" #include "LocalGearyCoordinator.h" #include "LocalGearyMapNewView.h" -#include "../ShpFile.h" + IMPLEMENT_CLASS(LocalGearyMapCanvas, MapCanvas) BEGIN_EVENT_TABLE(LocalGearyMapCanvas, MapCanvas) @@ -63,8 +66,34 @@ is_bi(isBivariate), is_rate(isEBRate), is_diff(local_geary_coordinator->local_geary_type == LocalGearyCoordinator::differential) { - LOG_MSG("Entering LocalGearyMapCanvas::LocalGearyMapCanvas"); + wxLogMessage("Entering LocalGearyMapCanvas::LocalGearyMapCanvas()"); + str_not_sig = _("Not Significant"); + str_highhigh = _("High-High"); + str_lowlow = _("Low-Low"); + str_otherpos = _("Other Positive"); + str_negative = _("Negative"); + str_positive = _("Positive"); + str_undefined = _("Undefined"); + str_neighborless = _("Neighborless"); + str_p005 = "p = 0.05"; + str_p001 = "p = 0.01"; + str_p0001 = "p = 0.001"; + str_p00001 = "p = 0.0001"; + + SetPredefinedColor(str_not_sig, wxColour(240, 240, 240)); + SetPredefinedColor(str_highhigh, wxColour(178,24,43)); + SetPredefinedColor(str_lowlow, wxColour(239,138,98)); + SetPredefinedColor(str_otherpos, wxColour(253,219,199)); + SetPredefinedColor(str_negative, wxColour(103,173,199)); + SetPredefinedColor(str_positive, wxColour(51,110,161)); + SetPredefinedColor(str_undefined, wxColour(70, 70, 70)); + SetPredefinedColor(str_neighborless, wxColour(140, 140, 140)); + SetPredefinedColor(str_p005, wxColour(75, 255, 80)); + SetPredefinedColor(str_p001, wxColour(6, 196, 11)); + SetPredefinedColor(str_p0001, wxColour(3, 116, 6)); + SetPredefinedColor(str_p00001, wxColour(1, 70, 3)); + cat_classif_def.cat_classif_type = theme_type_s; // must set var_info times from LocalGearyCoordinator initially var_info = local_geary_coordinator->var_info; @@ -74,42 +103,54 @@ is_diff(local_geary_coordinator->local_geary_type == LocalGearyCoordinator::diff } CreateAndUpdateCategories(); - LOG_MSG("Exiting LocalGearyMapCanvas::LocalGearyMapCanvas"); + UpdateStatusBar(); + + wxLogMessage("Exiting LocalGearyMapCanvas::LocalGearyMapCanvas()"); } LocalGearyMapCanvas::~LocalGearyMapCanvas() { - LOG_MSG("In LocalGearyMapCanvas::~LocalGearyMapCanvas"); + wxLogMessage("In LocalGearyMapCanvas::~LocalGearyMapCanvas"); } void LocalGearyMapCanvas::DisplayRightClickMenu(const wxPoint& pos) { - LOG_MSG("Entering LocalGearyMapCanvas::DisplayRightClickMenu"); + wxLogMessage("Entering LocalGearyMapCanvas::DisplayRightClickMenu"); // Workaround for right-click not changing window focus in OSX / wxW 3.0 wxActivateEvent ae(wxEVT_NULL, true, 0, wxActivateEvent::Reason_Mouse); ((LocalGearyMapFrame*) template_frame)->OnActivate(ae); - wxMenu* optMenu = wxXmlResource::Get()-> - LoadMenu("ID_LISAMAP_NEW_VIEW_MENU_OPTIONS"); + wxMenu* optMenu = wxXmlResource::Get()->LoadMenu("ID_LISAMAP_NEW_VIEW_MENU_OPTIONS"); AddTimeVariantOptionsToMenu(optMenu); SetCheckMarks(optMenu); template_frame->UpdateContextMenuItems(optMenu); template_frame->PopupMenu(optMenu, pos + GetPosition()); template_frame->UpdateOptionMenuItems(); - LOG_MSG("Exiting LocalGearyMapCanvas::DisplayRightClickMenu"); + wxLogMessage("Exiting LocalGearyMapCanvas::DisplayRightClickMenu"); } wxString LocalGearyMapCanvas::GetCanvasTitle() { wxString local_geary_t; - if (is_clust && !is_bi) local_geary_t = " LocalGeary Cluster Map"; - if (is_clust && is_bi) local_geary_t = " BiLocalGeary Cluster Map"; - if (is_clust && is_diff) local_geary_t = " Differential LocalGeary Cluster Map"; - - if (!is_clust && !is_bi) local_geary_t = " LocalGeary Significance Map"; - if (!is_clust && is_bi) local_geary_t = " BiLocalGeary Significance Map"; - if (!is_clust && is_diff) local_geary_t = " Differential Significance Map"; + if (is_clust && !is_bi) { + local_geary_t = _(" Local Geary Cluster Map"); + } + if (is_clust && is_bi) { + local_geary_t = _(" Bivariate Local Geary Cluster Map"); + } + if (is_clust && is_diff) { + local_geary_t = _(" Differential Local Geary Cluster Map"); + } + if (!is_clust && !is_bi) { + local_geary_t = _(" Local Geary Significance Map"); + } + if (!is_clust && is_bi) { + local_geary_t = _(" Bivariate LocalGeary Significance Map"); + } + if (!is_clust && is_diff) { + local_geary_t = _(" Differential Significance Map"); + } wxString field_t; if (is_bi) { @@ -137,6 +178,29 @@ wxString LocalGearyMapCanvas::GetCanvasTitle() return ret; } +wxString LocalGearyMapCanvas::GetVariableNames() +{ + wxString field_t; + if (is_bi) { + field_t << GetNameWithTime(0) << " w/ " << GetNameWithTime(1); + } else if (is_diff) { + field_t << GetNameWithTime(0) << " - " << GetNameWithTime(1); + } else if (local_geary_coord->local_geary_type == LocalGearyCoordinator::multivariate) { + for (int i=0; inum_vars; i++) { + field_t << GetNameWithTime(i); + if (i < local_geary_coord->num_vars -1 ) + field_t << ", "; + } + + } else { + field_t << GetNameWithTime(0); + } + if (is_rate) { + field_t << GetNameWithTime(0) << " / " << GetNameWithTime(1); + } + return field_t; +} + /** This method definition is empty. It is here to override any call to the parent-class method since smoothing and theme changes are not supported by LocalGeary maps */ @@ -144,7 +208,7 @@ bool LocalGearyMapCanvas::ChangeMapType(CatClassification::CatClassifType new_map_theme, SmoothingType new_map_smoothing) { - LOG_MSG("In LocalGearyMapCanvas::ChangeMapType"); + wxLogMessage("In LocalGearyMapCanvas::ChangeMapType"); return false; } @@ -167,6 +231,8 @@ void LocalGearyMapCanvas::SetCheckMarks(wxMenu* menu) sig_filter == 3); GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_SIGNIFICANCE_FILTER_0001"), sig_filter == 4); + GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_SIGNIFICANCE_FILTER_SETUP"), + sig_filter == -1); GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_USE_SPECIFIED_SEED"), local_geary_coord->IsReuseLastSeed()); @@ -174,7 +240,7 @@ void LocalGearyMapCanvas::SetCheckMarks(wxMenu* menu) void LocalGearyMapCanvas::TimeChange() { - LOG_MSG("Entering LocalGearyMapCanvas::TimeChange"); + wxLogMessage("Entering LocalGearyMapCanvas::TimeChange"); if (!is_any_sync_with_global_time) return; int cts = project->GetTimeState()->GetCurrTime(); @@ -201,27 +267,73 @@ void LocalGearyMapCanvas::TimeChange() invalidateBms(); PopulateCanvas(); Refresh(); - LOG_MSG("Exiting LocalGearyMapCanvas::TimeChange"); + wxLogMessage("Exiting LocalGearyMapCanvas::TimeChange"); } /** Update Categories based on info in LocalGearyCoordinator */ void LocalGearyMapCanvas::CreateAndUpdateCategories() { + wxLogMessage("Entering LocalGearyMapCanvas::CreateAndUpdateCategories()"); SyncVarInfoFromCoordinator(); cat_data.CreateEmptyCategories(num_time_vals, num_obs); + + double sig_cutoff = local_geary_coord->significance_cutoff; + int s_f = local_geary_coord->GetSignificanceFilter(); + int set_perm = local_geary_coord->permutations; + double stop_sig = 1.0 / (1.0 + set_perm); + + wxString def_cats[4] = {str_p005, str_p001, str_p0001, str_p00001}; + double def_cutoffs[4] = {0.05, 0.01, 0.001, 0.0001}; + bool is_cust_cutoff = true; + for (int i=0; i<4; i++) { + if (sig_cutoff == def_cutoffs[i]) { + is_cust_cutoff = false; + break; + } + } + + if ( is_cust_cutoff ) { + // if set customized cutoff value + wxString lbl = wxString::Format("p = %g", sig_cutoff); + if ( sig_cutoff > 0.05 ) { + def_cutoffs[0] = sig_cutoff; + lbl_color_dict[lbl] = lbl_color_dict[def_cats[0]]; + def_cats[0] = lbl; + } else { + for (int i = 1; i < 4; i++) { + if (def_cutoffs[i-1] + def_cutoffs[i] < 2 * sig_cutoff){ + lbl_color_dict[lbl] = lbl_color_dict[def_cats[i-1]]; + def_cutoffs[i-1] = sig_cutoff; + def_cats[i-1] = lbl; + break; + } else { + lbl_color_dict[lbl] = lbl_color_dict[def_cats[i]]; + def_cutoffs[i] = sig_cutoff; + def_cats[i] = lbl; + break; + } + } + } + } + for (int t=0; tsig_local_geary_vecs[t]; + int* cluster = local_geary_coord->cluster_vecs[t]; + int* sigCat = local_geary_coord->sig_cat_vecs[t]; + int undefined_cat = -1; int isolates_cat = -1; int num_cats = 0; - double stop_sig = 0; + Shapefile::Header& hdr = project->main_data.header; if (local_geary_coord->GetHasIsolates(t)) num_cats++; if (local_geary_coord->GetHasUndefined(t)) num_cats++; + if (is_clust) { if (local_geary_coord->local_geary_type == LocalGearyCoordinator::multivariate) { num_cats += 2; @@ -230,33 +342,8 @@ void LocalGearyMapCanvas::CreateAndUpdateCategories() } else { num_cats += 5; } - } else { - // significance map - // 0: >0.05 1: 0.05, 2: 0.01, 3: 0.001, 4: 0.0001 - int s_f = local_geary_coord->GetSignificanceFilter(); - num_cats += 6 - s_f; - - // issue #474 only show significance levels that can be mapped for the given number of permutations, e.g., for 99 it would stop at 0.01, for 999 at 0.001, etc. - double sig_cutoff = local_geary_coord->significance_cutoff; - int set_perm = local_geary_coord->permutations; - stop_sig = 1.0 / (1.0 + set_perm); - - if ( sig_cutoff >= 0.0001 && stop_sig > 0.0001) { - num_cats -= 1; - } - if ( sig_cutoff >= 0.001 && stop_sig > 0.001 ) { - num_cats -= 1; - } - if ( sig_cutoff >= 0.01 && stop_sig > 0.01 ) { - num_cats -= 1; - } - } - cat_data.CreateCategoriesAtCanvasTm(num_cats, t); - - Shapefile::Header& hdr = project->main_data.header; - - if (is_clust) { - cat_data.SetCategoryLabel(t, 0, "Not Significant"); + cat_data.CreateCategoriesAtCanvasTm(num_cats, t); + cat_data.SetCategoryLabel(t, 0, str_not_sig); if (hdr.shape_type == Shapefile::POINT_TYP) { cat_data.SetCategoryColor(t, 0, wxColour(190, 190, 190)); @@ -264,8 +351,8 @@ void LocalGearyMapCanvas::CreateAndUpdateCategories() cat_data.SetCategoryColor(t, 0, wxColour(240, 240, 240)); } if (local_geary_coord->local_geary_type == LocalGearyCoordinator::multivariate) { - cat_data.SetCategoryLabel(t, 1, "Positive"); - cat_data.SetCategoryColor(t, 1, wxColour(51,110,161)); + cat_data.SetCategoryLabel(t, 1, str_positive); + cat_data.SetCategoryColor(t, 1, lbl_color_dict[str_positive]); if (local_geary_coord->GetHasIsolates(t) && local_geary_coord->GetHasUndefined(t)) { @@ -278,10 +365,10 @@ void LocalGearyMapCanvas::CreateAndUpdateCategories() } } else if (local_geary_coord->local_geary_type == LocalGearyCoordinator::bivariate) { - cat_data.SetCategoryLabel(t, 1, "Positive"); - cat_data.SetCategoryColor(t, 1, wxColour(51,110,161)); - cat_data.SetCategoryLabel(t, 2, "Negative"); - cat_data.SetCategoryColor(t, 2, wxColour(113,250,142)); + cat_data.SetCategoryLabel(t, 1, str_positive); + cat_data.SetCategoryColor(t, 1, lbl_color_dict[str_positive]); + cat_data.SetCategoryLabel(t, 2, str_negative); + cat_data.SetCategoryColor(t, 2, lbl_color_dict[str_negative]);//wxColour(113,250,142)); if (local_geary_coord->GetHasIsolates(t) && local_geary_coord->GetHasUndefined(t)) { @@ -294,14 +381,14 @@ void LocalGearyMapCanvas::CreateAndUpdateCategories() } } else { - cat_data.SetCategoryLabel(t, 1, "High-High"); - cat_data.SetCategoryColor(t, 1, wxColour(178,24,43)); - cat_data.SetCategoryLabel(t, 2, "Low-Low"); - cat_data.SetCategoryColor(t, 2, wxColour(239,138,98)); - cat_data.SetCategoryLabel(t, 3, "Other Pos"); - cat_data.SetCategoryColor(t, 3, wxColour(253,219,199)); - cat_data.SetCategoryLabel(t, 4, "Negative"); - cat_data.SetCategoryColor(t, 4, wxColour(103,173,199)); + cat_data.SetCategoryLabel(t, 1, str_highhigh); + cat_data.SetCategoryColor(t, 1, lbl_color_dict[str_highhigh]); + cat_data.SetCategoryLabel(t, 2, str_lowlow); + cat_data.SetCategoryColor(t, 2, lbl_color_dict[str_lowlow]); + cat_data.SetCategoryLabel(t, 3, str_otherpos); + cat_data.SetCategoryColor(t, 3, lbl_color_dict[str_otherpos]); + cat_data.SetCategoryLabel(t, 4, str_negative); + cat_data.SetCategoryColor(t, 4, lbl_color_dict[str_negative]);//wxColour(103,173,199)); if (local_geary_coord->GetHasIsolates(t) && local_geary_coord->GetHasUndefined(t)) { @@ -313,70 +400,17 @@ void LocalGearyMapCanvas::CreateAndUpdateCategories() isolates_cat = 5; } } - - - } else { - // 0: >0.05 1: 0.05, 2: 0.01, 3: 0.001, 4: 0.0001 - int s_f = local_geary_coord->GetSignificanceFilter(); - cat_data.SetCategoryLabel(t, 0, "Not Significant"); - - if (hdr.shape_type == Shapefile::POINT_TYP) { - cat_data.SetCategoryColor(t, 0, wxColour(190, 190, 190)); - } else { - cat_data.SetCategoryColor(t, 0, wxColour(240, 240, 240)); + if (undefined_cat != -1) { + cat_data.SetCategoryLabel(t, undefined_cat, str_undefined); + cat_data.SetCategoryColor(t, undefined_cat, lbl_color_dict[str_undefined]); + } + if (isolates_cat != -1) { + cat_data.SetCategoryLabel(t, isolates_cat, str_neighborless); + cat_data.SetCategoryColor(t, isolates_cat, lbl_color_dict[str_neighborless]); } - - int skip_cat = 0; - if (s_f <=4 && stop_sig <= 0.0001) { - cat_data.SetCategoryLabel(t, 5-s_f, "p = 0.0001"); - cat_data.SetCategoryColor(t, 5-s_f, wxColour(1, 70, 3)); - } else skip_cat++; - - if (s_f <= 3 && stop_sig <= 0.001) { - cat_data.SetCategoryLabel(t, 4-s_f, "p = 0.001"); - cat_data.SetCategoryColor(t, 4-s_f, wxColour(3, 116, 6)); - } else skip_cat++; - - if (s_f <= 2 && stop_sig <= 0.01) { - cat_data.SetCategoryLabel(t, 3-s_f, "p = 0.01"); - cat_data.SetCategoryColor(t, 3-s_f, wxColour(6, 196, 11)); - } else skip_cat++; - - if (s_f <= 1) { - cat_data.SetCategoryLabel(t, 2-s_f, "p = 0.05"); - cat_data.SetCategoryColor(t, 2-s_f, wxColour(75, 255, 80)); - } - if (local_geary_coord->GetHasIsolates(t) && - local_geary_coord->GetHasUndefined(t)) { - isolates_cat = 6 - s_f - skip_cat; - undefined_cat = 7 - s_f - skip_cat; - - } else if (local_geary_coord->GetHasUndefined(t)) { - undefined_cat = 6 -s_f - skip_cat; - - } else if (local_geary_coord->GetHasIsolates(t)) { - isolates_cat = 6 - s_f -skip_cat; - - } - } - if (undefined_cat != -1) { - cat_data.SetCategoryLabel(t, undefined_cat, "Undefined"); - cat_data.SetCategoryColor(t, undefined_cat, wxColour(70, 70, 70)); - } - if (isolates_cat != -1) { - cat_data.SetCategoryLabel(t, isolates_cat, "Neighborless"); - cat_data.SetCategoryColor(t, isolates_cat, wxColour(140, 140, 140)); - } - - double cuttoff = local_geary_coord->significance_cutoff; - double* p = local_geary_coord->sig_local_geary_vecs[t]; - int* cluster = local_geary_coord->cluster_vecs[t]; - int* sigCat = local_geary_coord->sig_cat_vecs[t]; - - if (is_clust) { if (local_geary_coord->local_geary_type == LocalGearyCoordinator::multivariate) { for (int i=0, iend=local_geary_coord->num_obs; i cuttoff && cluster[i] != 2 && cluster[i] != 3) { + if (p[i] > sig_cutoff && cluster[i] != 2 && cluster[i] != 3) { cat_data.AppendIdToCategory(t, 0, i); // not significant } else if (cluster[i] == 2) { cat_data.AppendIdToCategory(t, isolates_cat, i); @@ -388,7 +422,7 @@ void LocalGearyMapCanvas::CreateAndUpdateCategories() } } else { for (int i=0, iend=local_geary_coord->num_obs; i cuttoff && cluster[i] != 5 && cluster[i] != 6) { + if (p[i] > sig_cutoff && cluster[i] != 5 && cluster[i] != 6) { cat_data.AppendIdToCategory(t, 0, i); // not significant } else if (cluster[i] == 5) { cat_data.AppendIdToCategory(t, isolates_cat, i); @@ -399,45 +433,119 @@ void LocalGearyMapCanvas::CreateAndUpdateCategories() } } } + } else { - int s_f = local_geary_coord->GetSignificanceFilter(); + // significance map + // 0: >0.05 1: 0.05, 2: 0.01, 3: 0.001, 4: 0.0001 + + num_cats = 5; + for (int j=0; j < 4; j++) { + if (sig_cutoff < def_cutoffs[j]) + num_cats -= 1; + } + + // issue #474 only show significance levels that can be mapped for the given number of permutations, e.g., for 99 it would stop at 0.01, for 999 at 0.001, etc. + if ( sig_cutoff >= def_cutoffs[3] && stop_sig > def_cutoffs[3] ){ //0.0001 + num_cats -= 1; + } + if ( sig_cutoff >= def_cutoffs[2] && stop_sig > def_cutoffs[2] ){ //0.001 + num_cats -= 1; + } + if ( sig_cutoff >= def_cutoffs[1] && stop_sig > def_cutoffs[1] ){ //0.01 + num_cats -= 1; + } + cat_data.CreateCategoriesAtCanvasTm(num_cats, t); + + // 0: >0.05 1: 0.05, 2: 0.01, 3: 0.001, 4: 0.0001 + cat_data.SetCategoryLabel(t, 0, str_not_sig); + + if (hdr.shape_type == Shapefile::POINT_TYP) { + cat_data.SetCategoryColor(t, 0, wxColour(190, 190, 190)); + } else { + cat_data.SetCategoryColor(t, 0, wxColour(240, 240, 240)); + } + + int cat_idx = 1; + std::map level_cat_dict; + for (int j=0; j < 4; j++) { + if (sig_cutoff >= def_cutoffs[j] && def_cutoffs[j] >= stop_sig) { + cat_data.SetCategoryColor(t, cat_idx, lbl_color_dict[def_cats[j]]); + cat_data.SetCategoryLabel(t, cat_idx, def_cats[j]); + level_cat_dict[j] = cat_idx; + cat_idx += 1; + } + } + + if (local_geary_coord->GetHasIsolates(t) && + local_geary_coord->GetHasUndefined(t)) { + isolates_cat = cat_idx++; + undefined_cat = cat_idx++; + + } else if (local_geary_coord->GetHasUndefined(t)) { + undefined_cat = cat_idx++; + + } else if (local_geary_coord->GetHasIsolates(t)) { + isolates_cat = cat_idx++; + } + + if (undefined_cat != -1) { + cat_data.SetCategoryLabel(t, undefined_cat, str_undefined); + cat_data.SetCategoryColor(t, undefined_cat, lbl_color_dict[str_undefined]); + } + if (isolates_cat != -1) { + cat_data.SetCategoryLabel(t, isolates_cat, str_neighborless); + cat_data.SetCategoryColor(t, isolates_cat, lbl_color_dict[str_neighborless]); + } + int s_f = local_geary_coord->GetSignificanceFilter(); if (local_geary_coord->local_geary_type == LocalGearyCoordinator::multivariate) { for (int i=0, iend=local_geary_coord->num_obs; i cuttoff && cluster[i] != 2 && cluster[i] != 3) { + if (p[i] > sig_cutoff && cluster[i] != 2 && cluster[i] != 3) { cat_data.AppendIdToCategory(t, 0, i); // not significant } else if (cluster[i] == 2) { cat_data.AppendIdToCategory(t, isolates_cat, i); } else if (cluster[i] == 3) { cat_data.AppendIdToCategory(t, undefined_cat, i); } else { - cat_data.AppendIdToCategory(t, (sigCat[i]-s_f)+1, i); + //cat_data.AppendIdToCategory(t, (sigCat[i]-s_f)+1, i); + for ( int c = 4-1; c >= 0; c-- ) { + if ( p[i] <= def_cutoffs[c] ) { + cat_data.AppendIdToCategory(t, level_cat_dict[c], i); + break; + } + } } } } else { for (int i=0, iend=local_geary_coord->num_obs; i cuttoff && cluster[i] != 5 && cluster[i] != 6) { + if (p[i] > sig_cutoff && cluster[i] != 5 && cluster[i] != 6) { cat_data.AppendIdToCategory(t, 0, i); // not significant } else if (cluster[i] == 5) { cat_data.AppendIdToCategory(t, isolates_cat, i); } else if (cluster[i] == 6) { cat_data.AppendIdToCategory(t, undefined_cat, i); } else { - cat_data.AppendIdToCategory(t, (sigCat[i]-s_f)+1, i); + //cat_data.AppendIdToCategory(t, (sigCat[i]-s_f)+1, i); + for ( int c = 4-1; c >= 0; c-- ) { + if ( p[i] <= def_cutoffs[c] ) { + cat_data.AppendIdToCategory(t, level_cat_dict[c], i); + break; + } + } } } } } + for (int cat=0; catmy_times(var_info.size()); for (int t=0; tvar_info; @@ -459,11 +568,13 @@ void LocalGearyMapCanvas::SyncVarInfoFromCoordinator() num_time_vals = local_geary_coord->num_time_vals; map_valid = local_geary_coord->map_valid; map_error_message = local_geary_coord->map_error_message; + + wxLogMessage("Exiting LocalGearyMapCanvas::SyncVarInfoFromCoordinator"); } void LocalGearyMapCanvas::TimeSyncVariableToggle(int var_index) { - LOG_MSG("In LocalGearyMapCanvas::TimeSyncVariableToggle"); + wxLogMessage("In LocalGearyMapCanvas::TimeSyncVariableToggle"); local_geary_coord->var_info[var_index].sync_with_global_time = !local_geary_coord->var_info[var_index].sync_with_global_time; for (int i=0; inotifyObservers(); } +void LocalGearyMapCanvas::UpdateStatusBar() +{ + wxStatusBar* sb = 0; + if (template_frame) { + sb = template_frame->GetStatusBar(); + } + if (!sb) + return; + wxString s; + s << _("#obs=") << project->GetNumRecords() <<" "; + + if ( highlight_state->GetTotalHighlighted() > 0) { + // for highlight from other windows + s << _("#selected=") << highlight_state->GetTotalHighlighted()<< " "; + } + if (mousemode == select && selectstate == start) { + if (total_hover_obs >= 1) { + s << _("#hover obs ") << hover_obs[0]+1; + } + if (total_hover_obs >= 2) { + s << ", "; + s << _("obs ") << hover_obs[1]+1; + } + if (total_hover_obs >= 3) { + s << ", "; + s << _("obs ") << hover_obs[2]+1; + } + if (total_hover_obs >= 4) { + s << ", ..."; + } + } + if (is_clust && local_geary_coord) { + double p_val = local_geary_coord->significance_cutoff; + wxString inf_str = wxString::Format(" p <= %g", p_val); + s << inf_str; + } + sb->SetStatusText(s); +} + IMPLEMENT_CLASS(LocalGearyMapFrame, MapFrame) BEGIN_EVENT_TABLE(LocalGearyMapFrame, MapFrame) @@ -489,8 +639,9 @@ LocalGearyMapFrame::LocalGearyMapFrame(wxFrame *parent, Project* project, : MapFrame(parent, project, pos, size, style), local_geary_coord(local_geary_coordinator) { - LOG_MSG("Entering LocalGearyMapFrame::LocalGearyMapFrame"); + wxLogMessage("Entering LocalGearyMapFrame::LocalGearyMapFrame"); + no_update_weights = true; int width, height; GetClientSize(&width, &height); @@ -501,6 +652,8 @@ local_geary_coord(local_geary_coordinator) CatClassification::CatClassifType theme_type_s = isClusterMap ? CatClassification::local_geary_categories : CatClassification::local_geary_significance; + DisplayStatusBar(true); + wxPanel* rpanel = new wxPanel(splitter_win); template_canvas = new LocalGearyMapCanvas(rpanel, this, project, local_geary_coordinator, @@ -513,7 +666,10 @@ local_geary_coord(local_geary_coordinator) wxBoxSizer* rbox = new wxBoxSizer(wxVERTICAL); rbox->Add(template_canvas, 1, wxEXPAND); rpanel->SetSizer(rbox); - + + WeightsManInterface* w_man_int = project->GetWManInt(); + ((MapCanvas*) template_canvas)->SetWeightsId(w_man_int->GetDefault()); + wxPanel* lpanel = new wxPanel(splitter_win); template_legend = new MapNewLegend(lpanel, template_canvas, wxPoint(0,0), wxSize(0,0)); @@ -526,9 +682,9 @@ local_geary_coord(local_geary_coordinator) wxPanel* toolbar_panel = new wxPanel(this,-1, wxDefaultPosition); wxBoxSizer* toolbar_sizer= new wxBoxSizer(wxVERTICAL); - wxToolBar* tb = wxXmlResource::Get()->LoadToolBar(toolbar_panel, "ToolBar_MAP"); + toolbar = wxXmlResource::Get()->LoadToolBar(toolbar_panel, "ToolBar_MAP"); SetupToolbar(); - toolbar_sizer->Add(tb, 0, wxEXPAND|wxALL); + toolbar_sizer->Add(toolbar, 0, wxEXPAND|wxALL); toolbar_panel->SetSizerAndFit(toolbar_sizer); wxBoxSizer* sizer = new wxBoxSizer(wxVERTICAL); @@ -538,18 +694,17 @@ local_geary_coord(local_geary_coordinator) //splitter_win->SetSize(wxSize(width,height)); SetAutoLayout(true); - DisplayStatusBar(true); SetTitle(template_canvas->GetCanvasTitle()); local_geary_coord->registerObserver(this); Show(true); - LOG_MSG("Exiting LocalGearyMapFrame::LocalGearyMapFrame"); + wxLogMessage("Exiting LocalGearyMapFrame::LocalGearyMapFrame"); } LocalGearyMapFrame::~LocalGearyMapFrame() { - LOG_MSG("In LocalGearyMapFrame::~LocalGearyMapFrame"); + wxLogMessage("In LocalGearyMapFrame::~LocalGearyMapFrame"); if (local_geary_coord) { local_geary_coord->removeObserver(this); local_geary_coord = 0; @@ -558,7 +713,7 @@ LocalGearyMapFrame::~LocalGearyMapFrame() void LocalGearyMapFrame::OnActivate(wxActivateEvent& event) { - LOG_MSG("In LocalGearyMapFrame::OnActivate"); + wxLogMessage("In LocalGearyMapFrame::OnActivate"); if (event.GetActive()) { RegisterAsActive("LocalGearyMapFrame", GetTitle()); } @@ -567,15 +722,14 @@ void LocalGearyMapFrame::OnActivate(wxActivateEvent& event) void LocalGearyMapFrame::MapMenus() { - LOG_MSG("In LocalGearyMapFrame::MapMenus"); + wxLogMessage("In LocalGearyMapFrame::MapMenus"); wxMenuBar* mb = GdaFrame::GetGdaFrame()->GetMenuBar(); // Map Options Menus - wxMenu* optMenu = wxXmlResource::Get()-> - LoadMenu("ID_LISAMAP_NEW_VIEW_MENU_OPTIONS"); + wxMenu* optMenu = wxXmlResource::Get()->LoadMenu("ID_LISAMAP_NEW_VIEW_MENU_OPTIONS"); ((MapCanvas*) template_canvas)-> AddTimeVariantOptionsToMenu(optMenu); ((MapCanvas*) template_canvas)->SetCheckMarks(optMenu); - GeneralWxUtils::ReplaceMenu(mb, "Options", optMenu); + GeneralWxUtils::ReplaceMenu(mb, _("Options"), optMenu); UpdateOptionMenuItems(); } @@ -583,7 +737,7 @@ void LocalGearyMapFrame::UpdateOptionMenuItems() { TemplateFrame::UpdateOptionMenuItems(); // set common items first wxMenuBar* mb = GdaFrame::GetGdaFrame()->GetMenuBar(); - int menu = mb->FindMenu("Options"); + int menu = mb->FindMenu(_("Options")); if (menu == wxNOT_FOUND) { LOG_MSG("LocalGearyMapFrame::UpdateOptionMenuItems: " "Options menu not found"); @@ -604,11 +758,17 @@ void LocalGearyMapFrame::UpdateContextMenuItems(wxMenu* menu) void LocalGearyMapFrame::RanXPer(int permutation) { + wxString msg; + msg << "Entering LocalGearyMapFrame::RanXPer() " << permutation; + wxLogMessage(msg); + if (permutation < 9) permutation = 9; if (permutation > 99999) permutation = 99999; local_geary_coord->permutations = permutation; local_geary_coord->CalcPseudoP(); local_geary_coord->notifyObservers(); + + wxLogMessage("Exiting LocalGearyMapFrame::RanXPer()"); } void LocalGearyMapFrame::OnRan99Per(wxCommandEvent& event) @@ -636,18 +796,27 @@ void LocalGearyMapFrame::OnRanOtherPer(wxCommandEvent& event) PermutationCounterDlg dlg(this); if (dlg.ShowModal() == wxID_OK) { long num; - dlg.m_number->GetValue().ToLong(&num); + + wxString input = dlg.m_number->GetValue(); + + wxLogMessage(input); + + input.ToLong(&num); RanXPer(num); } } void LocalGearyMapFrame::OnUseSpecifiedSeed(wxCommandEvent& event) { + wxLogMessage("Entering LocalGearyMapFrame::OnUseSpecifiedSeed()"); local_geary_coord->SetReuseLastSeed(!local_geary_coord->IsReuseLastSeed()); + wxLogMessage("Exiting LocalGearyMapFrame::OnUseSpecifiedSeed()"); } void LocalGearyMapFrame::OnSpecifySeedDlg(wxCommandEvent& event) { + wxLogMessage("Entering LocalGearyMapFrame::OnSpecifySeedDlg()"); + uint64_t last_seed = local_geary_coord->GetLastUsedSeed(); wxString m; m << "The last seed used by the pseudo random\nnumber "; @@ -659,9 +828,12 @@ void LocalGearyMapFrame::OnSpecifySeedDlg(wxCommandEvent& event) wxString cur_val; cur_val << last_seed; - wxTextEntryDialog dlg(NULL, m, "Enter a seed value", cur_val); + wxTextEntryDialog dlg(NULL, m, _("Enter a seed value"), cur_val); if (dlg.ShowModal() != wxID_OK) return; dlg_val = dlg.GetValue(); + + wxLogMessage(dlg_val); + dlg_val.Trim(true); dlg_val.Trim(false); if (dlg_val.IsEmpty()) return; @@ -670,19 +842,26 @@ void LocalGearyMapFrame::OnSpecifySeedDlg(wxCommandEvent& event) uint64_t new_seed_val = val; local_geary_coord->SetLastUsedSeed(new_seed_val); } else { - wxString m; - m << "\"" << dlg_val << "\" is not a valid seed. Seed unchanged."; - wxMessageDialog dlg(NULL, m, "Error", wxOK | wxICON_ERROR); + wxString m = _("\"%s\" is not a valid seed. Seed unchanged."); + m = wxString::Format(m, dlg_val); + wxMessageDialog dlg(NULL, m, _("Error"), wxOK | wxICON_ERROR); dlg.ShowModal(); } + wxLogMessage("Exiting LocalGearyMapFrame::OnSpecifySeedDlg()"); } void LocalGearyMapFrame::SetSigFilterX(int filter) { + wxString msg; + msg << "Entering LocalGearyMapFrame::SetSigFilterX() " << filter; + wxLogMessage(msg); + if (filter == local_geary_coord->GetSignificanceFilter()) return; local_geary_coord->SetSignificanceFilter(filter); local_geary_coord->notifyObservers(); UpdateOptionMenuItems(); + + wxLogMessage("Exiting LocalGearyMapFrame::SetSigFilterX()"); } void LocalGearyMapFrame::OnSigFilter05(wxCommandEvent& event) @@ -705,8 +884,37 @@ void LocalGearyMapFrame::OnSigFilter0001(wxCommandEvent& event) SetSigFilterX(4); } +void LocalGearyMapFrame::OnSigFilterSetup(wxCommandEvent& event) +{ + wxLogMessage("Entering LocalGearyMapFrame::OnSigFilterSetup()"); + + LocalGearyMapCanvas* lc = (LocalGearyMapCanvas*)template_canvas; + int t = template_canvas->cat_data.GetCurrentCanvasTmStep(); + double* p = local_geary_coord->sig_local_geary_vecs[t]; + int n = local_geary_coord->num_obs; + + wxString ttl = _("Inference Settings"); + ttl << " (" << local_geary_coord->permutations << " perm)"; + + double user_sig = local_geary_coord->significance_cutoff; + if (local_geary_coord->GetSignificanceFilter()<0) user_sig = local_geary_coord->user_sig_cutoff; + + InferenceSettingsDlg dlg(this, user_sig, p, n, ttl); + if (dlg.ShowModal() == wxID_OK) { + local_geary_coord->SetSignificanceFilter(-1); + local_geary_coord->significance_cutoff = dlg.GetAlphaLevel(); + local_geary_coord->user_sig_cutoff = dlg.GetUserInput(); + local_geary_coord->notifyObservers(); + local_geary_coord->bo = dlg.GetBO(); + local_geary_coord->fdr = dlg.GetFDR(); + UpdateOptionMenuItems(); + } + wxLogMessage("Exiting LocalGearyMapFrame::OnSigFilterSetup()"); +} + void LocalGearyMapFrame::OnSaveLocalGeary(wxCommandEvent& event) { + wxLogMessage("Entering LocalGearyMapFrame::OnSaveLocalGeary()"); int t = template_canvas->cat_data.GetCurrentCanvasTmStep(); LocalGearyMapCanvas* lc = (LocalGearyMapCanvas*)template_canvas; @@ -730,7 +938,7 @@ void LocalGearyMapFrame::OnSaveLocalGeary(wxCommandEvent& event) } data[0].d_val = &tempLocalMoran; data[0].label = "LocalGeary Indices"; - data[0].field_default = "LocalGeary_I"; + data[0].field_default = "Geary_I"; data[0].type = GdaConst::double_type; data[0].undefined = &undefs; @@ -747,7 +955,7 @@ void LocalGearyMapFrame::OnSaveLocalGeary(wxCommandEvent& event) } data[1].l_val = &clust; data[1].label = "Clusters"; - data[1].field_default = "LocalGeary_CL"; + data[1].field_default = "Geary_CL"; data[1].type = GdaConst::long64_type; data[1].undefined = &undefs; @@ -767,7 +975,7 @@ void LocalGearyMapFrame::OnSaveLocalGeary(wxCommandEvent& event) data[2].d_val = &sig; data[2].label = "Significance"; - data[2].field_default = "LocalGeary_P"; + data[2].field_default = "Geary_P"; data[2].type = GdaConst::double_type; data[2].undefined = &undefs; @@ -780,13 +988,17 @@ void LocalGearyMapFrame::OnSaveLocalGeary(wxCommandEvent& event) } SaveToTableDlg dlg(project, this, data, - "Save Results: LocalGeary", + _("Save Results: LocalGeary"), wxDefaultPosition, wxSize(400,400)); dlg.ShowModal(); + + wxLogMessage("Exiting LocalGearyMapFrame::OnSaveLocalGeary()"); } void LocalGearyMapFrame::CoreSelectHelper(const std::vector& elem) { + wxLogMessage("Entering LocalGearyMapFrame::CoreSelectHelper()"); + HighlightState* highlight_state = project->GetHighlightState(); std::vector& hs = highlight_state->GetHighlight(); bool selection_changed = false; @@ -804,43 +1016,58 @@ void LocalGearyMapFrame::CoreSelectHelper(const std::vector& elem) highlight_state->SetEventType(HLStateInt::delta); highlight_state->notifyObservers(); } + wxLogMessage("Exiting LocalGearyMapFrame::CoreSelectHelper()"); } void LocalGearyMapFrame::OnSelectCores(wxCommandEvent& event) { - LOG_MSG("Entering LocalGearyMapFrame::OnSelectCores"); + wxLogMessage("Entering LocalGearyMapFrame::OnSelectCores"); std::vector elem(local_geary_coord->num_obs, false); int ts = template_canvas->cat_data.GetCurrentCanvasTmStep(); int* clust = local_geary_coord->cluster_vecs[ts]; int* sig_cat = local_geary_coord->sig_cat_vecs[ts]; + double* sig_val = local_geary_coord->sig_local_geary_vecs[ts]; int sf = local_geary_coord->significance_filter; + double user_sig = local_geary_coord->significance_cutoff; // add all cores to elem list. for (int i=0; inum_obs; i++) { - if (clust[i] >= 1 && clust[i] <= 4 && sig_cat[i] >= sf) { + if (clust[i] >= 1 && clust[i] <= 4) { + bool cont = true; + if (sf >=0 && sig_cat[i] >= sf) cont = false; + if (sf < 0 && sig_val[i] < user_sig) cont = false; + if (cont) continue; elem[i] = true; } } CoreSelectHelper(elem); - LOG_MSG("Exiting LocalGearyMapFrame::OnSelectCores"); + wxLogMessage("Exiting LocalGearyMapFrame::OnSelectCores"); } void LocalGearyMapFrame::OnSelectNeighborsOfCores(wxCommandEvent& event) { - LOG_MSG("Entering LocalGearyMapFrame::OnSelectNeighborsOfCores"); + wxLogMessage("Entering LocalGearyMapFrame::OnSelectNeighborsOfCores"); std::vector elem(local_geary_coord->num_obs, false); int ts = template_canvas->cat_data.GetCurrentCanvasTmStep(); int* clust = local_geary_coord->cluster_vecs[ts]; int* sig_cat = local_geary_coord->sig_cat_vecs[ts]; + double* sig_val = local_geary_coord->sig_local_geary_vecs[ts]; int sf = local_geary_coord->significance_filter; const GalElement* W = local_geary_coord->Gal_vecs_orig[ts]->gal; + double user_sig = local_geary_coord->significance_cutoff; + // add all cores and neighbors of cores to elem list for (int i=0; inum_obs; i++) { - if (clust[i] >= 1 && clust[i] <= 4 && sig_cat[i] >= sf) { + if (clust[i] >= 1 && clust[i] <= 4) { + bool cont = true; + if (sf >=0 && sig_cat[i] >= sf) cont = false; + if (sf < 0 && sig_val[i] < user_sig) cont = false; + if (cont) continue; + elem[i] = true; const GalElement& e = W[i]; for (int j=0, jend=e.Size(); jnum_obs; i++) { - if (clust[i] >= 1 && clust[i] <= 4 && sig_cat[i] >= sf) { + if (clust[i] >= 1 && clust[i] <= 4) { + bool cont = true; + if (sf >=0 && sig_cat[i] >= sf) cont = false; + if (sf < 0 && sig_val[i] < user_sig) cont = false; + if (cont) continue; + elem[i] = false; } } CoreSelectHelper(elem); - LOG_MSG("Exiting LocalGearyMapFrame::OnSelectNeighborsOfCores"); + wxLogMessage("Exiting LocalGearyMapFrame::OnSelectNeighborsOfCores"); } void LocalGearyMapFrame::OnSelectCoresAndNeighbors(wxCommandEvent& event) { - LOG_MSG("Entering LocalGearyMapFrame::OnSelectCoresAndNeighbors"); + wxLogMessage("Entering LocalGearyMapFrame::OnSelectCoresAndNeighbors"); std::vector elem(local_geary_coord->num_obs, false); int ts = template_canvas->cat_data.GetCurrentCanvasTmStep(); int* clust = local_geary_coord->cluster_vecs[ts]; int* sig_cat = local_geary_coord->sig_cat_vecs[ts]; + double* sig_val = local_geary_coord->sig_local_geary_vecs[ts]; int sf = local_geary_coord->significance_filter; const GalElement* W = local_geary_coord->Gal_vecs_orig[ts]->gal; + + double user_sig = local_geary_coord->significance_cutoff; // add all cores and neighbors of cores to elem list for (int i=0; inum_obs; i++) { - if (clust[i] >= 1 && clust[i] <= 4 && sig_cat[i] >= sf) { + if (clust[i] >= 1 && clust[i] <= 4 ) { + bool cont = true; + if (sf >=0 && sig_cat[i] >= sf) cont = false; + if (sf < 0 && sig_val[i] < user_sig) cont = false; + if (cont) continue; + elem[i] = true; const GalElement& e = W[i]; for (int j=0, jend=e.Size(); jcat_data.GetCurrentCanvasTmStep(); - GalWeight* gal_weights = local_geary_coord->Gal_vecs_orig[ts]; - - HighlightState& hs = *project->GetHighlightState(); - std::vector& h = hs.GetHighlight(); - int nh_cnt = 0; - std::vector add_elem(gal_weights->num_obs, false); - - std::vector new_highlight_ids; - - for (int i=0; inum_obs; i++) { - if (h[i]) { - GalElement& e = gal_weights->gal[i]; - for (int j=0, jend=e.Size(); j 0) { - hs.SetEventType(HLStateInt::delta); - hs.notifyObservers(); - } + wxLogMessage("Exiting LocalGearyMapFrame::OnSelectCoresAndNeighbors"); } void LocalGearyMapFrame::OnShowAsConditionalMap(wxCommandEvent& event) { + wxLogMessage("In LocalGearyMapFrame::OnShowAsConditionalMap"); + VariableSettingsDlg dlg(project, VariableSettingsDlg::bivariate, false, false, - _("Conditional LocalGeary Map Variables"), + _("Conditional Local Geary Map Variables"), _("Horizontal Cells"), _("Vertical Cells")); @@ -949,17 +1155,20 @@ void LocalGearyMapFrame::OnShowAsConditionalMap(wxCommandEvent& event) - new randomization for p-vals and therefore categories have changed */ void LocalGearyMapFrame::update(LocalGearyCoordinator* o) { + wxLogMessage("In LocalGearyMapFrame::update"); + LocalGearyMapCanvas* lc = (LocalGearyMapCanvas*) template_canvas; lc->SyncVarInfoFromCoordinator(); lc->CreateAndUpdateCategories(); if (template_legend) template_legend->Recreate(); SetTitle(lc->GetCanvasTitle()); lc->Refresh(); + lc->UpdateStatusBar(); } void LocalGearyMapFrame::closeObserver(LocalGearyCoordinator* o) { - LOG_MSG("In LocalGearyMapFrame::closeObserver(LocalGearyCoordinator*)"); + wxLogMessage("In LocalGearyMapFrame::closeObserver(LocalGearyCoordinator*)"); if (local_geary_coord) { local_geary_coord->removeObserver(this); local_geary_coord = 0; @@ -969,6 +1178,8 @@ void LocalGearyMapFrame::closeObserver(LocalGearyCoordinator* o) void LocalGearyMapFrame::GetVizInfo(std::vector& clusters) { + wxLogMessage("In LocalGearyMapFrame::GetVizInfo()"); + if (local_geary_coord) { if(local_geary_coord->sig_cat_vecs.size()>0) { for (int i=0; inum_obs;i++) { diff --git a/Explore/LocalGearyMapNewView.h b/Explore/LocalGearyMapNewView.h index 6d6868468..960069593 100644 --- a/Explore/LocalGearyMapNewView.h +++ b/Explore/LocalGearyMapNewView.h @@ -42,6 +42,7 @@ class LocalGearyMapCanvas : public MapCanvas virtual ~LocalGearyMapCanvas(); virtual void DisplayRightClickMenu(const wxPoint& pos); virtual wxString GetCanvasTitle(); + virtual wxString GetVariableNames(); virtual bool ChangeMapType(CatClassification::CatClassifType new_map_theme, SmoothingType new_map_smoothing); virtual void SetCheckMarks(wxMenu* menu); @@ -49,7 +50,12 @@ class LocalGearyMapCanvas : public MapCanvas void SyncVarInfoFromCoordinator(); virtual void CreateAndUpdateCategories(); virtual void TimeSyncVariableToggle(int var_index); - + virtual void UpdateStatusBar(); + virtual void SetWeightsId(boost::uuids::uuid id) { weights_id = id; } + + double bo; + double fdr; + bool is_diff; protected: @@ -58,6 +64,19 @@ class LocalGearyMapCanvas : public MapCanvas bool is_bi; // true = Bivariate, false = Univariate bool is_rate; // true = Moran Empirical Bayes Rate Smoothing + wxString str_not_sig; + wxString str_highhigh; + wxString str_lowlow; + wxString str_negative; + wxString str_positive; + wxString str_otherpos; + wxString str_undefined; + wxString str_neighborless; + wxString str_p005; + wxString str_p001; + wxString str_p0001; + wxString str_p00001; + DECLARE_EVENT_TABLE() }; @@ -78,6 +97,7 @@ class LocalGearyMapFrame : public MapFrame, public LocalGearyCoordinatorObserver virtual void MapMenus(); virtual void UpdateOptionMenuItems(); virtual void UpdateContextMenuItems(wxMenu* menu); + virtual void update(WeightsManState* o){} void RanXPer(int permutation); void OnRan99Per(wxCommandEvent& event); @@ -94,14 +114,14 @@ class LocalGearyMapFrame : public MapFrame, public LocalGearyCoordinatorObserver void OnSigFilter01(wxCommandEvent& event); void OnSigFilter001(wxCommandEvent& event); void OnSigFilter0001(wxCommandEvent& event); - + void OnSigFilterSetup(wxCommandEvent& event); + void OnSaveLocalGeary(wxCommandEvent& event); void OnSelectCores(wxCommandEvent& event); void OnSelectNeighborsOfCores(wxCommandEvent& event); void OnSelectCoresAndNeighbors(wxCommandEvent& event); - void OnAddNeighborToSelection(wxCommandEvent& event); - + void OnShowAsConditionalMap(wxCommandEvent& event); virtual void update(LocalGearyCoordinator* o); diff --git a/Explore/LowessParamDlg.cpp b/Explore/LowessParamDlg.cpp index 0f12faf54..0c3b28ea7 100644 --- a/Explore/LowessParamDlg.cpp +++ b/Explore/LowessParamDlg.cpp @@ -17,6 +17,7 @@ * along with this program. If not, see . */ +#include #include #include #include @@ -28,14 +29,13 @@ #include "../DialogTools/WebViewHelpWin.h" #include "LowessParamDlg.h" -LowessParamFrame::LowessParamFrame(double f, int iter, double delta_factor, - Project* project_) -: wxFrame((wxWindow*) 0, wxID_ANY, "LOWESS Smoother Parameters", +LowessParamFrame::LowessParamFrame(double f, int iter, double delta_factor, Project* project_) +: wxFrame((wxWindow*) 0, wxID_ANY, _("LOWESS Smoother Parameters"), wxDefaultPosition, wxSize(400, -1), wxDEFAULT_FRAME_STYLE), LowessParamObservable(f, iter, delta_factor), project(project_) { - LOG_MSG("Entering LowessParamFrame::LowessParamFrame"); + wxLogMessage("Entering LowessParamFrame::LowessParamFrame"); wxPanel* panel = new wxPanel(this); panel->SetBackgroundColour(*wxWHITE); @@ -43,27 +43,27 @@ project(project_) wxButton* help_btn = new wxButton(panel, XRCID("ID_HELP_BTN"), - "Help", + _("Help"), wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT); wxButton* apply_btn = new wxButton(panel, XRCID("ID_APPLY_BTN"), - "Apply", + _("Apply"), wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT); wxButton* reset_defaults_btn = new wxButton(panel, XRCID("ID_RESET_DEFAULTS_BTN"), - "Reset", + _("Reset"), wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT); - wxStaticText* f_stat_t = new wxStaticText(panel, wxID_ANY, "Bandwidth:"); + wxStaticText* f_stat_t = new wxStaticText(panel, wxID_ANY, _("Bandwidth:")); f_text = new wxTextCtrl(panel, XRCID("ID_F_TEXT"), - wxString::Format("%.2f", GetF()), + wxString::Format("%f", GetF()), wxDefaultPosition, wxSize(100, -1), wxTE_PROCESS_ENTER); @@ -73,7 +73,7 @@ project(project_) Connect(XRCID("ID_F_TEXT"), wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler(LowessParamFrame::OnApplyBtn)); - wxStaticText* iter_stat_t = new wxStaticText(panel, wxID_ANY, "Iterations:"); + wxStaticText* iter_stat_t = new wxStaticText(panel, wxID_ANY, _("Iterations:")); iter_text = new wxTextCtrl(panel, XRCID("ID_ITER_TEXT"), wxString::Format("%d", GetIter()), @@ -88,7 +88,7 @@ project(project_) wxCommandEventHandler(LowessParamFrame::OnApplyBtn)); wxStaticText* delta_factor_stat_t = - new wxStaticText(panel, wxID_ANY, "Delta Factor:"); + new wxStaticText(panel, wxID_ANY, _("Delta Factor:")); delta_factor_text = new wxTextCtrl(panel, XRCID("ID_DELTA_FACTOR_TEXT"), wxString::Format("%.4f", GetDeltaFactor()), @@ -153,38 +153,38 @@ project(project_) Show(true); - LOG_MSG("Exiting LowessParamFrame::LowessParamFrame"); + wxLogMessage("Exiting LowessParamFrame::LowessParamFrame"); } LowessParamFrame::~LowessParamFrame() { - LOG_MSG("In LowessParamFrame::~LowessParamFrame"); + wxLogMessage("In LowessParamFrame::~LowessParamFrame"); notifyObserversOfClosing(); } void LowessParamFrame::OnHelpBtn(wxCommandEvent& ev) { - LOG_MSG("In LowessParamFrame::OnHelpBtn"); + wxLogMessage("In LowessParamFrame::OnHelpBtn"); WebViewHelpWin* win = new WebViewHelpWin(project, GetHelpPageHtml(), NULL, wxID_ANY, _("LOWESS Smoother Help")); } void LowessParamFrame::OnApplyBtn(wxCommandEvent& ev) { - LOG_MSG("In LowessParamFrame::OnApplyBtn"); + wxLogMessage("In LowessParamFrame::OnApplyBtn"); UpdateParamsFromFields(); notifyObservers(); } void LowessParamFrame::OnResetDefaultsBtn(wxCommandEvent& ev) { - LOG_MSG("In LowessParamFrame::OnResetDefaultsBtn"); + wxLogMessage("In LowessParamFrame::OnResetDefaultsBtn"); f = Lowess::default_f; iter = Lowess::default_iter; delta_factor = Lowess::default_delta_factor; - f_text->ChangeValue(wxString::Format("%.2f", GetF())); + f_text->ChangeValue(wxString::Format("%f", GetF())); iter_text->ChangeValue(wxString::Format("%d", GetIter())); - delta_factor_text->ChangeValue(wxString::Format("%.4f", GetDeltaFactor())); + delta_factor_text->ChangeValue(wxString::Format("%f", GetDeltaFactor())); OnApplyBtn(ev); } @@ -208,7 +208,7 @@ void LowessParamFrame::closeAndDeleteWhenEmpty() void LowessParamFrame::UpdateParamsFromFields() { - LOG_MSG("Entering LowessParamFrame::UpdateParamsFromFields"); + wxLogMessage("Entering LowessParamFrame::UpdateParamsFromFields"); Lowess temp_l(GetF(), GetIter(), GetDeltaFactor()); { wxString s = f_text->GetValue(); @@ -216,7 +216,7 @@ void LowessParamFrame::UpdateParamsFromFields() if (s.ToDouble(&v)) temp_l.SetF(v); f = temp_l.GetF(); - wxString sf = wxString::Format("%.2f", GetF()); + wxString sf = wxString::Format("%f", GetF()); f_text->ChangeValue(sf); } { @@ -237,7 +237,7 @@ void LowessParamFrame::UpdateParamsFromFields() wxString sf = wxString::Format("%.4f", GetDeltaFactor()); delta_factor_text->ChangeValue(sf); } - LOG_MSG("Exiting LowessParamFrame::UpdateParamsFromFields"); + wxLogMessage("Exiting LowessParamFrame::UpdateParamsFromFields"); } wxString LowessParamFrame::GetHelpPageHtml() const diff --git a/Explore/MLJCCoordinator.cpp b/Explore/MLJCCoordinator.cpp new file mode 100644 index 000000000..e8e2e65e1 --- /dev/null +++ b/Explore/MLJCCoordinator.cpp @@ -0,0 +1,688 @@ +/** + * GeoDa TM, Copyright (C) 2011-2015 by Luc Anselin - all rights reserved + * + * This file is part of GeoDa. + * + * GeoDa is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * GeoDa is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include +#include // for normal_distribution +#include +#include +#include +#include +#include +#include + +#include "../Algorithms/gpu_lisa.h" +#include "../DataViewer/TableInterface.h" +#include "../ShapeOperations/Randik.h" +#include "../ShapeOperations/WeightsManState.h" +#include "../VarCalc/WeightsManInterface.h" +#include "../logger.h" +#include "../Project.h" +#include "MLJCCoordinatorObserver.h" +#include "MLJCCoordinator.h" + +/////////////////////////////////////////////////////////////////////////////// +// +// JCWorkerThread +// +/////////////////////////////////////////////////////////////////////////////// +JCWorkerThread::JCWorkerThread(int t_, int obs_start_s, int obs_end_s, uint64_t seed_start_s, JCCoordinator* jc_coord_s, wxMutex* worker_list_mutex_s, wxCondition* worker_list_empty_cond_s, std::list *worker_list_s,int thread_id_s) +: wxThread(), +t(t_), +obs_start(obs_start_s), obs_end(obs_end_s), seed_start(seed_start_s), +jc_coord(jc_coord_s), +worker_list_mutex(worker_list_mutex_s), +worker_list_empty_cond(worker_list_empty_cond_s), +worker_list(worker_list_s), +thread_id(thread_id_s) +{ +} + +JCWorkerThread::~JCWorkerThread() +{ +} + +wxThread::ExitCode JCWorkerThread::Entry() +{ + LOG_MSG(wxString::Format("JCWorkerThread %d started", thread_id)); + // call work for assigned range of observations + jc_coord->CalcPseudoP_range(t, obs_start, obs_end, seed_start); + + wxMutexLocker lock(*worker_list_mutex); + // remove ourself from the list + worker_list->remove(this); + // if empty, signal on empty condition since only main thread + // should be waiting on this condition + if (worker_list->empty()) { + worker_list_empty_cond->Signal(); + } + + return NULL; +} + + +/////////////////////////////////////////////////////////////////////////////// +// +// JCCoordinator +// +/////////////////////////////////////////////////////////////////////////////// +JCCoordinator::JCCoordinator(boost::uuids::uuid weights_id, Project* project, const std::vector& var_info_s, const std::vector& col_ids) +: w_man_state(project->GetWManState()), +w_man_int(project->GetWManInt()), +w_id(weights_id), +num_obs(project->GetNumRecords()), +permutations(999), +var_info(var_info_s), +data(var_info_s.size()), +undef_data(var_info_s.size()), +last_seed_used(123456789), reuse_last_seed(true) +{ + reuse_last_seed = GdaConst::use_gda_user_seed; + if ( GdaConst::use_gda_user_seed) { + last_seed_used = GdaConst::gda_user_seed; + } + TableInterface* table_int = project->GetTableInt(); + for (int i=0; iGetColData(col_ids[i], data[i]); + table_int->GetColUndefined(col_ids[i], undef_data[i]); + } + num_vars = var_info.size(); + weight_name = w_man_int->GetLongDispName(w_id); + weights = w_man_int->GetGal(w_id); + SetSignificanceFilter(1); + + InitFromVarInfo(); + + w_man_state->registerObserver(this); +} + +JCCoordinator::~JCCoordinator() +{ + if (w_man_state) { + w_man_state->removeObserver(this); + w_man_state = NULL; + } + DeallocateVectors(); +} + +void JCCoordinator::DeallocateVectors() +{ + for (int i=0; igal; + // get undef_tms across multi-variables + for (int v=0; v& c_val) +{ + int t = 0; + double* p_val = sig_local_jc_vecs[t]; + const GalElement* W = Gal_vecs[t]->gal; + c_val.resize(num_obs); + + + for (int i=0; i undefs; + bool has_undef = false; + for (int i=0; iUpdate(undefs); + } else { + gw = weights; + } + GalElement* W = gw->gal; + Gal_vecs[t] = gw; + Gal_vecs_orig[t] = weights; + + for (int i=0; i local_t; + for (int v=0; v0) { // x_j = 1 + for (int j=0, sz=W[i].Size(); j0) { // x_i.z_i = 1 + for (int j=0, sz=W[i].Size(); j0) { // x_i.z_i = 1 + for (int j=0, sz=W[i].Size(); j local_t; + for (int v=0; vgal; + double* _sigLocal = sig_local_jc_vecs[t]; + + wxString exePath = GenUtils::GetBasemapCacheDir(); + wxString clPath = exePath + "localjc_kernel.cl"; + bool flag = gpu_localjoincount(clPath.mb_str(), num_obs, permutations, last_seed_used, num_vars, zz, local_jc, w, _sigLocal); + + delete[] values; + + if (!flag) { + wxMessageDialog dlg(NULL, "GeoDa can't configure GPU device. Default CPU solution will be used instead.", _("Error"), wxOK | wxICON_ERROR); + dlg.ShowModal(); + CalcPseudoP_threaded(t); + } + } + } + LOG_MSG(wxString::Format("JCCoordinator::GPU took %ld ms", sw_vd.Time())); +} + +void JCCoordinator::CalcPseudoP_threaded(int t) +{ + LOG_MSG("Entering JCCoordinator::CalcPseudoP_threaded"); + int nCPUs = GdaConst::gda_cpu_cores; + if (!GdaConst::gda_set_cpu_cores) + nCPUs = wxThread::GetCPUCount(); + + // mutext protects access to the worker_list + wxMutex worker_list_mutex; + // signals that worker_list is empty + wxCondition worker_list_empty_cond(worker_list_mutex); + worker_list_mutex.Lock(); // mutex should be initially locked + + // List of all the threads currently alive. As soon as the thread + // terminates, it removes itself from the list. + std::list worker_list; + + // divide up work according to number of observations + // and number of CPUs + int work_chunk = num_obs / nCPUs; + int obs_start = 0; + int obs_end = obs_start + work_chunk; + + bool is_thread_error = false; + int quotient = num_obs / nCPUs; + int remainder = num_obs % nCPUs; + int tot_threads = (quotient > 0) ? nCPUs : remainder; + + if (!reuse_last_seed) last_seed_used = time(0); + for (int i=0; iCreate() != wxTHREAD_NO_ERROR ) { + delete thread; + is_thread_error = true; + } else { + worker_list.push_front(thread); + } + } + if (is_thread_error) { + // fall back to single thread calculation mode + CalcPseudoP_range(t, 0, num_obs-1, last_seed_used); + } else { + std::list::iterator it; + for (it = worker_list.begin(); it != worker_list.end(); it++) { + (*it)->Run(); + } + + while (!worker_list.empty()) { + // wait until thread_list might be empty + worker_list_empty_cond.Wait(); + // We have been woken up. If this was not a false + // alarm (spurious signal), the loop will exit. + } + } + LOG_MSG("Exiting JCCoordinator::CalcPseudoP_threaded"); +} + +/** In the code that computes Gi and Gi*, we specifically checked for + self-neighbors and handled the situation appropriately. For the + permutation code, we will disallow self-neighbors. */ +void JCCoordinator::CalcPseudoP_range(int t, int obs_start, int obs_end, uint64_t seed_start) +{ + GeoDaSet workPermutation(num_obs); + + int max_rand = num_obs-1; + + GalElement* W = Gal_vecs[t]->gal; + int* zz = zz_vecs[t]; + double* local_jc = local_jc_vecs[t]; + std::vector& undefs = undef_tms[t]; + double* pseudo_p = sig_local_jc_vecs[t]; + + vector local_t; + for (int v=0; v 0) { + int countLarger = 0; + double permuted = 0; + + for (int perm=0; perm < permutations; perm++) { + int rand = 0; + while (rand < numNeighsI) { + // computing 'perfect' permutation of given size + double rng_val = Gda::ThomasWangHashDouble(seed_start++) * max_rand; + // round is needed to fix issue + //https://github.com/GeoDaCenter/geoda/issues/488 + int newRandom = (int) (rng_val < 0.0 ? ceil(rng_val - 0.5) : floor(rng_val + 0.5)); + + if (newRandom != i && + !workPermutation.Belongs(newRandom) && + undefs[newRandom] == false) + { + workPermutation.Push(newRandom); + rand++; + } + } + + double perm_jc = 0; + // use permutation to compute the lags + for (int j=0; j= local_jc[i]) countLarger++; + } + // pick the smallest + if (permutations-countLarger < countLarger) { + countLarger=permutations - countLarger; + } + pseudo_p[i] = (countLarger + 1.0)/(permutations+1.0); + } + } +} + +void JCCoordinator::SetSignificanceFilter(int filter_id) +{ + if (filter_id == -1) { + // user input cutoff + significance_filter = filter_id; + return; + } + // 0: >0.05 1: 0.05, 2: 0.01, 3: 0.001, 4: 0.0001 + if (filter_id < 1 || filter_id > 4) return; + significance_filter = filter_id; + if (filter_id == 1) significance_cutoff = 0.05; + if (filter_id == 2) significance_cutoff = 0.01; + if (filter_id == 3) significance_cutoff = 0.001; + if (filter_id == 4) significance_cutoff = 0.0001; +} + +void JCCoordinator::update(WeightsManState* o) +{ + weight_name = w_man_int->GetLongDispName(w_id); +} + +int JCCoordinator::numMustCloseToRemove(boost::uuids::uuid id) const +{ + return id == w_id ? observers.size() : 0; +} + +void JCCoordinator::closeObserver(boost::uuids::uuid id) +{ + if (numMustCloseToRemove(id) == 0) return; + std::list observers_cpy = observers; + for (std::list::iterator i=observers_cpy.begin(); + i != observers_cpy.end(); ++i) { + if (*i != 0) { + (*i)->closeObserver(this); + } + } +} + +void JCCoordinator::registerObserver(JCCoordinatorObserver* o) +{ + observers.push_front(o); +} + +void JCCoordinator::removeObserver(JCCoordinatorObserver* o) +{ + observers.remove(o); + if (observers.size() == 0) { + delete this; + } +} + +void JCCoordinator::notifyObservers() +{ + for (std::list::iterator it=observers.begin(); + it != observers.end(); ++it) { + (*it)->update(this); + } +} + diff --git a/Explore/MLJCCoordinator.h b/Explore/MLJCCoordinator.h new file mode 100644 index 000000000..9757239ab --- /dev/null +++ b/Explore/MLJCCoordinator.h @@ -0,0 +1,207 @@ +/** + * GeoDa TM, Copyright (C) 2011-2015 by Luc Anselin - all rights reserved + * + * This file is part of GeoDa. + * + * GeoDa is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * GeoDa is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + NOTE: JCCoordinator and GetisOrdMapNewView implement the + Observable/Observer interface. However, we have chosen not to define + a JCCoordinatorObserver interface for GetisOrdMapNewView to implement + because JCCoordinator needs to know more details about the + GetisOrdMapNewView instances that register with it. In particular, we only + allow at most 8 different GetisOrdMapNewView instances to be observers, and + each instance must be a different type according to the options enumerated + in GetisOrdMapNewView::GMapType. + */ + +#ifndef __GEODA_CENTER_MLJC_COORDINATOR_H__ +#define __GEODA_CENTER_MLJC_COORDINATOR_H__ + +#include +#include +#include +#include +#include +#include "../VarTools.h" +#include "../ShapeOperations/GalWeight.h" +#include "../ShapeOperations/WeightsManStateObserver.h" +#include "../ShapeOperations/OGRDataAdapter.h" + + +class JCCoordinatorObserver; +class JCCoordinator; +class Project; +class WeightsManState; +typedef boost::multi_array d_array_type; +typedef boost::multi_array b_array_type; + +class JCWorkerThread : public wxThread +{ +public: + JCWorkerThread(int t, + int obs_start, int obs_end, uint64_t seed_start, + JCCoordinator* jc_coord, + wxMutex* worker_list_mutex, + wxCondition* worker_list_empty_cond, + std::list *worker_list, + int thread_id); + + virtual ~JCWorkerThread(); + virtual void* Entry(); // thread execution starts here + + int t; + int obs_start; + int obs_end; + uint64_t seed_start; + int thread_id; + + JCCoordinator* jc_coord; + wxMutex* worker_list_mutex; + wxCondition* worker_list_empty_cond; + std::list *worker_list; +}; + +class JCCoordinator : public WeightsManStateObserver +{ +public: + JCCoordinator(boost::uuids::uuid weights_id, Project* project, + const std::vector& var_info, + const std::vector& col_ids); + virtual ~JCCoordinator(); + + bool IsOk() { return true; } + wxString GetErrorMessage() { return "Error Message"; } + + int significance_filter; // 0: >0.05 1: 0.05, 2: 0.01, 3: 0.001, 4: 0.0001 + double significance_cutoff; // either 0.05, 0.01, 0.001 or 0.0001 + void SetSignificanceFilter(int filter_id); + int GetSignificanceFilter() { return significance_filter; } + int permutations; // any number from 9 to 99999, 99 will be default + double bo; //Bonferroni bound + double fdr; //False Discovery Rate + double user_sig_cutoff; // user defined cutoff + + uint64_t GetLastUsedSeed() { return last_seed_used;} + + void SetLastUsedSeed(uint64_t seed) { + reuse_last_seed = true; + last_seed_used = seed; + // update global one + GdaConst::use_gda_user_seed = true; + OGRDataAdapter::GetInstance().AddEntry("use_gda_user_seed", "1"); + GdaConst::gda_user_seed = last_seed_used; + wxString val; + val << last_seed_used; + OGRDataAdapter::GetInstance().AddEntry("gda_user_seed", val); + } + + bool IsReuseLastSeed() { return reuse_last_seed; } + void SetReuseLastSeed(bool reuse) { + reuse_last_seed = reuse; + // update global one + GdaConst::use_gda_user_seed = reuse; + if (reuse) { + last_seed_used = GdaConst::gda_user_seed; + OGRDataAdapter::GetInstance().AddEntry("use_gda_user_seed", "1"); + } else { + OGRDataAdapter::GetInstance().AddEntry("use_gda_user_seed", "0"); + } + } + + /** Implementation of WeightsManStateObserver interface */ + virtual void update(WeightsManState* o); + virtual int numMustCloseToRemove(boost::uuids::uuid id) const; + virtual void closeObserver(boost::uuids::uuid id); + + vector > data_vecs; + vector > undef_tms; + vector zz_vecs; + vector local_jc_vecs; + vector sig_local_jc_vecs; + std::vector > num_neighbors; + + std::vector Gal_vecs; + std::vector Gal_vecs_orig; + + std::vector has_isolates; + std::vector has_undefined; + + boost::uuids::uuid w_id; + wxString weight_name; + + int num_vars; + int num_obs; // total # obs including neighborless obs + int num_time_vals; // number of valid time periods based on var_info + + // This variable should be empty for GStatMapCanvas + std::vector data; // data[variable][time][obs] + std::vector undef_data; // data[variable][time][obs] + + // All objects synchronize themselves from the following 6 variables. + int ref_var_index; + std::vector var_info; + bool is_any_time_variant; + bool is_any_sync_with_global_time; + std::vector map_valid; + std::vector map_error_message; + + + bool GetHasIsolates(int time) { return has_isolates[time]; } + bool GetHasUndefined(int time) { return has_undefined[time]; } + + void registerObserver(JCCoordinatorObserver* o); + void removeObserver(JCCoordinatorObserver* o); + void notifyObservers(); + + /** The array of registered observer objects. */ + std::list observers; + + void CalcPseudoP(); + void CalcPseudoP_range(int t, + int obs_start, + int obs_end, + uint64_t seed_start); + + void InitFromVarInfo(); + + void VarInfoAttributeChange(); + + void FillClusterCats(int canvas_time,std::vector& c_val); + +protected: + // The following ten are just temporary pointers into the corresponding + // space-time data arrays below + + + GalWeight* weights; + + + uint64_t last_seed_used; + bool reuse_last_seed; + + WeightsManState* w_man_state; + WeightsManInterface* w_man_int; + + void DeallocateVectors(); + void AllocateVectors(); + + void CalcPseudoP_threaded(int t); + + void CalcMultiLocalJoinCount(); +}; + +#endif diff --git a/DataViewer/DbfTable.cpp b/Explore/MLJCCoordinatorObserver.h similarity index 68% rename from DataViewer/DbfTable.cpp rename to Explore/MLJCCoordinatorObserver.h index 1040dc19c..2bc184003 100644 --- a/DataViewer/DbfTable.cpp +++ b/Explore/MLJCCoordinatorObserver.h @@ -17,5 +17,16 @@ * along with this program. If not, see . */ +#ifndef __GEODA_CENTER_MLJC_COORDINATOR_OBSERVER_H__ +#define __GEODA_CENTER_MLJC_COORDINATOR_OBSERVER_H__ +class JCCoordinator; // forward declaration +class JCCoordinatorObserver { +public: + virtual void update(JCCoordinator* o) = 0; + /** Request for the Observer to close itself */ + virtual void closeObserver(JCCoordinator* o) = 0; +}; + +#endif diff --git a/Explore/MLJCMapNewView.cpp b/Explore/MLJCMapNewView.cpp new file mode 100644 index 000000000..ca39f4cfb --- /dev/null +++ b/Explore/MLJCMapNewView.cpp @@ -0,0 +1,963 @@ +/** + * GeoDa TM, Copyright (C) 2011-2015 by Luc Anselin - all rights reserved + * + * This file is part of GeoDa. + * + * GeoDa is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * GeoDa is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include "MLJCMapNewView.h" + +#include +#include +#include +#include +#include +#include +#include "../DataViewer/TableInterface.h" +#include "../DataViewer/TimeState.h" +#include "../GeneralWxUtils.h" +#include "../GeoDa.h" +#include "../logger.h" +#include "../Project.h" +#include "../DialogTools/PermutationCounterDlg.h" +#include "../DialogTools/SaveToTableDlg.h" +#include "../DialogTools/VariableSettingsDlg.h" +#include "../DialogTools/RandomizationDlg.h" +#include "../VarCalc/WeightsManInterface.h" +#include "ConditionalClusterMapView.h" +#include "MLJCCoordinator.h" +#include "MLJCMapNewView.h" + +IMPLEMENT_CLASS(MLJCMapCanvas, MapCanvas) +BEGIN_EVENT_TABLE(MLJCMapCanvas, MapCanvas) + EVT_PAINT(TemplateCanvas::OnPaint) + EVT_ERASE_BACKGROUND(TemplateCanvas::OnEraseBackground) + EVT_MOUSE_EVENTS(TemplateCanvas::OnMouseEvent) + EVT_MOUSE_CAPTURE_LOST(TemplateCanvas::OnMouseCaptureLostEvent) +END_EVENT_TABLE() + + +MLJCMapCanvas::MLJCMapCanvas(wxWindow *parent, TemplateFrame* t_frame, bool is_clust_p, Project* project, JCCoordinator* gs_coordinator, const wxPoint& pos, const wxSize& size) +: MapCanvas(parent, t_frame, project, std::vector(0), std::vector(0), CatClassification::no_theme, no_smoothing, 1, boost::uuids::nil_uuid(), pos, size), +gs_coord(gs_coordinator), is_clust(is_clust_p) +{ + LOG_MSG("Entering MLJCMapCanvas::MLJCMapCanvas"); + + str_sig = _("Not Significant"); + str_low = _("No Colocation"); + str_med = _("Has Colocation"); + str_high = _("Colocation Cluster"); + str_undefined = _("Undefined"); + str_neighborless = _("Neighborless"); + str_p005 = "p = 0.05"; + str_p001 = "p = 0.01"; + str_p0001 = "p = 0.001"; + str_p00001 ="p = 0.0001"; + + SetPredefinedColor(str_sig, wxColour(240, 240, 240)); + SetPredefinedColor(str_high, wxColour(255, 0, 0)); + SetPredefinedColor(str_med, wxColour(0, 255, 0)); + SetPredefinedColor(str_low, wxColour(0, 0, 255)); + SetPredefinedColor(str_undefined, wxColour(70, 70, 70)); + SetPredefinedColor(str_neighborless, wxColour(140, 140, 140)); + SetPredefinedColor(str_p005, wxColour(75, 255, 80)); + SetPredefinedColor(str_p001, wxColour(6, 196, 11)); + SetPredefinedColor(str_p0001, wxColour(3, 116, 6)); + SetPredefinedColor(str_p00001, wxColour(1, 70, 3)); + + if (is_clust) { + cat_classif_def.cat_classif_type = CatClassification::local_join_count_categories; + } else { + cat_classif_def.cat_classif_type = CatClassification::local_join_count_significance; + } + + // must set var_info times from JCCoordinator initially + var_info = gs_coord->var_info; + template_frame->ClearAllGroupDependencies(); + for (int t=0, sz=var_info.size(); tAddGroupDependancy(var_info[t].name); + } + CreateAndUpdateCategories(); + UpdateStatusBar(); + LOG_MSG("Exiting MLJCMapCanvas::MLJCMapCanvas"); +} + +MLJCMapCanvas::~MLJCMapCanvas() +{ + LOG_MSG("In MLJCMapCanvas::~MLJCMapCanvas"); +} + +void MLJCMapCanvas::DisplayRightClickMenu(const wxPoint& pos) +{ + LOG_MSG("Entering MLJCMapCanvas::DisplayRightClickMenu"); + // Workaround for right-click not changing window focus in OSX / wxW 3.0 + wxActivateEvent ae(wxEVT_NULL, true, 0, wxActivateEvent::Reason_Mouse); + ((MLJCMapFrame*) template_frame)->OnActivate(ae); + + wxMenu* optMenu = wxXmlResource::Get()-> + LoadMenu("ID_LOCALJOINCOUNT_NEW_VIEW_MENU_OPTIONS"); + AddTimeVariantOptionsToMenu(optMenu); + SetCheckMarks(optMenu); + + template_frame->UpdateContextMenuItems(optMenu); + template_frame->PopupMenu(optMenu, pos + GetPosition()); + template_frame->UpdateOptionMenuItems(); + LOG_MSG("Exiting MLJCMapCanvas::DisplayRightClickMenu"); +} + +wxString MLJCMapCanvas::GetCanvasTitle() +{ + wxString new_title; + + new_title << _("Local Join Count "); + + new_title << (is_clust ? "Cluster" : "Significance") << " Map "; + new_title << "(" << gs_coord->weight_name << "): "; + for (int i=0; inum_vars; i++) { + new_title << GetNameWithTime(i); + if (i < gs_coord->num_vars-1) { + new_title << ","; + } + } + new_title << wxString::Format(", pseudo p (%d perm)", gs_coord->permutations); + + return new_title; +} + +wxString MLJCMapCanvas::GetVariableNames() +{ + wxString new_title; + for (int i=0; inum_vars; i++) { + new_title << GetNameWithTime(i); + if (i < gs_coord->num_vars-1) { + new_title << ", "; + } + } + return new_title; +} + +/** This method definition is empty. It is here to override any call + to the parent-class method since smoothing and theme changes are not + supported by MLJC maps */ +bool MLJCMapCanvas::ChangeMapType(CatClassification::CatClassifType new_theme, SmoothingType new_smoothing) +{ + LOG_MSG("In MLJCMapCanvas::ChangeMapType"); + return false; +} + +void MLJCMapCanvas::SetCheckMarks(wxMenu* menu) +{ + // Update the checkmarks and enable/disable state for the + // following menu items if they were specified for this particular + // view in the xrc file. Items that cannot be enable/disabled, + // or are not checkable do not appear. + MapCanvas::SetCheckMarks(menu); + + int sig_filter = ((MLJCMapFrame*) template_frame)->GetJCCoordinator()->GetSignificanceFilter(); + + GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_SIGNIFICANCE_FILTER_05"), + sig_filter == 1); + GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_SIGNIFICANCE_FILTER_01"), + sig_filter == 2); + GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_SIGNIFICANCE_FILTER_001"), + sig_filter == 3); + GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_SIGNIFICANCE_FILTER_0001"), + sig_filter == 4); + GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_SIGNIFICANCE_FILTER_SETUP"), + sig_filter == -1); + + GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_USE_SPECIFIED_SEED"), + gs_coord->IsReuseLastSeed()); +} + +void MLJCMapCanvas::TimeChange() +{ + LOG_MSG("Entering MLJCMapCanvas::TimeChange"); + if (!is_any_sync_with_global_time) return; + + int cts = project->GetTimeState()->GetCurrTime(); + int ref_time = var_info[ref_var_index].time; + int ref_time_min = var_info[ref_var_index].time_min; + int ref_time_max = var_info[ref_var_index].time_max; + + if ((cts == ref_time) || + (cts > ref_time_max && ref_time == ref_time_max) || + (cts < ref_time_min && ref_time == ref_time_min)) + { + return; + } + if (cts > ref_time_max) { + ref_time = ref_time_max; + + } else if (cts < ref_time_min) { + ref_time = ref_time_min; + + } else { + ref_time = cts; + } + for (int i=0; i cluster; + for (int t=0; tGetHasIsolates(t)) { + num_cats++; + } + if (gs_coord->GetHasUndefined(t)) { + num_cats++; + } + + if (is_clust) { + num_cats += 4; // 0 not sig 1 no loc 2 has loc 3 loc cluster + + } else { + int set_perm = gs_coord->permutations; + stop_sig = 1.0 / (1.0 + set_perm); + double sig_cutoff = gs_coord->significance_cutoff; + + if (gs_coord->GetSignificanceFilter() < 0) { + // user specified cutoff + num_cats += 2; + } else { + num_cats += 6 - gs_coord->GetSignificanceFilter(); + + if ( sig_cutoff >= 0.0001 && stop_sig > 0.0001) { + num_cats -= 1; + } + if ( sig_cutoff >= 0.001 && stop_sig > 0.001 ) { + num_cats -= 1; + } + if ( sig_cutoff >= 0.01 && stop_sig > 0.01 ) { + num_cats -= 1; + } + } + } + cat_data.CreateCategoriesAtCanvasTm(num_cats, t); + + if (is_clust) { + cat_data.SetCategoryLabel(t, 0, str_sig); + cat_data.SetCategoryColor(t, 0, lbl_color_dict[str_sig]); + cat_data.SetCategoryLabel(t, 1, str_low); + cat_data.SetCategoryColor(t, 1, lbl_color_dict[str_low]); + cat_data.SetCategoryLabel(t, 2, str_med); + cat_data.SetCategoryColor(t, 2, lbl_color_dict[str_med]); + cat_data.SetCategoryLabel(t, 3, str_high); + cat_data.SetCategoryColor(t, 3, lbl_color_dict[str_high]); + + if (gs_coord->GetHasIsolates(t) && gs_coord->GetHasUndefined(t)) { + isolates_cat = 4; + undefined_cat = 5; + } else if (gs_coord->GetHasUndefined(t)) { + undefined_cat = 4; + } else if (gs_coord->GetHasIsolates(t)) { + isolates_cat = 4; + } + + } else { + cat_data.SetCategoryLabel(t, 0, str_sig); + cat_data.SetCategoryColor(t, 0, lbl_color_dict[str_sig]); + + if (gs_coord->GetSignificanceFilter() < 0) { + // user specified cutoff + wxString lbl = wxString::Format("p = %g", gs_coord->significance_cutoff); + cat_data.SetCategoryLabel(t, 1, lbl); + cat_data.SetCategoryColor(t, 1, wxColour(3, 116, 6)); + + if (gs_coord->GetHasIsolates(t) && + gs_coord->GetHasUndefined(t)) + { + isolates_cat = 2; + undefined_cat = 3; + } else if (gs_coord->GetHasUndefined(t)) { + undefined_cat = 2; + } else if (gs_coord->GetHasIsolates(t)) { + isolates_cat = 2; + } + + } else { + int s_f = gs_coord->GetSignificanceFilter(); + int set_perm = gs_coord->permutations; + stop_sig = 1.0 / (1.0 + set_perm); + + wxString def_cats[4] = {str_p005, str_p001, str_p0001, str_p00001}; + double def_cutoffs[4] = {0.05, 0.01, 0.001, 0.0001}; + + int cat_idx = 1; + for (int j=s_f-1; j < 4; j++) { + if (def_cutoffs[j] >= stop_sig) { + cat_data.SetCategoryLabel(t, cat_idx, def_cats[j]); + cat_data.SetCategoryColor(t, cat_idx++, lbl_color_dict[def_cats[j]]); + } + } + if (gs_coord->GetHasIsolates(t) && + gs_coord->GetHasUndefined(t)) { + isolates_cat = cat_idx++; + undefined_cat = cat_idx++; + + } else if (gs_coord->GetHasUndefined(t)) { + undefined_cat = cat_idx++; + + } else if (gs_coord->GetHasIsolates(t)) { + isolates_cat = cat_idx++; + } + } + } + + if (undefined_cat != -1) { + cat_data.SetCategoryLabel(t, undefined_cat, str_undefined); + cat_data.SetCategoryColor(t, undefined_cat, lbl_color_dict[str_undefined]); + } + if (isolates_cat != -1) { + cat_data.SetCategoryLabel(t, isolates_cat, str_neighborless); + cat_data.SetCategoryColor(t, isolates_cat, lbl_color_dict[str_neighborless]); + } + + gs_coord->FillClusterCats(t, cluster); + + if (is_clust) { + for (int i=0, iend=gs_coord->num_obs; isig_local_jc_vecs[t]; + + if (gs_coord->GetSignificanceFilter() < 0) { + // user specified cutoff + int s_f = 1; + double sig_cutoff = gs_coord->significance_cutoff; + for (int i=0, iend=gs_coord->num_obs; iGetSignificanceFilter(); + for (int i=0, iend=gs_coord->num_obs; iGetStatusBar(); + } + if (!sb) + return; + wxString s; + s << _("#obs=") << project->GetNumRecords() <<" "; + + if ( highlight_state->GetTotalHighlighted() > 0) { + // for highlight from other windows + s << _("#selected=") << highlight_state->GetTotalHighlighted()<< " "; + } + if (mousemode == select && selectstate == start) { + if (total_hover_obs >= 1) { + s << _("#hover obs ") << hover_obs[0]+1; + } + if (total_hover_obs >= 2) { + s << ", "; + s << _("obs ") << hover_obs[1]+1; + } + if (total_hover_obs >= 3) { + s << ", "; + s << _("obs ") << hover_obs[2]+1; + } + if (total_hover_obs >= 4) { + s << ", ..."; + } + } + if (is_clust && gs_coord) { + double p_val = gs_coord->significance_cutoff; + wxString inf_str = wxString::Format(" p <= %g", p_val); + s << inf_str; + } + sb->SetStatusText(s); +} + +void MLJCMapCanvas::TimeSyncVariableToggle(int var_index) +{ + LOG_MSG("In MLJCMapCanvas::TimeSyncVariableToggle"); + gs_coord->var_info[var_index].sync_with_global_time = + !gs_coord->var_info[var_index].sync_with_global_time; + for (int i=0; ivar_info[i].time = var_info[i].time; + } + gs_coord->VarInfoAttributeChange(); + gs_coord->InitFromVarInfo(); + gs_coord->notifyObservers(); +} + +/** Copy everything in var_info except for current time field for each + variable. Also copy over is_any_time_variant, is_any_sync_with_global_time, + ref_var_index, num_time_vales, map_valid and map_error_message */ +void MLJCMapCanvas::SyncVarInfoFromCoordinator() +{ + std::vectormy_times(var_info.size()); + for (int t=0; tvar_info; + template_frame->ClearAllGroupDependencies(); + for (int t=0; tAddGroupDependancy(var_info[t].name); + } + is_any_time_variant = gs_coord->is_any_time_variant; + is_any_sync_with_global_time = gs_coord->is_any_sync_with_global_time; + ref_var_index = gs_coord->ref_var_index; + num_time_vals = gs_coord->num_time_vals; + map_valid = gs_coord->map_valid; + map_error_message = gs_coord->map_error_message; +} + +IMPLEMENT_CLASS(MLJCMapFrame, MapFrame) + BEGIN_EVENT_TABLE(MLJCMapFrame, MapFrame) + EVT_ACTIVATE(MLJCMapFrame::OnActivate) +END_EVENT_TABLE() + +MLJCMapFrame::MLJCMapFrame(wxFrame *parent, Project* project, JCCoordinator* gs_coordinator, bool isClusterMap, const wxPoint& pos, const wxSize& size, const long style) +: MapFrame(parent, project, pos, size, style), +gs_coord(gs_coordinator), +is_clust(isClusterMap) +{ + wxLogMessage("Entering MLJCMapFrame::MLJCMapFrame"); + + no_update_weights = true; + int width, height; + GetClientSize(&width, &height); + + DisplayStatusBar(true); + + wxSplitterWindow* splitter_win = new wxSplitterWindow(this,-1, + wxDefaultPosition, wxDefaultSize, + wxSP_3D|wxSP_LIVE_UPDATE|wxCLIP_CHILDREN); + splitter_win->SetMinimumPaneSize(10); + + wxPanel* rpanel = new wxPanel(splitter_win); + template_canvas = new MLJCMapCanvas(rpanel, this, is_clust, project, gs_coordinator); + template_canvas->SetScrollRate(1,1); + wxBoxSizer* rbox = new wxBoxSizer(wxVERTICAL); + rbox->Add(template_canvas, 1, wxEXPAND); + rpanel->SetSizer(rbox); + + WeightsManInterface* w_man_int = project->GetWManInt(); + ((MapCanvas*) template_canvas)->SetWeightsId(w_man_int->GetDefault()); + + + wxPanel* lpanel = new wxPanel(splitter_win); + template_legend = new MapNewLegend(lpanel, template_canvas, wxPoint(0,0), wxSize(0,0)); + wxBoxSizer* lbox = new wxBoxSizer(wxVERTICAL); + template_legend->GetContainingSizer()->Detach(template_legend); + lbox->Add(template_legend, 1, wxEXPAND); + lpanel->SetSizer(lbox); + + splitter_win->SplitVertically(lpanel, rpanel, GdaConst::map_default_legend_width); + + + wxPanel* toolbar_panel = new wxPanel(this,-1, wxDefaultPosition); + wxBoxSizer* toolbar_sizer= new wxBoxSizer(wxVERTICAL); + toolbar = wxXmlResource::Get()->LoadToolBar(toolbar_panel, "ToolBar_MAP"); + SetupToolbar(); + toolbar_sizer->Add(toolbar, 0, wxEXPAND|wxALL); + toolbar_panel->SetSizerAndFit(toolbar_sizer); + + wxBoxSizer* sizer = new wxBoxSizer(wxVERTICAL); + sizer->Add(toolbar_panel, 0, wxEXPAND|wxALL); + sizer->Add(splitter_win, 1, wxEXPAND|wxALL); + SetSizer(sizer); + SetAutoLayout(true); + + gs_coord->registerObserver(this); + + SetTitle(template_canvas->GetCanvasTitle()); + Show(true); + wxLogMessage("Exiting MLJCMapFrame::MLJCMapFrame"); +} + +MLJCMapFrame::~MLJCMapFrame() +{ + wxLogMessage("In MLJCMapFrame::~MLJCMapFrame"); + if (gs_coord) { + gs_coord->removeObserver(this); + gs_coord = 0; + } +} + +void MLJCMapFrame::OnActivate(wxActivateEvent& event) +{ + LOG_MSG("In MLJCMapFrame::OnActivate"); + if (event.GetActive()) { + RegisterAsActive("MLJCMapFrame", GetTitle()); + } + if ( event.GetActive() && template_canvas ) template_canvas->SetFocus(); +} + +void MLJCMapFrame::MapMenus() +{ + LOG_MSG("In MLJCMapFrame::MapMenus"); + wxMenuBar* mb = GdaFrame::GetGdaFrame()->GetMenuBar(); + // Map Options Menus + wxMenu* optMenu = wxXmlResource::Get()->LoadMenu("ID_LOCALJOINCOUNT_NEW_VIEW_MENU_OPTIONS"); + ((MapCanvas*) template_canvas)->AddTimeVariantOptionsToMenu(optMenu); + ((MapCanvas*) template_canvas)->SetCheckMarks(optMenu); + GeneralWxUtils::ReplaceMenu(mb, _("Options"), optMenu); + UpdateOptionMenuItems(); +} + +void MLJCMapFrame::UpdateOptionMenuItems() +{ + TemplateFrame::UpdateOptionMenuItems(); // set common items first + wxMenuBar* mb = GdaFrame::GetGdaFrame()->GetMenuBar(); + int menu = mb->FindMenu(_("Options")); + if (menu == wxNOT_FOUND) { + LOG_MSG("MLJCMapFrame::UpdateOptionMenuItems: Options menu not found"); + } else { + ((MLJCMapCanvas*) template_canvas)->SetCheckMarks(mb->GetMenu(menu)); + } +} + +void MLJCMapFrame::UpdateContextMenuItems(wxMenu* menu) +{ + // Update the checkmarks and enable/disable state for the + // following menu items if they were specified for this particular + // view in the xrc file. Items that cannot be enable/disabled, + // or are not checkable do not appear. + + TemplateFrame::UpdateContextMenuItems(menu); // set common items +} + +void MLJCMapFrame::RanXPer(int permutation) +{ + if (permutation < 9) permutation = 9; + if (permutation > 99999) permutation = 99999; + gs_coord->permutations = permutation; + gs_coord->CalcPseudoP(); + gs_coord->notifyObservers(); +} + +void MLJCMapFrame::OnRan99Per(wxCommandEvent& event) +{ + RanXPer(99); +} + +void MLJCMapFrame::OnRan199Per(wxCommandEvent& event) +{ + RanXPer(199); +} + +void MLJCMapFrame::OnRan499Per(wxCommandEvent& event) +{ + RanXPer(499); +} + +void MLJCMapFrame::OnRan999Per(wxCommandEvent& event) +{ + RanXPer(999); +} + +void MLJCMapFrame::OnRanOtherPer(wxCommandEvent& event) +{ + PermutationCounterDlg dlg(this); + if (dlg.ShowModal() == wxID_OK) { + long num; + wxString input = dlg.m_number->GetValue(); + + wxLogMessage(input); + + input.ToLong(&num); + RanXPer(num); + } +} + +void MLJCMapFrame::OnUseSpecifiedSeed(wxCommandEvent& event) +{ + gs_coord->SetReuseLastSeed(!gs_coord->IsReuseLastSeed()); +} + +void MLJCMapFrame::OnSpecifySeedDlg(wxCommandEvent& event) +{ + uint64_t last_seed = gs_coord->GetLastUsedSeed(); + wxString m; + m << "The last seed used by the pseudo random\nnumber "; + m << "generator was " << last_seed << ".\n"; + m << "Enter a seed value to use between\n0 and "; + m << std::numeric_limits::max() << "."; + long long unsigned int val; + wxString dlg_val; + wxString cur_val; + cur_val << last_seed; + + wxTextEntryDialog dlg(NULL, m, "\nEnter a seed value", cur_val); + if (dlg.ShowModal() != wxID_OK) return; + dlg_val = dlg.GetValue(); + + wxLogMessage(dlg_val); + + dlg_val.Trim(true); + dlg_val.Trim(false); + if (dlg_val.IsEmpty()) return; + if (dlg_val.ToULongLong(&val)) { + if (!gs_coord->IsReuseLastSeed()) gs_coord->SetLastUsedSeed(true); + uint64_t new_seed_val = val; + gs_coord->SetLastUsedSeed(new_seed_val); + } else { + wxString m; + m << "\"" << dlg_val << "\" is not a valid seed. Seed unchanged."; + wxMessageDialog dlg(NULL, m, _("Error"), wxOK | wxICON_ERROR); + dlg.ShowModal(); + } +} + +void MLJCMapFrame::SetSigFilterX(int filter) +{ + if (filter == gs_coord->GetSignificanceFilter()) + return; + gs_coord->SetSignificanceFilter(filter); + gs_coord->notifyObservers(); + UpdateOptionMenuItems(); +} + +void MLJCMapFrame::OnSigFilter05(wxCommandEvent& event) +{ + SetSigFilterX(1); +} + +void MLJCMapFrame::OnSigFilter01(wxCommandEvent& event) +{ + SetSigFilterX(2); +} + +void MLJCMapFrame::OnSigFilter001(wxCommandEvent& event) +{ + SetSigFilterX(3); +} + +void MLJCMapFrame::OnSigFilter0001(wxCommandEvent& event) +{ + SetSigFilterX(4); +} + +void MLJCMapFrame::OnSigFilterSetup(wxCommandEvent& event) +{ + MLJCMapCanvas* lc = (MLJCMapCanvas*)template_canvas; + int t = template_canvas->cat_data.GetCurrentCanvasTmStep(); + double* p_val_t = gs_coord->sig_local_jc_vecs[t]; + int n = gs_coord->num_obs; + + wxString ttl = _("Inference Settings"); + ttl << " (" << gs_coord->permutations << " perm)"; + + double user_sig = gs_coord->significance_cutoff; + if (gs_coord->GetSignificanceFilter()<0) + user_sig = gs_coord->user_sig_cutoff; + + int new_n = 0; + for (int i=0; inum_obs; i++) { + if (gs_coord->data[0][t][i] == 1) { + new_n += 1; + } + } + int j= 0; + double* p_val = new double[new_n]; + for (int i=0; inum_obs; i++) { + if (gs_coord->data[0][t][i] == 1) { + p_val[j++] = p_val_t[i]; + } + } + InferenceSettingsDlg dlg(this, user_sig, p_val, new_n, ttl); + if (dlg.ShowModal() == wxID_OK) { + gs_coord->SetSignificanceFilter(-1); + gs_coord->significance_cutoff = dlg.GetAlphaLevel(); + gs_coord->user_sig_cutoff = dlg.GetUserInput(); + gs_coord->notifyObservers(); + gs_coord->bo = dlg.GetBO(); + gs_coord->fdr = dlg.GetFDR(); + UpdateOptionMenuItems(); + } + delete[] p_val; +} + + + +void MLJCMapFrame::OnSaveMLJC(wxCommandEvent& event) +{ + int t = 0;//template_canvas->cat_data.GetCurrentCanvasTmStep(); + wxString title = _("Save Results: Local Join Count stats, "); + title += wxString::Format("pseudo p (%d perm), ", gs_coord->permutations); + + int num_obs = gs_coord->num_obs; + std::vector p_undefs(num_obs, false); + + std::vector c_val; + gs_coord->FillClusterCats(t, c_val); + + wxString c_label = "Cluster Category"; + wxString c_field_default = "C_ID"; + + double* jc_t = gs_coord->local_jc_vecs[t]; + std::vector jc_val(num_obs); + for (int i=0; isig_local_jc_vecs[t]; + std::vector pp_val(num_obs); + for (int i=0; i data(num_data); + std::vector undefs = gs_coord->undef_tms[t]; + + int data_i = 0; + + data[data_i].l_val = &jc_val; + data[data_i].label = jc_label; + data[data_i].field_default = jc_field_default; + data[data_i].type = GdaConst::long64_type; + data[data_i].undefined = &undefs; + data_i++; + + data[data_i].l_val = &gs_coord->num_neighbors[t]; + data[data_i].label = "Number of Neighbors"; + data[data_i].field_default = "NN"; + data[data_i].type = GdaConst::long64_type; + data[data_i].undefined = &undefs; + data_i++; + + data[data_i].d_val = &pp_val; + data[data_i].label = pp_label; + data[data_i].field_default = pp_field_default; + data[data_i].type = GdaConst::double_type; + data[data_i].undefined = &p_undefs; + data_i++; + + SaveToTableDlg dlg(project, this, data, title, + wxDefaultPosition, wxSize(400,400)); + dlg.ShowModal(); +} + +void MLJCMapFrame::CoreSelectHelper(const std::vector& elem) +{ + HighlightState* highlight_state = project->GetHighlightState(); + std::vector& hs = highlight_state->GetHighlight(); + bool selection_changed = false; + + for (int i=0; inum_obs; i++) { + if (!hs[i] && elem[i]) { + hs[i] = true; + selection_changed = true; + } else if (hs[i] && !elem[i]) { + hs[i] = false; + selection_changed = true; + } + } + if (selection_changed ) { + highlight_state->SetEventType(HLStateInt::delta); + highlight_state->notifyObservers(); + } +} + +void MLJCMapFrame::OnSelectCores(wxCommandEvent& event) +{ + wxLogMessage("Entering MLJCMapFrame::OnSelectCores"); + + std::vector elem(gs_coord->num_obs, false); + int ts = template_canvas->cat_data.GetCurrentCanvasTmStep(); + std::vector c_val; + gs_coord->FillClusterCats(ts, c_val); + + // add all cores to elem list. + for (int i=0; inum_obs; i++) { + if (c_val[i] == 1 || c_val[i] == 2) elem[i] = true; + } + CoreSelectHelper(elem); + + wxLogMessage("Exiting MLJCMapFrame::OnSelectCores"); +} + +void MLJCMapFrame::OnSelectNeighborsOfCores(wxCommandEvent& event) +{ + wxLogMessage("Entering MLJCMapFrame::OnSelectNeighborsOfCores"); + + std::vector elem(gs_coord->num_obs, false); + int ts = template_canvas->cat_data.GetCurrentCanvasTmStep(); + std::vector c_val; + gs_coord->FillClusterCats(ts, c_val); + + // add all cores and neighbors of cores to elem list + for (int i=0; inum_obs; i++) { + if (c_val[i] == 1 || c_val[i] == 2) { + elem[i] = true; + const GalElement& e = gs_coord->Gal_vecs_orig[ts]->gal[i]; + for (int j=0, jend=e.Size(); jnum_obs; i++) { + if (c_val[i] == 1 || c_val[i] == 2) { + elem[i] = false; + } + } + CoreSelectHelper(elem); + + wxLogMessage("Exiting MLJCMapFrame::OnSelectNeighborsOfCores"); +} + +void MLJCMapFrame::OnSelectCoresAndNeighbors(wxCommandEvent& event) +{ + wxLogMessage("Entering MLJCMapFrame::OnSelectCoresAndNeighbors"); + + std::vector elem(gs_coord->num_obs, false); + int ts = template_canvas->cat_data.GetCurrentCanvasTmStep(); + std::vector c_val; + gs_coord->FillClusterCats(ts, c_val); + + // add all cores and neighbors of cores to elem list + for (int i=0; inum_obs; i++) { + if (c_val[i] == 1 || c_val[i] == 2) { + elem[i] = true; + const GalElement& e = gs_coord->Gal_vecs_orig[ts]->gal[i]; + for (int j=0, jend=e.Size(); jGetCanvasTitle(); + //ConditionalClusterMapFrame* subframe = new ConditionalClusterMapFrame(this, project, dlg.var_info, dlg.col_ids, gs_coord); +} + +/** Called by JCCoordinator to notify that state has changed. State changes + can include: + - variable sync change and therefore all Gi categories have changed + - significance level has changed and therefore categories have changed + - new randomization for p-vals and therefore categories have changed */ +void MLJCMapFrame::update(JCCoordinator* o) +{ + MLJCMapCanvas* lc = (MLJCMapCanvas*) template_canvas; + lc->SyncVarInfoFromCoordinator(); + lc->CreateAndUpdateCategories(); + if (template_legend) template_legend->Recreate(); + SetTitle(lc->GetCanvasTitle()); + lc->Refresh(); + lc->UpdateStatusBar(); +} + +void MLJCMapFrame::closeObserver(JCCoordinator* o) +{ + wxLogMessage("In MLJCMapFrame::closeObserver(JCCoordinator*)"); + if (gs_coord) { + gs_coord->removeObserver(this); + gs_coord = 0; + } + Close(true); +} diff --git a/Explore/MLJCMapNewView.h b/Explore/MLJCMapNewView.h new file mode 100644 index 000000000..4d61a34af --- /dev/null +++ b/Explore/MLJCMapNewView.h @@ -0,0 +1,140 @@ +/** + * GeoDa TM, Copyright (C) 2011-2015 by Luc Anselin - all rights reserved + * + * This file is part of GeoDa. + * + * GeoDa is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * GeoDa is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#ifndef __GEODA_CENTER_MLJC_MAP_NEW_VIEW_H__ +#define __GEODA_CENTER_MLJC_MAP_NEW_VIEW_H__ + +#include +#include "../GdaConst.h" +#include "MapNewView.h" +#include "MLJCCoordinatorObserver.h" + +class MapCanvas; +class MapFrame; +class JCCoordinator; +class MLJCMapFrame; +class MLJCMapCanvas; + +class MLJCMapCanvas : public MapCanvas +{ + DECLARE_CLASS(MLJCMapCanvas) +public: + MLJCMapCanvas(wxWindow *parent, + TemplateFrame* t_frame, + bool is_clust, + Project* project, + JCCoordinator* gs_coordinator, + const wxPoint& pos = wxDefaultPosition, + const wxSize& size = wxDefaultSize); + virtual ~MLJCMapCanvas(); + virtual void DisplayRightClickMenu(const wxPoint& pos); + virtual wxString GetCanvasTitle(); + virtual wxString GetVariableNames(); + virtual bool ChangeMapType(CatClassification::CatClassifType new_map_theme, + SmoothingType new_map_smoothing); + virtual void SetCheckMarks(wxMenu* menu); + virtual void TimeChange(); + void SyncVarInfoFromCoordinator(); + virtual void CreateAndUpdateCategories(); + virtual void TimeSyncVariableToggle(int var_index); + virtual void UpdateStatusBar(); + virtual void SetWeightsId(boost::uuids::uuid id) { weights_id = id; } + + double bo; + double fdr; + +protected: + JCCoordinator* gs_coord; + bool is_clust; // true = cluster map, false = significance map + + wxString str_sig; + wxString str_high; + wxString str_med; + wxString str_low; + wxString str_undefined; + wxString str_neighborless; + wxString str_p005; + wxString str_p001; + wxString str_p0001; + wxString str_p00001; + + DECLARE_EVENT_TABLE() +}; + +class MLJCMapFrame : public MapFrame, public JCCoordinatorObserver +{ + DECLARE_CLASS(MLJCMapFrame) +public: + + MLJCMapFrame(wxFrame *parent, Project* project, + JCCoordinator* gs_coordinator, + bool isClusterMap, + const wxPoint& pos = wxDefaultPosition, + const wxSize& size = GdaConst::map_default_size, + const long style = wxDEFAULT_FRAME_STYLE); + virtual ~MLJCMapFrame(); + + void OnActivate(wxActivateEvent& event); + virtual void MapMenus(); + virtual void UpdateOptionMenuItems(); + virtual void UpdateContextMenuItems(wxMenu* menu); + virtual void update(WeightsManState* o){} + + void RanXPer(int permutation); + void OnRan99Per(wxCommandEvent& event); + void OnRan199Per(wxCommandEvent& event); + void OnRan499Per(wxCommandEvent& event); + void OnRan999Per(wxCommandEvent& event); + void OnRanOtherPer(wxCommandEvent& event); + + void OnUseSpecifiedSeed(wxCommandEvent& event); + void OnSpecifySeedDlg(wxCommandEvent& event); + + void SetSigFilterX(int filter); + void OnSigFilter05(wxCommandEvent& event); + void OnSigFilter01(wxCommandEvent& event); + void OnSigFilter001(wxCommandEvent& event); + void OnSigFilter0001(wxCommandEvent& event); + void OnSigFilterSetup(wxCommandEvent& event); + + void OnSaveMLJC(wxCommandEvent& event); + + void OnSelectCores(wxCommandEvent& event); + void OnSelectNeighborsOfCores(wxCommandEvent& event); + void OnSelectCoresAndNeighbors(wxCommandEvent& event); + + void OnShowAsConditionalMap(wxCommandEvent& event); + + virtual void update(JCCoordinator* o); + /** Request for the Observer to close itself */ + virtual void closeObserver(JCCoordinator* o); + + + JCCoordinator* GetJCCoordinator() { return gs_coord; } + +protected: + void CoreSelectHelper(const std::vector& elem); + JCCoordinator* gs_coord; + bool is_clust; // true = cluster map, false = significance map + + DECLARE_EVENT_TABLE() +}; + + +#endif diff --git a/Explore/MapLayer.cpp b/Explore/MapLayer.cpp new file mode 100644 index 000000000..d0db36332 --- /dev/null +++ b/Explore/MapLayer.cpp @@ -0,0 +1,504 @@ +// +// MapLayer.cpp +// GeoDa +// +// Created by Xun Li on 8/24/18. +// + +#include "MapNewView.h" +#include "../Project.h" +#include "MapLayer.hpp" + +BackgroundMapLayer::BackgroundMapLayer() +: AssociateLayerInt(), +pen_color(wxColour(192, 192, 192)), +brush_color(wxColour(255, 255, 255, 255)), +point_radius(2), +opacity(255), +pen_size(1), +show_boundary(false), +is_hide(true), +map_boundary(NULL) +{ +} + +BackgroundMapLayer::BackgroundMapLayer(wxString name, OGRLayerProxy* _layer_proxy, OGRSpatialReference* sr) +: AssociateLayerInt(), +layer_name(name), +layer_proxy(_layer_proxy), +pen_color(wxColour(192, 192, 192)), +brush_color(wxColour(255, 255, 255, 255)), +point_radius(2), +opacity(255), +pen_size(1), +show_boundary(false), +is_hide(false), +map_boundary(NULL), +show_connect_line(false) +{ + num_obs = layer_proxy->GetNumRecords(); + shape_type = layer_proxy->GetGdaGeometries(shapes, sr); + // this is for map boundary only + shape_type = layer_proxy->GetOGRGeometries(geoms, sr); + field_names = layer_proxy->GetIntegerFieldNames(); + key_names = layer_proxy->GetIntegerAndStringFieldNames(); + for (int i=0; i::iterator it; + for (it=associated_layers.begin(); it!=associated_layers.end();it++) { + AssociateLayerInt* asso_layer = it->first; + if (layer->GetName() == asso_layer->GetName()) { + del_key = asso_layer; + } + } + if (del_key) { + associated_layers.erase(del_key); + } +} + +void BackgroundMapLayer::SetLayerAssociation(wxString my_key, AssociateLayerInt* layer, wxString key, bool show_connline) +{ + associated_layers[layer] = make_pair(my_key, key); + associated_lines[layer] = show_connline; +} + +bool BackgroundMapLayer::IsAssociatedWith(AssociateLayerInt* layer) +{ + map::iterator it; + for (it=associated_layers.begin(); it!=associated_layers.end();it++) { + AssociateLayerInt* asso_layer = it->first; + if (layer->GetName() == asso_layer->GetName()) { + return true; + } + } + return false; +} + +GdaShape* BackgroundMapLayer::GetShape(int idx) +{ + return shapes[idx]; +} + +void BackgroundMapLayer::DrawHighlight(wxMemoryDC& dc, MapCanvas* map_canvas) +{ + // draw any connected layers + map::iterator it; + for (it=associated_layers.begin(); it!=associated_layers.end();it++) { + AssociateLayerInt* associated_layer = it->first; + Association& al = it->second; + wxString primary_key = al.first; + wxString associated_key = al.second; + + vector pid(shapes.size()); // e.g. 1 2 3 4 5 + if (primary_key.IsEmpty() == false) { + GetKeyColumnData(primary_key, pid); + } else { + for (int i=0; i fid; // e.g. 2 2 1 1 3 5 4 4 + associated_layer->GetKeyColumnData(associated_key, fid); + associated_layer->ResetHighlight(); + + map > aid_idx; + for (int i=0; i& ids = aid_idx[aid]; + for (int j=0; jSetHighlight( ids[j] ); + } + } + associated_layer->DrawHighlight(dc, map_canvas); + for (int i=0; i& ids = aid_idx[aid]; + for (int j=0; jcenter, associated_layer->GetShape(ids[j])->center); + } + } + } + } + + // draw self highlight + for (int i=0; ipaintSelf(dc); + } + } +} + +void BackgroundMapLayer::SetHighlight(int idx) +{ + highlight_flags[idx] = true; +} + +void BackgroundMapLayer::SetUnHighlight(int idx) +{ + highlight_flags[idx] = false; +} + +void BackgroundMapLayer::ResetHighlight() +{ + for (int i=0; iSetName(layer_name); + copy->SetShapeType(shape_type); + copy->SetKeyNames(key_names); + copy->SetFieldNames(field_names); + copy->associated_layers = associated_layers; + copy->associated_lines = associated_lines; + + if (clone_style) { + copy->SetPenColour(pen_color); + copy->SetBrushColour(brush_color); + copy->SetPointRadius(point_radius); + copy->SetOpacity(opacity); + copy->SetPenSize(pen_size); + copy->SetShowBoundary(show_boundary); + copy->SetHide(is_hide); + } + // deep copy + copy->highlight_flags = highlight_flags; + if (map_boundary) { + copy->map_boundary = map_boundary->clone(); + } + // not deep copy + copy->shapes = shapes; + copy->geoms = geoms; + copy->layer_proxy = layer_proxy; + copy->highlight_flags = highlight_flags; + return copy; +} + +int BackgroundMapLayer::GetNumRecords() +{ + return shapes.size(); +} + +bool BackgroundMapLayer::GetIntegerColumnData(wxString field_name, vector& data) +{ + if (data.empty()) { + data.resize(shapes.size()); + } + // this function is for finding IDs of multi-layer + GdaConst::FieldType type = layer_proxy->GetFieldType(field_name); + int col_idx = layer_proxy->GetFieldPos(field_name); + if (type == GdaConst::long64_type) { + for (int i=0; idata[i]->GetFieldAsInteger64(col_idx); + } + return true; + } else if (type == GdaConst::string_type) { + for (int i=0; idata[i]->GetFieldAsInteger64(col_idx); + } + } + return false; +} + +bool BackgroundMapLayer::GetKeyColumnData(wxString field_name, vector& data) +{ + if (data.empty()) { + data.resize(shapes.size()); + } + // this function is for finding IDs of multi-layer + if (field_name.IsEmpty() || field_name == "(Use Sequences)") { + for (int i=0; iGetFieldType(field_name); + int col_idx = layer_proxy->GetFieldPos(field_name); + if (type == GdaConst::long64_type) { + for (int i=0; idata[i]->GetFieldAsInteger64(col_idx); + } + return true; + } else if (type == GdaConst::string_type) { + for (int i=0; idata[i]->GetFieldAsString(col_idx); + } + } + return false; +} + +vector BackgroundMapLayer::GetIntegerFieldNames() +{ + return field_names; +} + +vector BackgroundMapLayer::GetKeyNames() +{ + return key_names; +} + +void BackgroundMapLayer::SetKeyNames(vector& names) +{ + key_names = names; +} + +void BackgroundMapLayer::SetFieldNames(vector& names) +{ + field_names = names; +} + +void BackgroundMapLayer::SetShapeType(Shapefile::ShapeType type) +{ + shape_type = type; +} + +Shapefile::ShapeType BackgroundMapLayer::GetShapeType() +{ + return shape_type; +} + +void BackgroundMapLayer::SetHide(bool flag) +{ + is_hide = flag; +} + +bool BackgroundMapLayer::IsHide() +{ + return is_hide; +} + +void BackgroundMapLayer::drawLegend(wxDC& dc, int x, int y, int w, int h) +{ + wxPen pen(pen_color); + int r = brush_color.Red(); + int g = brush_color.Green(); + int b = brush_color.Blue(); + wxColour b_color(r,g,b,opacity); + dc.SetPen(pen); + dc.SetBrush(b_color); + dc.DrawRectangle(x, y, w, h); +} + +void BackgroundMapLayer::SetOpacity(int val) +{ + opacity = val; +} + +int BackgroundMapLayer::GetOpacity() +{ + return opacity; +} + +int BackgroundMapLayer::GetPenSize() +{ + return pen_size; +} + +void BackgroundMapLayer::SetPenSize(int val) +{ + pen_size = val; +} + +void BackgroundMapLayer::SetPenColour(wxColour &color) +{ + pen_color = color; +} + +wxColour BackgroundMapLayer::GetPenColour() +{ + return pen_color; +} + +void BackgroundMapLayer::SetBrushColour(wxColour &color) +{ + brush_color = color; +} + +wxColour BackgroundMapLayer::GetBrushColour() +{ + return brush_color; +} + +void BackgroundMapLayer::ShowBoundary(bool show) +{ + show_boundary = show; + if (show) { + if (map_boundary == NULL) { + map_boundary = OGRLayerProxy::GetMapBoundary(geoms); + } + } +} + +void BackgroundMapLayer::SetShowBoundary(bool flag) +{ + show_boundary = flag; +} + +bool BackgroundMapLayer::IsShowBoundary() +{ + return show_boundary; +} + +void BackgroundMapLayer::SetPointRadius(int radius) +{ + point_radius = radius; +} + +int BackgroundMapLayer::GetPointRadius() +{ + return point_radius; +} + +vector& BackgroundMapLayer::GetShapes() +{ + return shapes; +} + + + + + + + +GdaShapeLayer::GdaShapeLayer(wxString _name, BackgroundMapLayer* _ml) +: name(_name), ml(_ml) +{ +} + +GdaShapeLayer::~GdaShapeLayer() +{ +} + +GdaShape* GdaShapeLayer::clone() +{ + // not implemented + return NULL; +} + +void GdaShapeLayer::Offset(double dx, double dy) +{ + +} + +void GdaShapeLayer::Offset(int dx, int dy) +{ + +} + +void GdaShapeLayer::applyScaleTrans(const GdaScaleTrans &A) +{ + if (ml->map_boundary) { + ml->map_boundary->applyScaleTrans(A); + } else { + for (int i=0; ishapes.size(); i++) { + ml->shapes[i]->applyScaleTrans(A); + } + } +} + +void GdaShapeLayer::projectToBasemap(GDA::Basemap *basemap, double scale_factor) +{ + if (ml->map_boundary) { + ml->map_boundary->projectToBasemap(basemap, scale_factor); + } else { + for (int i=0; ishapes.size(); i++) { + ml->shapes[i]->projectToBasemap(basemap, scale_factor); + } + } +} + +void GdaShapeLayer::paintSelf(wxDC &dc) +{ + if (ml->IsHide() == false) { + wxPen pen(ml->GetPenColour(), ml->GetPenSize()); + if (ml->GetPenSize() == 0 ) { + pen.SetColour(ml->GetBrushColour()); + } + + wxBrush brush(ml->GetBrushColour()); + + if (ml->IsShowBoundary()) { + ml->map_boundary->paintSelf(dc); + return; + } + + for (int i=0; ishapes.size(); i++) { + if (ml->GetShapeType() == Shapefile::POINT_TYP) { + GdaPoint* pt = (GdaPoint*)ml->shapes[i]; + pt->radius = ml->GetPointRadius(); + } + ml->shapes[i]->setPen(pen); + ml->shapes[i]->setBrush(brush); + ml->shapes[i]->paintSelf(dc); + } + } +} + +void GdaShapeLayer::paintSelf(wxGraphicsContext *gc) +{ + // not implemented (using wxGCDC instead) +} diff --git a/Explore/MapLayer.hpp b/Explore/MapLayer.hpp new file mode 100644 index 000000000..755a6d466 --- /dev/null +++ b/Explore/MapLayer.hpp @@ -0,0 +1,161 @@ +// +// MapLayer.hpp +// GeoDa +// +// Created by Xun Li on 8/24/18. +// + +#ifndef MapLayer_hpp +#define MapLayer_hpp + +#include +#include +#include + +#include "../GdaShape.h" +#include "../ShapeOperations/OGRLayerProxy.h" + +using namespace std; + +class MapCanvas; +class AssociateLayerInt; + +// my_key, key from other layer +typedef pair Association; + +class AssociateLayerInt +{ +public: + // primary key : AssociateLayer + map associated_layers; + map associated_lines; + + AssociateLayerInt() {} + virtual ~AssociateLayerInt() {} + + virtual bool IsCurrentMap() = 0; + virtual wxString GetName() = 0; + virtual int GetNumRecords() = 0; + virtual vector GetKeyNames() = 0; + virtual bool GetKeyColumnData(wxString col_name, vector& data) = 0; + virtual void ResetHighlight() = 0; + virtual void SetHighlight(int idx) = 0; + virtual void DrawHighlight(wxMemoryDC& dc, MapCanvas* map_canvas) = 0; + virtual void SetLayerAssociation(wxString my_key, AssociateLayerInt* layer, + wxString key, bool show_connline=true) = 0; + virtual bool IsAssociatedWith(AssociateLayerInt* layer) = 0; + virtual void ClearLayerAssociation() { + associated_layers.clear(); + } + virtual GdaShape* GetShape(int i) = 0; +}; + + +class BackgroundMapLayer : public AssociateLayerInt +{ + int num_obs; + Shapefile::ShapeType shape_type; + vector field_names; + vector key_names; + + bool show_connect_line; + wxString layer_name; + wxColour pen_color; + wxColour brush_color; + int point_radius; + int opacity; + int pen_size; + bool show_boundary; + bool is_hide; + +public: + OGRLayerProxy* layer_proxy; + GdaPolygon* map_boundary; + vector shapes; + vector geoms; + vector highlight_flags; + + BackgroundMapLayer(); + BackgroundMapLayer(wxString name, OGRLayerProxy* layer_proxy, OGRSpatialReference* sr); + virtual ~BackgroundMapLayer(); + + virtual bool IsCurrentMap(); + virtual int GetNumRecords(); + virtual bool GetKeyColumnData(wxString field_name, vector& data); + virtual void SetHighlight(int idx); + virtual void SetUnHighlight(int idx); + virtual void ResetHighlight(); + virtual void DrawHighlight(wxMemoryDC& dc, MapCanvas* map_canvas); + virtual void SetLayerAssociation(wxString my_key, AssociateLayerInt* layer, + wxString key, bool show_connline=true); + virtual bool IsAssociatedWith(AssociateLayerInt* layer); + virtual void RemoveAssociatedLayer(AssociateLayerInt* layer); + + + // clone all except shapes and geoms, which are owned by Project* instance; + // so that different map window can configure the multi-layers + BackgroundMapLayer* Clone(bool clone_style=false); + + vector& GetShapes(); + virtual GdaShape* GetShape(int idx); + + void CleanMemory(); + wxString GetAssociationText(); + + void SetName(wxString name); + virtual wxString GetName(); + + void SetHide(bool flag); + bool IsHide(); + + void SetPenColour(wxColour& color); + wxColour GetPenColour(); + + void SetBrushColour(wxColour& color); + wxColour GetBrushColour(); + + void SetPointRadius(int radius); + int GetPointRadius(); + + void SetOpacity(int opacity); + int GetOpacity(); + + void SetPenSize(int size); + int GetPenSize(); + + void SetShapeType(Shapefile::ShapeType type); + Shapefile::ShapeType GetShapeType(); + + void ShowBoundary(bool show); + bool IsShowBoundary(); + void SetShowBoundary(bool flag); + + void SetKeyNames(vector& names); + vector GetKeyNames(); + + void SetFieldNames(vector& names); + vector GetIntegerFieldNames(); + bool GetIntegerColumnData(wxString field_name, vector& data); + + void drawLegend(wxDC& dc, int x, int y, int w, int h); +}; + +class GdaShapeLayer : public GdaShape { + wxString name; + BackgroundMapLayer* ml; + +public: + GdaShapeLayer(wxString name, BackgroundMapLayer* ml); + ~GdaShapeLayer(); + + virtual GdaShape* clone(); + virtual void Offset(double dx, double dy); + virtual void Offset(int dx, int dy); + virtual void applyScaleTrans(const GdaScaleTrans& A); + virtual void projectToBasemap(GDA::Basemap* basemap, double scale_factor = 1.0); + virtual void paintSelf(wxDC& dc); + virtual void paintSelf(wxGraphicsContext* gc); +}; + + +#endif /* MapLayer_hpp */ diff --git a/Explore/MapLayerTree.cpp b/Explore/MapLayerTree.cpp new file mode 100644 index 000000000..cd95b4806 --- /dev/null +++ b/Explore/MapLayerTree.cpp @@ -0,0 +1,1042 @@ +// +// MapLayerTree.cpp +// GeoDa +// +// Created by Xun Li on 8/24/18. +// + +#include + +#include +#include +#include +#include +#include + +#include "../rc/GeoDaIcon-16x16.xpm" +#include "../DialogTools/SaveToTableDlg.h" +#include "../logger.h" +#include "../Project.h" +#include "../SpatialIndTypes.h" +#include "MapNewView.h" +#include "MapLayer.hpp" +#include "MapLayerTree.hpp" + +wxString SetAssociationDlg::LAYER_LIST_ID = "SETASSOCIATIONDLG_LAYER_LIST"; + +SetAssociationDlg::SetAssociationDlg(wxWindow* parent, AssociateLayerInt* ml,vector& _all_layers, const wxString& title, const wxPoint& pos, const wxSize& size) +: wxDialog(parent, -1, title, pos, size) +{ + current_ml = ml; + all_layers = _all_layers; + int nrows = all_layers.size(); + if (nrows == 0) nrows = 1; + for (int i=0; iBind(wxEVT_CHOICE, &SetAssociationDlg::OnLayerSelect, this); + } + CreateControls(nrows); + Center(); + Init(); +} + +void SetAssociationDlg::CreateControls(int nrows) +{ + wxBoxSizer *top_sizer = new wxBoxSizer(wxVERTICAL); + top_sizer->AddSpacer(10); + + wxFlexGridSizer *fg_sizer = new wxFlexGridSizer(nrows, 8, 3, 3); + for (int i=0; iAdd(new wxStaticText(this, wxID_ANY, _("Select layer")), 0, wxALIGN_CENTER | wxTOP | wxBOTTOM | wxLEFT, 5); + fg_sizer->Add(layer_list[i], 0, wxALL|wxALIGN_CENTER, 5); + fg_sizer->Add(new wxStaticText(this, wxID_ANY, _("and field")), 0, wxALIGN_CENTER | wxTOP | wxBOTTOM | wxLEFT, 5); + fg_sizer->Add(field_list[i], 0, wxALL|wxALIGN_CENTER, 5); + fg_sizer->Add(new wxStaticText(this, wxID_ANY, _("is associated to")), 0, wxALIGN_CENTER | wxTOP | wxBOTTOM | wxLEFT, 5); + fg_sizer->Add(my_field_list[i], 0, wxALL|wxALIGN_CENTER, 5); + fg_sizer->Add(new wxStaticText(this, wxID_ANY, _("in current layer.")), 0, wxALIGN_CENTER | wxTOP | wxBOTTOM | wxLEFT, 5); + fg_sizer->Add(conn_list[i], 0, wxALIGN_CENTER | wxTOP | wxBOTTOM | wxLEFT, 5); + } + + top_sizer->Add(fg_sizer, 0, wxALL|wxALIGN_CENTER, 15); + + wxButton* ok_btn = new wxButton(this, wxID_OK, _("OK"), wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT); + wxButton* cancel_btn = new wxButton(this, wxID_CANCEL, _("Close"), wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT); + wxBoxSizer* hbox = new wxBoxSizer(wxHORIZONTAL); + hbox->Add(ok_btn, 0, wxALIGN_CENTER | wxALL, 5); + hbox->Add(cancel_btn, 0, wxALIGN_CENTER | wxALL, 5); + + top_sizer->Add(hbox, 0, wxALL|wxALIGN_CENTER, 15); + + SetSizerAndFit(top_sizer); + + ok_btn->Bind(wxEVT_BUTTON, &SetAssociationDlg::OnOk, this); +} + +int SetAssociationDlg::GetSelectRow(wxCommandEvent& e) +{ + int sel_row = -1; + int ctrl_id = e.GetId(); + int nrows = all_layers.size(); + for (int i=0; iClear(); + layer_list[i]->Append(""); + for (int j=0; jGetName(); + layer_list[i]->Append(name); + } + + wxCommandEvent e; + e.SetId(ctrl_id); + OnLayerSelect(e); + + my_field_list[i]->Clear(); + my_field_list[i]->Append(""); + my_field_list[i]->Append(_("(Use Sequences)")); + vector my_fieldnames = current_ml->GetKeyNames(); + for (int j=0; jAppend(my_fieldnames[j]); + } + } + + int i = 0; + map& asso = current_ml->associated_layers; + map::iterator it; + for (it = asso.begin(); it!=asso.end(); it++) { + AssociateLayerInt* layer = it->first; + Association& lyr = it->second; + wxString my_key = lyr.first; + wxString key = lyr.second; + + wxString layer_name; + for (int j=0; jGetName(); + if (layer->GetName() == name) { + layer_name = name; + layer_list[i]->SetSelection(j+1); + + wxString layer_id = LAYER_LIST_ID; + layer_id << i; + int ctrl_id = XRCID(layer_id); + wxCommandEvent e; + e.SetId(ctrl_id); + OnLayerSelect(e); + + AssociateLayerInt* ml = GetMapLayer(layer_name); + if (ml) { + if (key.IsEmpty()) { + field_list[i]->SetSelection(1); + } else { + vector names = ml->GetKeyNames(); + for (int j=0; jSetSelection(j+2); + break; + } + } + } + } + break; + } + } + + vector my_fieldnames = current_ml->GetKeyNames(); + for (int j=0; jSetSelection(j+2); + break; + } + } + + conn_list[i]->SetValue(current_ml->associated_lines[layer]); + + i++; + } +} + +bool SetAssociationDlg::CheckLayerValid(int irow, wxString layer_name) +{ + int nrows = all_layers.size(); + for (int i=0; iGetSelection(); + wxString check_name = layer_list[i]->GetString(idx); + if (check_name == layer_name) { + return false; + } + } + } + return true; +} + +void SetAssociationDlg::OnLayerSelect(wxCommandEvent& e) +{ + int sel_row = GetSelectRow(e); + int idx = layer_list[sel_row]->GetSelection(); + if (idx >=0) { + field_list[sel_row]->Clear(); + wxString map_name = layer_list[sel_row]->GetString(idx); + if (map_name.IsEmpty()) + return; + if (CheckLayerValid(sel_row, map_name) == false) { + wxMessageDialog dlg (this, _("Current layer has already been associated with selected layer. Please select another layer to associate with."), _("Error"), wxOK | wxICON_ERROR); + dlg.ShowModal(); + layer_list[sel_row]->SetSelection(0); + return; + } + AssociateLayerInt* ml = GetMapLayer(map_name); + if (ml) { + field_list[sel_row]->Append(""); + field_list[sel_row]->Append(_("(Use Sequences)")); + vector names = ml->GetKeyNames(); + for (int i=0; iAppend(names[i]); + } + } + } +} + +AssociateLayerInt* SetAssociationDlg::GetMapLayer(wxString map_name) +{ + bool found = false; + AssociateLayerInt* ml = NULL; + for (int i=0; iGetName() == map_name) { + ml = all_layers[i]; + found = true; + break; + } + } + return ml; +} + +void SetAssociationDlg::OnOk(wxCommandEvent& e) +{ + current_ml->ClearLayerAssociation(); + + int nrows = all_layers.size(); + for (int i=0; iGetSelection(); + if (lyr_idx > 0) { + wxString mykey = GetCurrentLayerFieldName(i); + wxString key = GetSelectLayerFieldName(i); + AssociateLayerInt* layer = GetSelectMapLayer(i); + bool conn_flag = conn_list[i]->IsChecked(); + if (!mykey.IsEmpty() && !key.IsEmpty()) { + current_ml->SetLayerAssociation(mykey, layer, key, conn_flag); + } + } + } + + EndDialog(wxID_OK); +} + +wxString SetAssociationDlg::GetCurrentLayerFieldName(int irow) +{ + int idx = my_field_list[irow]->GetSelection(); + if (idx > 0) { + return my_field_list[irow]->GetString(idx); + } + return wxEmptyString; +} + +wxString SetAssociationDlg::GetSelectLayerFieldName(int irow) +{ + int idx = field_list[irow]->GetSelection(); + if (idx > 0) { // first row is "(Use Sequences)" + return field_list[irow]->GetString(idx); + } + return wxEmptyString; +} + +AssociateLayerInt* SetAssociationDlg::GetSelectMapLayer(int irow) +{ + int idx = layer_list[irow]->GetSelection(); + if (idx > 0) { + wxString map_name = layer_list[irow]->GetString(idx); + bool found = false; + AssociateLayerInt* ml = NULL; + for (int i=0; iGetName() == map_name) { + ml = all_layers[i]; + found = true; + break; + } + } + return ml; + } + return NULL; +} + +IMPLEMENT_ABSTRACT_CLASS(MapTree, wxWindow) +BEGIN_EVENT_TABLE(MapTree, wxWindow) +EVT_MENU(XRCID("IDC_CHANGE_POINT_RADIUS"), MapTree::OnChangePointRadius) +EVT_MOUSE_EVENTS(MapTree::OnEvent) +END_EVENT_TABLE() + +MapTree::MapTree(wxWindow *parent, MapCanvas* _canvas, const wxPoint& pos, const wxSize& size) +: wxWindow(parent, wxID_ANY, pos, size), +select_id(-1), +canvas(_canvas), +is_resize(false), +isLeftDown(false), +recreate_labels(true), +isDragDropAllowed(false) +{ + SetBackgroundColour(GdaConst::legend_background_color); + SetBackgroundStyle(wxBG_STYLE_PAINT); + px_switch = 30; + px = 60; + py = 40; + leg_h = 15; + leg_w = 20; + leg_pad_x = 10; + leg_pad_y = 5; + + current_map_title = canvas->GetName() + " (current map)"; + + Init(); + + Connect(wxEVT_IDLE, wxIdleEventHandler(MapTree::OnIdle)); + Connect(wxEVT_PAINT, wxPaintEventHandler(MapTree::OnPaint)); +} + +MapTree::~MapTree() +{ +} + +void MapTree::Init() +{ + int w, h; + GetClientSize(&w, &h); + + map_titles.clear(); + new_order.clear(); + + bg_maps = canvas->GetBackgroundMayLayers(); + fg_maps = canvas->GetForegroundMayLayers(); + + int n_maps = bg_maps.size() + fg_maps.size() + 1; + h = n_maps * 25 + 60; + SetSize(w, h); + + for (int i=0; iGetName(); + map_titles.push_back(lbl); + } + map_titles.push_back(current_map_title); + for (int i=0; iGetName(); + map_titles.push_back(lbl); + } + + + for (int i=0; iGetName() == map_name) { + // remove if it is associated with other layer + RemoveAssociationRelationship(ml); + canvas->RemoveLayer(map_name); + bg_maps.erase(bg_maps.begin() + i); + found = true; + break; + } + } + if (found == false) { + for (int i=0; iGetName() == map_name) { + // remove if it is associated with other layer + RemoveAssociationRelationship(ml); + canvas->RemoveLayer(map_name); + fg_maps.erase(fg_maps.begin() + i); + found = true; + break; + } + } + } + + if (found) { + int oid = new_order[select_id]; + map_titles.erase(map_titles.begin() + new_order[select_id]); + new_order.erase(new_order.begin() + select_id); + for (int i=0; i oid) { + new_order[i] -= 1; + } + } + select_id = select_id > 0 ? select_id-1 : 0; + Refresh(); + OnMapLayerChange(); + } +} + +void MapTree::RemoveAssociationRelationship(BackgroundMapLayer* ml) +{ + BackgroundMapLayer* tmp = NULL; + for (int i=0; iRemoveAssociatedLayer(ml); + } + } + for (int i=0; iRemoveAssociatedLayer(ml); + } + } +} + +void MapTree::OnSpatialJoinCount(wxCommandEvent& event) +{ + wxString map_name = map_titles[new_order[select_id]]; + BackgroundMapLayer* ml = GetMapLayer(map_name); + if (ml) { + // create rtree using points (normally, more points than polygons) + rtree_pt_2d_t rtree; + Shapefile::ShapeType shp_type = ml->GetShapeType(); + if (shp_type == Shapefile::POINT_TYP) { + int n = ml->shapes.size(); + double x, y; + for (int i=0; ishapes[i]->center_o.x; + y = ml->shapes[i]->center_o.y; + rtree.insert(std::make_pair(pt_2d(x,y), i)); + } + } + + // for each polygon in map, query points + Shapefile::Main& main_data = canvas->GetGeometryData(); + OGRLayerProxy* ogr_layer = canvas->GetOGRLayerProxy(); + Shapefile::PolygonContents* pc; + int n_polygons = main_data.records.size(); + vector spatial_counts(n_polygons, 0); + for (int i=0; ibox[0], pc->box[1]), + pt_2d(pc->box[2], pc->box[3])); + // query points in this box + std::vector q; + rtree.query(bgi::within(b), std::back_inserter(q)); + OGRGeometry* ogr_poly = ogr_layer->GetGeometry(i); + for (int j=0; j(); + double y = v.first.get<1>(); + OGRPoint ogr_pt(x, y); + if (ogr_pt.Within(ogr_poly)) { + spatial_counts[i] += 1; + } + } + } + + // save results + int new_col = 1; + std::vector new_data(new_col); + vector undefs(n_polygons, false); + new_data[0].l_val = &spatial_counts; + new_data[0].label = "Spatial Counts"; + new_data[0].field_default = "SC"; + new_data[0].type = GdaConst::long64_type; + new_data[0].undefined = &undefs; + SaveToTableDlg dlg(canvas->GetProject(), this, new_data, + "Save Results: Spatial Counts", + wxDefaultPosition, wxSize(400,400)); + dlg.ShowModal(); + } +} + +void MapTree::OnChangeFillColor(wxCommandEvent& event) +{ + wxString map_name = map_titles[new_order[select_id]]; + BackgroundMapLayer* ml = GetMapLayer(map_name); + if (ml) { + wxColour clr; + clr = wxGetColourFromUser(this, ml->GetBrushColour()); + ml->SetBrushColour(clr); + Refresh(); + canvas->DisplayMapLayers(); + } +} + +void MapTree::OnChangeOutlineColor(wxCommandEvent& event) +{ + wxString map_name = map_titles[new_order[select_id]]; + BackgroundMapLayer* ml = GetMapLayer(map_name); + if (ml) { + wxColour clr; + clr = wxGetColourFromUser(this, ml->GetPenColour()); + ml->SetPenColour(clr); + Refresh(); + canvas->DisplayMapLayers(); + } +} +void MapTree::OnChangePointRadius(wxCommandEvent& event) +{ + wxString map_name = map_titles[new_order[select_id]]; + BackgroundMapLayer* ml = GetMapLayer(map_name); + if (ml) { + int old_radius = ml->GetPointRadius(); + PointRadiusDialog dlg(_("Change Point Radius"), old_radius); + if (dlg.ShowModal() == wxID_OK) { + int new_radius = dlg.GetRadius(); + ml->SetPointRadius(new_radius); + Refresh(); + canvas->DisplayMapLayers(); + } + } +} + +void MapTree::OnClearAssociateLayer(wxCommandEvent& event) +{ + vector all_layers; + wxString map_name = map_titles[new_order[select_id]]; + AssociateLayerInt* ml = GetMapLayer(map_name); + + if (ml == NULL) { + // selection is current map + ml = canvas; + map_name = canvas->GetName(); + } + + ml->ClearLayerAssociation(); + +} + +void MapTree::OnSetAssociateLayer(wxCommandEvent& event) +{ + vector all_layers; + wxString map_name = map_titles[new_order[select_id]]; + AssociateLayerInt* ml = GetMapLayer(map_name); + + if (ml == NULL) { + // selection is current map + ml = canvas; + map_name = canvas->GetName(); + } + for (int i=0; iGetName() != ml->GetName()) { + all_layers.push_back(fg_maps[i]); + } + } + if (ml != canvas) { + all_layers.push_back(canvas); + } + for (int i=0; iGetName() != ml->GetName()) { + all_layers.push_back(bg_maps[i]); + } + } + + wxString title = _("Set Association Dialog"); + title << " (" << ml->GetName() << ")"; + SetAssociationDlg dlg(this, ml, all_layers, title); + + if (dlg.ShowModal() == wxID_OK) { + bool check_flag = false; + map::iterator it; + + for (int i=0; i checker; + vector stack; + + stack.push_back(ml); + + while (!stack.empty()) { + AssociateLayerInt* tmp_ml = stack.back(); + stack.pop_back(); + + if (checker.find(tmp_ml->GetName()) != checker.end()) { + check_flag = true; + break; + } else { + checker[tmp_ml->GetName()] = true; + } + map& asso = tmp_ml->associated_layers; + for (it = asso.begin(); it!= asso.end(); it++) { + AssociateLayerInt* layer = it->first; + Association& lyr = it->second; + wxString key = lyr.second; + stack.push_back(layer); + } + } + + if (check_flag) + break; + } + + if (check_flag) { + for (int i=0; iClearLayerAssociation(); + } + wxMessageDialog dlg (this, _("Invalid layer association has been detected, which will cause infinite highlighting loop. Please try to reset highlight association between layers."), _("Error"), wxOK | wxICON_ERROR); + dlg.ShowModal(); + } + } +} + +void MapTree::OnOutlineVisible(wxCommandEvent& event) +{ + wxString map_name = map_titles[new_order[select_id]]; + BackgroundMapLayer* ml = GetMapLayer(map_name); + if (ml) { + int pen_size = ml->GetPenSize(); + if (pen_size > 0) { + // not show outline + ml->SetPenSize(0); + } else { + // show outline + ml->SetPenSize(1); + } + Refresh(); + canvas->DisplayMapLayers(); + } +} +void MapTree::OnShowMapBoundary(wxCommandEvent& event) +{ + wxString map_name = map_titles[new_order[select_id]]; + BackgroundMapLayer* ml = GetMapLayer(map_name); + if (ml) { + bool show_bnd = ml->IsShowBoundary(); + ml->ShowBoundary(!show_bnd); + Refresh(); + canvas->DisplayMapLayers(); + } +} + +void MapTree::OnEvent(wxMouseEvent& event) +{ + int cat_clicked = GetCategoryClick(event); + if (event.RightUp()) { + OnRightClick(event); + return; + } + + if (event.LeftDown()) { + isLeftDown = true; + select_id = cat_clicked; + if (select_id > -1) { + select_name = map_titles[new_order[select_id]]; + move_pos = event.GetPosition(); + } + Refresh(); + } else if (event.Dragging()) { + if (isLeftDown) { + isLeftMove = true; + // moving + if (select_id > -1 ) { + // paint selected label with mouse + int label_id = new_order[select_id]; + move_pos = event.GetPosition(); + if (cat_clicked > -1 && select_id != cat_clicked) { + // reorganize new_order + int val = new_order[select_id]; + if (select_id > cat_clicked) { + new_order.insert(new_order.begin()+cat_clicked, val); + new_order.erase(new_order.begin() + select_id + 1); + } else { + new_order.insert(new_order.begin()+cat_clicked+1, val); + new_order.erase(new_order.begin() + select_id); + } + select_id = cat_clicked; + } + } + } + Refresh(); + } else if (event.LeftUp()) { + if (isLeftMove) { + isLeftMove = false; + // stop move + OnMapLayerChange(); + select_id = -1; + select_name = ""; + + } else { + // only left click + OnSwitchClick(event); + } + select_name = ""; + Refresh(false); + isLeftDown = false; + } else { + select_name = ""; + Refresh(false); + isLeftDown = false; + } +} + +void MapTree::OnRightClick(wxMouseEvent& event) +{ + select_id = GetLegendClick(event); + if (select_id < 0) { + OnSwitchClick(event); + return; + } + wxMenu* popupMenu = new wxMenu(wxEmptyString); + + wxString map_name = map_titles[ new_order[select_id] ]; + BackgroundMapLayer* ml = GetMapLayer(map_name); + + wxString menu_name = _("Set Highlight Association"); + popupMenu->Append(XRCID("MAPTREE_SET_FOREIGN_KEY"), menu_name); + Connect(XRCID("MAPTREE_SET_FOREIGN_KEY"), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MapTree::OnSetAssociateLayer)); + + popupMenu->Append(XRCID("MAPTREE_CLEAR_FOREIGN_KEY"), _("Clear Highlight Association")); + Connect(XRCID("MAPTREE_CLEAR_FOREIGN_KEY"), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MapTree::OnClearAssociateLayer)); + + if (ml == NULL) { + // if it's current map, then no other options other than "Set Highlight" + PopupMenu(popupMenu, event.GetPosition()); + return; + } + + popupMenu->AppendSeparator(); + + if (canvas->GetShapeType() == MapCanvas::polygons && + ml->GetShapeType() == Shapefile::POINT_TYP) + { + //popupMenu->Append(XRCID("MAPTREE_POINT_IN_POLYGON"), _("Spatial Join Count")); + //Connect(XRCID("MAPTREE_POINT_IN_POLYGON"), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MapTree::OnSpatialJoinCount)); + //popupMenu->AppendSeparator(); + } + + popupMenu->Append(XRCID("MAPTREE_CHANGE_FILL_COLOR"), _("Change Fill Color")); + popupMenu->Append(XRCID("MAPTREE_CHANGE_OUTLINE_COLOR"), _("Change Outline Color")); + popupMenu->Append(XRCID("MAPTREE_OUTLINE_VISIBLE"), _("Outline Visible")); + + // check menu items + wxMenuItem* outline = popupMenu->FindItem(XRCID("MAPTREE_OUTLINE_VISIBLE")); + if (outline) { + outline->SetCheckable(true); + if (ml->GetPenSize() > 0) outline->Check(); + } + + Connect(XRCID("MAPTREE_CHANGE_FILL_COLOR"), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MapTree::OnChangeFillColor)); + Connect(XRCID("MAPTREE_CHANGE_OUTLINE_COLOR"), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MapTree::OnChangeOutlineColor)); + Connect(XRCID("MAPTREE_OUTLINE_VISIBLE"), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MapTree::OnOutlineVisible)); + + if (ml->GetShapeType() == Shapefile::POINT_TYP) { + popupMenu->Append(XRCID("MAPTREE_CHANGE_POINT_RADIUS"), _("Change Point Radius")); + Connect(XRCID("MAPTREE_CHANGE_POINT_RADIUS"), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MapTree::OnChangePointRadius)); + + } else { + popupMenu->Append(XRCID("MAPTREE_BOUNDARY_ONLY"), _("Only Map Boundary")); + Connect(XRCID("MAPTREE_BOUNDARY_ONLY"), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MapTree::OnShowMapBoundary)); + wxMenuItem* boundary = popupMenu->FindItem(XRCID("MAPTREE_BOUNDARY_ONLY")); + if (boundary) { + boundary->SetCheckable(true); + if (ml->IsShowBoundary()) boundary->Check(); + } + } + popupMenu->AppendSeparator(); + + popupMenu->Append(XRCID("MAPTREE_REMOVE"), _("Remove")); + Connect(XRCID("MAPTREE_REMOVE"), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MapTree::OnRemoveMapLayer)); + + PopupMenu(popupMenu, event.GetPosition()); +} + +void MapTree::OnDraw(wxDC& dc) +{ + dc.SetFont(*GdaConst::small_font); + dc.SetPen(*wxBLACK_PEN); + wxCoord w, h; + dc.GetSize(&w, &h); + + dc.DrawText(_("Map Layer Setting"), 5, 10); + + if ( !select_name.IsEmpty() ) { + DrawLegend(dc, px_switch, move_pos.y, select_name); + } + + for (int i=0; iGetPenColour(), ml->GetPenSize()); + wxBrush brush(ml->GetBrushColour()); + dc.SetPen(pen); + dc.SetBrush(brush); + dc.DrawRectangle(x, y, leg_w, leg_h); + } + + x = x + leg_w + leg_pad_x; + dc.SetTextForeground(*wxBLACK); + if (text == current_map_title) { + dc.SetTextForeground(*wxLIGHT_GREY); + } + dc.DrawText(text, x, y); + + // draw switch button + if (ml == NULL) { + return; + } + + wxString ds_thumb = "switch-on.png"; + if (ml->IsHide()) ds_thumb = "switch-off.png"; + wxString file_path_str = GenUtils::GetSamplesDir() + ds_thumb; + + wxImage img; + if (!wxFileExists(file_path_str)) { + return; + } + + img.LoadFile(file_path_str); + if (!img.IsOk()) { + return; + } + + wxBitmap bmp(img); + dc.DrawBitmap(bmp, x_org, y); +} + +int MapTree::GetCategoryClick(wxMouseEvent& event) +{ + wxPoint pt(event.GetPosition()); + int x = pt.x, y = pt.y; + wxCoord w, h; + GetClientSize(&w, &h); + for (int i = 0; i px) && (x < w - px) && + (y > cur_y) && (y < cur_y + leg_h)) + { + return i; + } + } + return -1; +} + +int MapTree::GetSwitchClick(wxMouseEvent& event) +{ + wxPoint pt(event.GetPosition()); + int x = pt.x, y = pt.y; + + for (int i = 0; i px_switch) && (x < px_switch + 30) && + (y > cur_y) && (y < cur_y + leg_h)) + { + return i; + } + } + return -1; +} + +int MapTree::GetLegendClick(wxMouseEvent& event) +{ + wxPoint pt(event.GetPosition()); + int x = pt.x, y = pt.y; + + for (int i = 0; i px_switch + 30 && + (y > cur_y) && (y < cur_y + leg_h)) + { + return i; + } + } + return -1; +} + +void MapTree::OnSwitchClick(wxMouseEvent& event) +{ + int switch_idx = GetSwitchClick(event); + if (switch_idx > -1) { + wxString map_name = map_titles[new_order[switch_idx]]; + + BackgroundMapLayer* ml = GetMapLayer(map_name); + + if (ml) { + ml->SetHide(!ml->IsHide()); + canvas->DisplayMapLayers(); + Refresh(); + } + } +} + +BackgroundMapLayer* MapTree::GetMapLayer(wxString map_name) +{ + bool found = false; + BackgroundMapLayer* ml = NULL; + for (int i=0; iGetName() == map_name) { + ml = bg_maps[i]; + found = true; + break; + } + } + if (found == false) { + for (int i=0; iGetName() == map_name) { + ml = fg_maps[i]; + found = true; + break; + } + } + } + if (ml==NULL) { + + } + return ml; +} + +void MapTree::OnMapLayerChange() +{ + vector new_bg_maps; + vector new_fg_maps; + + bool is_fgmap = true; + for (int i=0; iSetForegroundMayLayers(fg_maps); + canvas->SetBackgroundMayLayers(bg_maps); + canvas->DisplayMapLayers(); +} + +void MapTree::AddCategoryColorToMenu(wxMenu* menu, int cat_clicked) +{ + +} + +MapTreeFrame::MapTreeFrame(wxWindow* parent, MapCanvas* _canvas, const wxPoint& pos, const wxSize& size) +: wxFrame(parent, -1, _canvas->GetCanvasTitle(), pos, size) +{ + SetIcon(wxIcon(GeoDaIcon_16x16_xpm)); + SetBackgroundColour(*wxWHITE); + canvas = _canvas; + tree = new MapTree(this, canvas, pos, size); + + wxBoxSizer* sizerAll = new wxBoxSizer(wxVERTICAL); + sizerAll->Add(tree, 1, wxEXPAND|wxALL, 10); + SetSizer(sizerAll); + SetAutoLayout(true); + sizerAll->Fit(this); + Centre(); + + Connect(wxEVT_CLOSE_WINDOW, wxCloseEventHandler(MapTreeFrame::OnClose)); +} + +MapTreeFrame::~MapTreeFrame() +{ + delete tree; +} + +void MapTreeFrame::OnClose( wxCloseEvent& event ) +{ + Destroy(); + event.Skip(); +} + +void MapTreeFrame::Recreate() +{ + int w, h; + GetClientSize(&w, &h); + + int n_maps = canvas->GetBackgroundMayLayers().size() + canvas->GetForegroundMayLayers().size() + 1; + h = n_maps * 25 + 120; + SetSize(w, h); + Layout(); + + tree->Init(); +} diff --git a/Explore/MapLayerTree.hpp b/Explore/MapLayerTree.hpp new file mode 100644 index 000000000..386496491 --- /dev/null +++ b/Explore/MapLayerTree.hpp @@ -0,0 +1,133 @@ +// +// MapLayerTree.hpp +// GeoDa +// +// Created by Xun Li on 8/24/18. +// + +#ifndef MapLayerTree_hpp +#define MapLayerTree_hpp + +#include +#include + +#include "MapLayer.hpp" + +using namespace std; + +class MapCanvas; + +class SetAssociationDlg : public wxDialog +{ + static wxString LAYER_LIST_ID; + vector layer_list; + vector field_list; + vector my_field_list; + vector conn_list; + AssociateLayerInt* current_ml; + vector all_layers; + + int GetSelectRow(wxCommandEvent& e); + bool CheckLayerValid(int row, wxString layer_name); +public: + SetAssociationDlg(wxWindow* parent, + AssociateLayerInt* ml, + vector& _all_layers, + const wxString& title = _("Set Association Dialog"), + const wxPoint& pos = wxDefaultPosition, + const wxSize& size = wxSize(400,300)); + void CreateControls(int nrows); + void Init(); + + wxString GetCurrentLayerFieldName(int irow); + wxString GetSelectLayerFieldName(int irow); + AssociateLayerInt* GetSelectMapLayer(int irow); + AssociateLayerInt* GetMapLayer(wxString map_name); + + void OnLayerSelect(wxCommandEvent& e); + void OnOk(wxCommandEvent& e); +}; + +class MapTree: public wxWindow +{ + DECLARE_ABSTRACT_CLASS(MapTree) + DECLARE_EVENT_TABLE() + + bool is_resize; + bool isDragDropAllowed; + wxSize maxSize; + int title_width; + int title_height; + int px, py; + int leg_w; + int leg_h; + int leg_pad_x; + int leg_pad_y; + int px_switch; + int opt_menu_cat; // last category added to Legend menu + + wxString current_map_title; + vector map_titles; + + MapCanvas* canvas; + vector bg_maps; + vector fg_maps; + + bool recreate_labels; + std::vector new_order; + bool isLeftDown; + bool isLeftMove; + int select_id; + wxString select_name; + wxPoint move_pos; + +public: + MapTree(wxWindow *parent, MapCanvas* canvas, const wxPoint& pos, + const wxSize& size); + virtual ~MapTree(); + + void Init(); + +protected: + virtual void OnPaint( wxPaintEvent& event ); + virtual void OnIdle(wxIdleEvent& event); + virtual void OnDraw(wxDC& dc); + + void RemoveAssociationRelationship(BackgroundMapLayer* ml); + void OnEvent(wxMouseEvent& event); + void OnRightClick(wxMouseEvent& event); + void OnChangeFillColor(wxCommandEvent& event); + void OnChangeOutlineColor(wxCommandEvent& event); + void OnChangePointRadius(wxCommandEvent& event); + void OnOutlineVisible(wxCommandEvent& event); + void OnShowMapBoundary(wxCommandEvent& event); + void OnRemoveMapLayer(wxCommandEvent& event); + void OnSwitchClick(wxMouseEvent& event); + void OnSpatialJoinCount(wxCommandEvent& event); + int GetLegendClick(wxMouseEvent& event); + int GetSwitchClick(wxMouseEvent& event); + int GetCategoryClick(wxMouseEvent& event); + void AddCategoryColorToMenu(wxMenu* menu, int cat_clicked); + void OnSetAssociateLayer(wxCommandEvent& event); + void OnClearAssociateLayer(wxCommandEvent& event); + void OnMapLayerChange(); + BackgroundMapLayer* GetMapLayer(wxString name); + void DrawLegend(wxDC& dc, int x, int y, wxString text); +}; + +class MapTreeFrame : public wxFrame +{ + MapTree *tree; + MapCanvas* canvas; + +public: + MapTreeFrame(wxWindow* parent, MapCanvas* canvas, + const wxPoint& pos = wxDefaultPosition, + const wxSize& size = wxDefaultSize); + virtual ~MapTreeFrame(); + + void OnClose( wxCloseEvent& event ); + void Recreate( ); +}; + +#endif /* MapLayerTree_hpp */ diff --git a/Explore/MapLayoutView.cpp b/Explore/MapLayoutView.cpp new file mode 100644 index 000000000..8a519734a --- /dev/null +++ b/Explore/MapLayoutView.cpp @@ -0,0 +1,781 @@ +// +// MapLayoutView.cpp +// GeoDa +// +// Created by Xun Li on 8/6/18. +// +#include +#include +#include + +#include "../TemplateLegend.h" +#include "../Explore/MapNewView.h" + +#include "MapLayoutView.h" + +using namespace std; + + +CanvasExportSettingDialog::CanvasExportSettingDialog(int w, int h, const wxString & title) +: wxDialog(NULL, -1, title, wxDefaultPosition, wxSize(320, 230)) +{ + width = w; + height = h; + tc1_value = w; + tc2_value = h; + unit_choice = 0; + aspect_ratio = (double) w / h; + wxPanel *panel = new wxPanel(this, -1); + + wxBoxSizer *vbox = new wxBoxSizer(wxVERTICAL); + wxBoxSizer *hbox = new wxBoxSizer(wxHORIZONTAL); + + wxFlexGridSizer *fgs = new wxFlexGridSizer(3, 3, 9, 25); + + wxStaticText *thetitle = new wxStaticText(panel, -1, _("Width:")); + wxStaticText *author = new wxStaticText(panel, -1, _("Height:")); + wxStaticText *review = new wxStaticText(panel, -1, _("Resolution(dpi):")); + + tc1 = new wxTextCtrl(panel, -1, wxString::Format("%d", w)); + tc2 = new wxTextCtrl(panel, -1, wxString::Format("%d", h)); + tc3 = new wxTextCtrl(panel, -1, "300"); + + wxString choices[] = {_("pixels"), _("inches"), _("mm")}; + m_unit = new wxChoice(panel, wxID_ANY, wxDefaultPosition, wxSize(100,-1), 3, choices); + m_unit->SetSelection(0); + + fgs->Add(thetitle); + fgs->Add(tc1, 1, wxEXPAND); + fgs->Add(m_unit, 1, wxEXPAND); + fgs->Add(author); + fgs->Add(tc2, 1, wxEXPAND); + fgs->AddSpacer(1); + fgs->Add(review, 1, wxEXPAND); + fgs->Add(tc3, 1, wxEXPAND); + fgs->AddSpacer(1); + + fgs->AddGrowableRow(2, 1); + fgs->AddGrowableCol(1, 1); + + wxButton *okButton = new wxButton(this, wxID_OK, _("Ok"), + wxDefaultPosition, wxSize(70, 30)); + wxButton *closeButton = new wxButton(this, wxID_CANCEL, _("Close"), + wxDefaultPosition, wxSize(70, 30)); + + hbox->Add(okButton, 1); + hbox->Add(closeButton, 1, wxLEFT, 5); + + wxBoxSizer* panel_v_szr = new wxBoxSizer(wxVERTICAL); + panel_v_szr->Add(fgs, 1, wxALL|wxEXPAND, 5); + panel->SetSizer(panel_v_szr); + + vbox->Add(panel, 1, wxALL | wxEXPAND, 10); + vbox->Add(hbox, 0, wxALIGN_CENTER | wxTOP | wxBOTTOM, 10); + + SetSizer(vbox); + SetAutoLayout(true); + vbox->Fit(this); + Centre(); + + tc1->Bind(wxEVT_TEXT, &CanvasExportSettingDialog::OnWidthChange, this); + tc2->Bind(wxEVT_TEXT, &CanvasExportSettingDialog::OnHeightChange, this); + tc3->Bind(wxEVT_TEXT, &CanvasExportSettingDialog::OnResolutionChange, this); + m_unit->Bind(wxEVT_CHOICE, &CanvasExportSettingDialog::OnUnitChange, this); +} + +void CanvasExportSettingDialog::OnUnitChange(wxCommandEvent& ev) +{ + // https://www.pixelcalculator.com/ + int unit_sel = m_unit->GetSelection(); + if (unit_sel >= 0) { + if (unit_choice == unit_sel) + return; + + double x = getTextValue(tc1); + double y = getTextValue(tc2); + + if (unit_choice == 0) { + if (unit_sel == 1) { + // pixel2inch + x = pixel2inch(x); + y = pixel2inch(y); + } else if (unit_sel == 2) { + // pixel2mm + x = pixel2mm(x); + y = pixel2mm(y); + } + + } else if (unit_choice == 1) { + if (unit_sel == 0) { + // inch2pixel + x = width; + y = height; + } else if (unit_sel == 2) { + // inch2mm + x = inch2mm(x); + y = inch2mm(y); + } + + } else if (unit_choice == 2) { + if (unit_sel == 0) { + // mm2pixel + x = width; + y = height; + } else if (unit_sel == 1) { + // mm2inch + x = mm2inch(x); + y = mm2inch(y); + } + } + unit_choice = unit_sel; + setTextValue(tc1, x); + setTextValue(tc2, y); + + } +} + +double CanvasExportSettingDialog::inch2mm(double inch) +{ + return inch * 25.4; +} + +double CanvasExportSettingDialog::mm2inch(double mm) +{ + return mm / 25.4; +} + +double CanvasExportSettingDialog::pixel2inch(int pixel) +{ + int res = GetMapResolution(); + if (res > 0) + return pixel * 1.0 / res; + return 0; +} + +double CanvasExportSettingDialog::pixel2mm(int pixel) +{ + int res = GetMapResolution(); + if (res > 0) + return pixel * 25.4 / res; + return 0; +} + +int CanvasExportSettingDialog::inch2pixel(double inch) +{ + int res = GetMapResolution(); + return inch * res; +} + +int CanvasExportSettingDialog::mm2pixel(double mm) +{ + int res = GetMapResolution(); + return mm * res / 25.4; +} + +void CanvasExportSettingDialog::OnResolutionChange(wxCommandEvent& ev) +{ + if (unit_choice > 0 ) { + width = GetMapWidth(); + height = GetMapHeight(); + } +} + +double CanvasExportSettingDialog::getTextValue(wxTextCtrl* tc) +{ + wxString val = tc->GetValue(); + double w = 0; + val.ToDouble(&w); + return w; +} + +void CanvasExportSettingDialog::setTextValue(wxTextCtrl* tc, double val) +{ + wxString tmp; + if (unit_choice == 0) { + tmp = wxString::Format("%d", (int)(val) ); + tc->SetLabel(tmp); + } else { + tmp = wxString::Format("%.2f", val); + tc->SetLabel(tmp); + } + if (tc == tc1) { + tc1_value = val; + } else if (tc == tc2) { + tc2_value = val; + } +} + +void CanvasExportSettingDialog::OnWidthChange(wxCommandEvent& ev) +{ + wxString val = tc1->GetValue(); + double w; + if (val.ToDouble(&w)) { + double h = w / aspect_ratio; + tc1_value = w; + setTextValue(tc2, h); + width = GetMapWidth(); + height = GetMapHeight(); + } +} + +void CanvasExportSettingDialog::OnHeightChange(wxCommandEvent& ev) +{ + wxString val = tc2->GetValue(); + double h; + if (val.ToDouble(&h)) { + double w = h * aspect_ratio; + tc2_value = h; + setTextValue(tc1, w); + width = GetMapWidth(); + height = GetMapHeight(); + } +} + +int CanvasExportSettingDialog::GetMapWidth() +{ + double val = tc1_value; + if (unit_choice == 1) { + return inch2pixel(val); + } else if (unit_choice == 2) { + return mm2pixel(val); + } + return val; +} + +int CanvasExportSettingDialog::GetMapHeight() +{ + double val = tc2_value; + if (unit_choice == 1) { + return inch2pixel(val); + } else if (unit_choice == 2) { + return mm2pixel(val); + } + return val; +} + +int CanvasExportSettingDialog::GetMapResolution() +{ + wxString val = tc3->GetValue(); + long result = 0; + if (!val.IsEmpty()) { + val.ToLong(&result); + } + return result; +} + +//////////////////////////////////////////////////////////////////////////////// + + +void CanvasLayoutEvtHandler::OnLeftClick(double WXUNUSED(x), double WXUNUSED(y), + int keys, int WXUNUSED(attachment)) +{ + wxShape* shape = this->GetShape(); + wxShapeCanvas* canvas = shape->GetCanvas(); + + wxNode* node = canvas->GetDiagram()->GetShapeList()->GetFirst(); + while (node) + { + wxShape* shape = (wxShape*) node->GetData(); + shape->Select(false); + shape->SetDraggable(false); + node = node->GetNext(); + } + + wxClientDC dc(canvas); + + if (shape) { + shape->Select(!shape->Selected()); + shape->SetHighlight(shape->Selected()); + shape->SetDraggable(shape->Selected()); + int x = shape->GetX(); + int y = shape->GetY(); + canvas->Refresh(); + } +} + +void CanvasLayoutEvtHandler::OnRightClick(double WXUNUSED(x), double WXUNUSED(y), + int keys, int WXUNUSED(attachment)) +{ + +} + +void CanvasLayoutEvtHandler::OnEndSize(double w, double h) +{ + +} + +//////////////////////////////////////////////////////////////////////////////// + + +CanvasLayoutDialog::CanvasLayoutDialog(wxString _project_name, TemplateLegend* _legend, TemplateCanvas* _canvas, const wxString& title, const wxPoint& pos, const wxSize& size) +: wxDialog(NULL, -1, title, pos, size, wxDEFAULT_DIALOG_STYLE|wxRESIZE_BORDER ) +{ + legend_shape = NULL; + + project_name = _project_name; + template_canvas = _canvas; + template_legend = _legend; + + is_resize = false; + is_initmap = false; + + canvas = new wxShapeCanvas(this, wxID_ANY, pos, size); + canvas->SetBackgroundColour(*wxWHITE); + canvas->SetCursor(wxCursor(wxCURSOR_CROSS)); + + diagram = new wxDiagram(); + diagram->SetCanvas(canvas); + canvas->SetDiagram(diagram); + + // map + map_shape = new wxBitmapShape(); + map_shape->SetCanvas(template_canvas); + canvas->AddShape(map_shape); + map_shape->SetDraggable(false); + map_shape->SetMaintainAspectRatio(true); + map_shape->Show(false); + + CanvasLayoutEvtHandler *evthandler = new CanvasLayoutEvtHandler(); + evthandler->SetShape(map_shape); + evthandler->SetPreviousHandler(map_shape->GetEventHandler()); + map_shape->SetEventHandler(evthandler); + + // legend + if (template_legend) { + legend_shape = new wxBitmapShape(); + legend_shape->SetCanvas(template_legend); + canvas->AddShape(legend_shape); + + legend_shape->SetX(50 + legend_shape->GetWidth()); + legend_shape->SetY(50 + legend_shape->GetHeight()); + legend_shape->MakeControlPoints(); + legend_shape->SetMaintainAspectRatio(true); + legend_shape->Show(false); + + CanvasLayoutEvtHandler *evthandler1 = new CanvasLayoutEvtHandler(); + evthandler1->SetShape(legend_shape); + evthandler1->SetPreviousHandler(legend_shape->GetEventHandler()); + legend_shape->SetEventHandler(evthandler1); + } + + //diagram->ShowAll(1); + + // ui + m_cb = new wxCheckBox(this, wxID_ANY, _("Show Legend")); + m_cb->SetValue(true); + if (template_legend == NULL) m_cb->Hide(); + m_no_bg = new wxCheckBox(this, wxID_ANY, _("Use Transparent Legend Background")); + m_no_bg->SetValue(true); + if (template_legend == NULL) m_no_bg->Hide(); + + wxBoxSizer *bmbox = new wxBoxSizer(wxHORIZONTAL); + m_bm_scale = new wxCheckBox(this, wxID_ANY, _("Scale Basemap")); + m_bm_scale->SetValue(true); + m_bm_scale->Hide(); + + bmbox->Add(m_cb); + bmbox->Add(m_no_bg); + bmbox->Add(m_bm_scale); + + wxBoxSizer *vbox = new wxBoxSizer(wxVERTICAL); + wxBoxSizer *hbox = new wxBoxSizer(wxHORIZONTAL); + wxButton *okButton = new wxButton(this, wxID_ANY, _("Save"), + wxDefaultPosition, wxSize(70, 30)); + wxButton *closeButton = new wxButton(this, wxID_CANCEL, _("Close"), + wxDefaultPosition, wxSize(70, 30)); + hbox->Add(okButton, 1, wxLEFT, 5); + hbox->Add(closeButton, 1, wxLEFT, 5); + vbox->Add(canvas, 1, wxEXPAND); + vbox->Add(bmbox, 0, wxALIGN_CENTER | wxTOP | wxBOTTOM, 10); + vbox->Add(hbox, 0, wxALIGN_CENTER | wxTOP | wxBOTTOM, 10); + SetSizer(vbox); + Centre(); + + Connect(wxEVT_SIZE, wxSizeEventHandler(CanvasLayoutDialog::OnSize)); + Connect(wxEVT_IDLE, wxIdleEventHandler(CanvasLayoutDialog::OnIdle)); + m_cb->Bind(wxEVT_CHECKBOX, &CanvasLayoutDialog::OnShowLegend, this); + m_no_bg->Bind(wxEVT_CHECKBOX, &CanvasLayoutDialog::OnTransparentBG, this); + m_bm_scale->Bind(wxEVT_CHECKBOX, &CanvasLayoutDialog::OnUseBMScale, this); + okButton->Bind(wxEVT_BUTTON, &CanvasLayoutDialog::OnSave, this); +} + +CanvasLayoutDialog::~CanvasLayoutDialog() +{ + if (legend_shape) delete legend_shape; + delete map_shape; + delete diagram; +} + +void CanvasLayoutDialog::OnSave(wxCommandEvent &event) +{ + int layout_w = GetWidth(); + int layout_h = GetHeight(); + CanvasExportSettingDialog setting_dlg(layout_w*2, layout_h*2, _("Image Dimension Setting")); + + if (setting_dlg.ShowModal() != wxID_OK) { + return; + } + + int out_res_x = setting_dlg.GetMapWidth(); + int out_resolution = setting_dlg.GetMapResolution(); + double lo_ar = (double)layout_w / layout_h; + int out_res_y = out_res_x / lo_ar; + + wxString default_fname(project_name); + wxString filter ="BMP|*.bmp|PNG|*.png|SVG|*.svg"; + int filter_index = 1; + wxFileDialog dialog(canvas, _("Save Image to File"), wxEmptyString, + default_fname, filter, + wxFD_SAVE | wxFD_OVERWRITE_PROMPT); + dialog.SetFilterIndex(filter_index); + if (dialog.ShowModal() != wxID_OK) { + return; + } + wxFileName fname = wxFileName(dialog.GetPath()); + wxString str_fname = fname.GetPathWithSep() + fname.GetName(); + + switch (dialog.GetFilterIndex()) { + case 0: + { + wxLogMessage("BMP selected"); + SaveToImage( str_fname, out_res_x, out_res_y, out_resolution); + } + break; + case 1: + { + wxLogMessage("PNG selected"); + SaveToImage( str_fname, out_res_x, out_res_y, out_resolution); + } + break; + + case 2: + { + wxLogMessage("SVG selected"); + SaveToSVG(str_fname, layout_w, layout_h); + } + break; + case 3: + { + wxLogMessage("PS selected"); + SaveToPS(str_fname); + } + break; + default: + { + } + break; + } +} + +void CanvasLayoutDialog::SaveToImage( wxString path, int out_res_x, int out_res_y, int out_resolution, wxBitmapType bm_type) +{ + double lo_scale = (double) out_res_x / GetWidth(); + + // composer of map and legend + wxBitmap all_bm(out_res_x, out_res_y); + wxMemoryDC all_dc(all_bm); + all_dc.SetBackground(*wxWHITE_BRUSH); + all_dc.Clear(); + + // print canvas + wxSize canvas_sz = template_canvas->GetClientSize(); + int canvas_width = canvas_sz.GetWidth(); + int canvas_height = canvas_sz.GetHeight(); + int lo_map_w = GetShapeWidth(map_shape) * lo_scale; + int lo_map_h = GetShapeHeight(map_shape) * lo_scale; + int lo_map_x = GetShapeStartX(map_shape) * lo_scale; + int lo_map_y = GetShapeStartY(map_shape) * lo_scale; + double canvas_scale = (double)lo_map_w / canvas_width; + wxBitmap canvas_bm; + canvas_bm.CreateScaled(canvas_width, canvas_height, 32, canvas_scale); + wxMemoryDC canvas_dc(canvas_bm); + canvas_dc.SetBackground(*wxWHITE_BRUSH); + canvas_dc.Clear(); + template_canvas->RenderToDC(canvas_dc, lo_map_w, lo_map_h); + all_dc.DrawBitmap(canvas_bm.ConvertToImage(), lo_map_x, lo_map_y); + + // print legend + if (template_legend && legend_shape && legend_shape->IsShown()) { + int legend_width = template_legend->GetDrawingWidth(); + int legend_height = template_legend->GetDrawingHeight(); + int lo_leg_w = GetShapeWidth(legend_shape) * lo_scale; + int lo_leg_h = GetShapeHeight(legend_shape) * lo_scale; + int lo_leg_x = GetShapeStartX(legend_shape) * lo_scale; + int lo_leg_y = GetShapeStartY(legend_shape) * lo_scale; + double leg_scale = (double)lo_leg_w / legend_width; + wxBitmap leg_bm(lo_leg_w, lo_leg_h); + wxMemoryDC leg_dc(leg_bm); + leg_dc.SetBackground(*wxWHITE_BRUSH); + leg_dc.Clear(); + template_legend->RenderToDC(leg_dc, leg_scale); + wxImage leg_im = leg_bm.ConvertToImage(); + if (m_no_bg->IsChecked()) { + leg_im.SetMaskColour(255, 255, 255); + all_dc.DrawBitmap(leg_im, lo_leg_x, lo_leg_y, true); + } else { + all_dc.DrawBitmap(leg_im, lo_leg_x, lo_leg_y); + } + } + + // save composer to file + if (bm_type == wxBITMAP_TYPE_PNG) path << ".png"; + else if (bm_type == wxBITMAP_TYPE_BMP) path << ".bmp"; + + wxImage output_img = all_bm.ConvertToImage(); + output_img.SetOption(wxIMAGE_OPTION_RESOLUTION, out_resolution); + output_img.SaveFile(path, bm_type); + output_img.Destroy(); +} + +void CanvasLayoutDialog::SaveToSVG(wxString path, int out_res_x, int out_res_y) +{ + int legend_w = 0; + double scale = 2.0; + if (template_legend) { + legend_w = template_legend->GetDrawingWidth() + 20; + } + + wxSVGFileDC dc(path + ".svg", out_res_x + legend_w + 20, out_res_y); + dc.SetDeviceOrigin(legend_w, 0); + template_canvas->RenderToSVG(dc, out_res_x, out_res_y); + if (template_legend) { + dc.SetDeviceOrigin(0, 20); + template_legend->RenderToDC(dc, 1.0); + } +} + +void CanvasLayoutDialog::SaveToPS(wxString path) +{ + int layout_w = GetWidth(); + int layout_h = GetHeight(); + + wxPrintData printData; + printData.SetFilename(path + ".ps"); + printData.SetPrintMode(wxPRINT_MODE_FILE); + wxPostScriptDC dc(printData); + + int w, h; + dc.GetSize(&w, &h); // A4 paper like? + wxLogMessage(wxString::Format("wxPostScriptDC GetSize = (%d,%d)", w, h)); + + if (dc.IsOk()) { + dc.StartDoc("printing..."); + int paperW, paperH; + dc.GetSize(&paperW, &paperH); + + double marginFactor = 0.03; + int marginW = (int) (paperW*marginFactor/2.0); + int marginH = (int) (paperH*marginFactor); + + int workingW = paperW - 2*marginW; + int workingH = paperH - 2*marginH; + + int originX = marginW+1; // experimentally obtained tweak + int originY = marginH+300; // experimentally obtained tweak + + // 1/5 use for legend; 4/5 use for map + int legend_w = 0; + double scale = 1.0; + + if (template_legend) { + legend_w = workingW * 0.2; + int legend_orig_w = template_legend->GetDrawingWidth(); + scale = legend_orig_w / (double) legend_w; + + dc.SetDeviceOrigin(originX, originY); + + template_legend->RenderToDC(dc, scale); + } + + wxSize canvas_sz = template_canvas->GetDrawingSize(); + int picW = canvas_sz.GetWidth(); + int picH = canvas_sz.GetHeight(); + + int map_w = 0; + int map_h = 0; + + // landscape + map_w = workingW - legend_w; + map_h = map_w * picH / picW; + + if (picW < picH) { + // portrait + map_w = map_w * (map_w / (double) map_h); + map_h = map_w * picH / picW; + } + + dc.SetDeviceOrigin( originX + legend_w + 100, originY); + + template_canvas->RenderToDC(dc, map_w, map_h); + + dc.EndDoc(); + } +} + +void CanvasLayoutDialog::OnShowLegend(wxCommandEvent &event) +{ + bool show_legend = m_cb->GetValue(); + if (m_no_bg) { + m_no_bg->Enable(show_legend); + } + legend_shape->Select(show_legend); + legend_shape->Show(show_legend); + wxClientDC dc(canvas); + canvas->Redraw(dc); + is_resize = true; +} + +void CanvasLayoutDialog::OnTransparentBG(wxCommandEvent &event) +{ + legend_shape->SetTransparentBG(m_no_bg->IsChecked()); + is_resize = true; +} + +void CanvasLayoutDialog::OnUseBMScale(wxCommandEvent &event) +{ + map_shape->SetScaledBasemap(m_bm_scale->IsChecked()); + is_resize = true; +} + +void CanvasLayoutDialog::OnSize(wxSizeEvent &event) +{ + is_resize = true; + event.Skip(); +} + +void CanvasLayoutDialog::OnIdle(wxIdleEvent& event) +{ + if (is_resize) { + if (!is_initmap) { + is_initmap = true; + int w, h; + canvas->GetClientSize(&w, &h); + double layout_width = w - 100; + double layout_height = h - 100; + double new_map_w, new_map_h; + double lo_ratio = layout_width / layout_height; + double map_ratio = map_shape->GetWidth() / (double)map_shape->GetHeight(); + if (lo_ratio > map_ratio) { + new_map_h = layout_height * 1.05; + new_map_w = map_ratio * new_map_h; + } else { + new_map_w = layout_width * 1.05; + new_map_h = new_map_w / map_ratio; + } + map_shape->SetSize(new_map_w, new_map_h); + map_shape->SetX(w/2.0); + map_shape->SetY(h/2.0); + //map_shape->Show(true); + diagram->ShowAll(1); + } + is_resize = false; + Refresh(); + } +} + +int CanvasLayoutDialog::GetWidth() +{ + wxSize sz = canvas->GetClientSize(); + return sz.GetWidth() - 100; +} + +int CanvasLayoutDialog::GetHeight() +{ + wxSize sz = canvas->GetClientSize(); + return sz.GetHeight() - 100; +} + +double CanvasLayoutDialog::GetShapeWidth(wxBitmapShape* shape) +{ + return shape->GetWidth(); +} + +double CanvasLayoutDialog::GetShapeHeight(wxBitmapShape* shape) +{ + return shape->GetHeight(); +} + +double CanvasLayoutDialog::GetShapeStartX(wxBitmapShape* shape) +{ + double x = shape->GetX(); + x = x - shape->GetWidth() /2.0; + return x - 50; +} + +double CanvasLayoutDialog::GetShapeStartY(wxBitmapShape* shape) +{ + double y = shape->GetY(); + y = y - shape->GetHeight() /2.0; + return y - 50; +} + +//////////////////////////////////////////////////////////////////////////////// + +MapLayoutDialog::MapLayoutDialog(wxString _project_name, TemplateLegend* _legend, TemplateCanvas* _canvas, const wxString& title, const wxPoint& pos, const wxSize& size) +: CanvasLayoutDialog(_project_name, _legend, _canvas, title, pos, size) +{ +} + +MapLayoutDialog::~MapLayoutDialog() +{ + +} + +void MapLayoutDialog::SaveToImage( wxString path, int out_res_x, int out_res_y, int out_resolution, wxBitmapType bm_type ) +{ + double lo_scale = (double) out_res_x / GetWidth(); + + // composer of map and legend + wxBitmap all_bm(out_res_x, out_res_y); + wxMemoryDC all_dc(all_bm); + all_dc.SetBackground(*wxWHITE_BRUSH); + all_dc.Clear(); + + // print map + wxSize map_sz = template_canvas->GetClientSize(); + int map_width = map_sz.GetWidth(); + int map_height = map_sz.GetHeight(); + int lo_map_w = GetShapeWidth(map_shape) * lo_scale; + int lo_map_h = GetShapeHeight(map_shape) * lo_scale; + int lo_map_x = GetShapeStartX(map_shape) * lo_scale; + int lo_map_y = GetShapeStartY(map_shape) * lo_scale; + double map_scale = (double)lo_map_w / map_width; + wxBitmap map_bm(lo_map_w, lo_map_h); + wxMemoryDC map_dc(map_bm); + map_dc.SetBackground(*wxWHITE_BRUSH); + map_dc.Clear(); + template_canvas->RenderToDC(map_dc, lo_map_w, lo_map_h); + all_dc.DrawBitmap(map_bm.ConvertToImage(), lo_map_x, lo_map_y); + + // print legend + if (template_legend && legend_shape && legend_shape->IsShown()) { + int legend_width = template_legend->GetDrawingWidth(); + int legend_height = template_legend->GetDrawingHeight(); + int lo_leg_w = GetShapeWidth(legend_shape) * lo_scale; + int lo_leg_h = GetShapeHeight(legend_shape) * lo_scale; + int lo_leg_x = GetShapeStartX(legend_shape) * lo_scale; + int lo_leg_y = GetShapeStartY(legend_shape) * lo_scale; + double leg_scale = (double)lo_leg_w / legend_width; + wxBitmap leg_bm(lo_leg_w, lo_leg_h); + wxMemoryDC leg_dc(leg_bm); + leg_dc.SetBackground(*wxWHITE_BRUSH); + leg_dc.Clear(); + template_legend->RenderToDC(leg_dc, leg_scale); + wxImage leg_im = leg_bm.ConvertToImage(); + if (m_no_bg->IsChecked()) { + leg_im.SetMaskColour(255, 255, 255); + all_dc.DrawBitmap(leg_im, lo_leg_x, lo_leg_y, true); + } else { + all_dc.DrawBitmap(leg_im, lo_leg_x, lo_leg_y); + } + } + + // save composer to file + if (bm_type == wxBITMAP_TYPE_PNG) path << ".png"; + else if (bm_type == wxBITMAP_TYPE_BMP) path << ".bmp"; + + wxImage output_img = all_bm.ConvertToImage(); + output_img.SetOption(wxIMAGE_OPTION_RESOLUTION, out_resolution); + output_img.SaveFile(path, bm_type); + output_img.Destroy(); +} diff --git a/Explore/MapLayoutView.h b/Explore/MapLayoutView.h new file mode 100644 index 000000000..b84960d53 --- /dev/null +++ b/Explore/MapLayoutView.h @@ -0,0 +1,122 @@ +// +// MapLayoutView.hpp +// GeoDa +// +// Created by Xun Li on 8/6/18. +// + +#ifndef MapLayoutView_h +#define MapLayoutView_h + +#include "wx/wx.h" +#include "../ogl/ogl.h" + +class MapCanvas; +class TemplateLegend; + + + +class CanvasExportSettingDialog : public wxDialog +{ + wxTextCtrl *tc1; + wxTextCtrl *tc2; + wxTextCtrl *tc3; + wxChoice* m_unit; + int unit_choice; + double aspect_ratio; + double tc1_value; + double tc2_value; + int width; + int height; + + double inch2mm(double inch); + double mm2inch(double mm); + double pixel2inch(int pixel); + double pixel2mm(int pixel); + int inch2pixel(double inch); + int mm2pixel(double mm); + double getTextValue(wxTextCtrl* tc); + void setTextValue(wxTextCtrl*tc, double val); + +public: + CanvasExportSettingDialog(int w, int h, const wxString& title); + + int GetMapWidth(); + int GetMapHeight(); + int GetMapResolution(); + + void OnWidthChange(wxCommandEvent& ev); + void OnHeightChange(wxCommandEvent& ev); + void OnResolutionChange(wxCommandEvent& ev); + void OnUnitChange(wxCommandEvent& ev); +}; + +class CanvasLayoutEvtHandler: public wxShapeEvtHandler +{ +public: + CanvasLayoutEvtHandler(wxShapeEvtHandler *prev = NULL, wxShape *shape = NULL, + const wxString& lab = wxEmptyString) + : wxShapeEvtHandler(prev, shape) { } + + ~CanvasLayoutEvtHandler(void) {} + + void OnLeftClick(double x, double y, int keys = 0, int attachment = 0); + void OnRightClick(double x, double y, int keys = 0, int attachment = 0); + virtual void OnEndSize(double w, double h); +}; + +class CanvasLayoutDialog : public wxDialog +{ +protected: + wxDiagram * diagram; + wxShapeCanvas *canvas; + + wxCheckBox* m_cb; + wxCheckBox* m_no_bg; + wxCheckBox* m_bm_scale; + + bool is_resize; + bool is_initmap; + + TemplateCanvas* template_canvas; + TemplateLegend* template_legend; + + wxString project_name; + +public: + CanvasLayoutDialog(wxString project_name, TemplateLegend* _legend, TemplateCanvas* _map, const wxString& title, const wxPoint& pos, const wxSize& size); + virtual ~CanvasLayoutDialog(); + + wxBitmapShape * map_shape; + wxBitmapShape * legend_shape; + + int GetWidth(); + int GetHeight(); + + double GetShapeWidth(wxBitmapShape* shape); + double GetShapeHeight(wxBitmapShape* shape); + double GetShapeStartX(wxBitmapShape* shape); + double GetShapeStartY(wxBitmapShape* shape); + + void OnSave( wxCommandEvent& event); + void OnSize( wxSizeEvent& event ); + void OnIdle( wxIdleEvent& event ); + void OnShowLegend( wxCommandEvent& event ); + void OnTransparentBG( wxCommandEvent& event ); + void OnUseBMScale(wxCommandEvent &event); + + virtual void SaveToImage( wxString path, int out_res_x, int out_res_y, int out_resolution, wxBitmapType bm_type = wxBITMAP_TYPE_PNG); + void SaveToSVG(wxString path, int out_res_x, int out_res_y); + void SaveToPS(wxString path); +}; + +class MapLayoutDialog : public CanvasLayoutDialog +{ +public: + MapLayoutDialog(wxString project_name, TemplateLegend* _legend, TemplateCanvas* _map, const wxString& title, const wxPoint& pos, const wxSize& size); + virtual ~MapLayoutDialog(); + + virtual void SaveToImage( wxString path, int out_res_x, int out_res_y, int out_resolution, wxBitmapType bm_type = wxBITMAP_TYPE_PNG); +}; + +#endif /* MapLayoutView_h */ diff --git a/Explore/MapNewView.cpp b/Explore/MapNewView.cpp index e9ba20ea4..433d4c999 100644 --- a/Explore/MapNewView.cpp +++ b/Explore/MapNewView.cpp @@ -31,9 +31,9 @@ #include #include #include - -#include "CatClassifState.h" -#include "CatClassifManager.h" +#include +#include +#include #include "../DataViewer/TableInterface.h" #include "../DataViewer/TimeState.h" #include "../DialogTools/CatClassifDlg.h" @@ -42,27 +42,31 @@ #include "../DialogTools/VariableSettingsDlg.h" #include "../DialogTools/ExportDataDlg.h" #include "../DialogTools/ConnectDatasourceDlg.h" +#include "../ShapeOperations/RateSmoothing.h" +#include "../ShapeOperations/VoronoiUtils.h" +#include "../ShapeOperations/WeightsManager.h" +#include "../ShapeOperations/WeightsManState.h" +#include "../ShapeOperations/OGRDatasourceProxy.h" +#include "../ShapeOperations/OGRDataAdapter.h" #include "../GdaConst.h" #include "../GeneralWxUtils.h" #include "../logger.h" #include "../GeoDa.h" #include "../Project.h" -#include "../ShapeOperations/RateSmoothing.h" -#include "../ShapeOperations/ShapeUtils.h" -#include "../ShapeOperations/VoronoiUtils.h" -#include "../ShapeOperations/WeightsManager.h" -#include "../ShapeOperations/WeightsManState.h" +#include "../TemplateLegend.h" +#include "CatClassifState.h" +#include "CatClassifManager.h" +#include "MapLayoutView.h" +#include "MapLayerTree.hpp" #include "Basemap.h" #include "MapNewView.h" +using namespace std; + wxWindowID ID_SLIDER = wxID_ANY; IMPLEMENT_CLASS(SliderDialog, wxDialog) BEGIN_EVENT_TABLE(SliderDialog, wxDialog) - EVT_COMMAND_SCROLL_THUMBRELEASE( ID_SLIDER, SliderDialog::OnSliderChange) -#ifdef __WIN32__ - EVT_COMMAND_SCROLL_CHANGED(ID_SLIDER, SliderDialog::OnSliderChange) -#endif END_EVENT_TABLE() SliderDialog::SliderDialog(wxWindow * parent, @@ -112,19 +116,19 @@ SliderDialog::SliderDialog(wxWindow * parent, boxSizer->Add(new wxButton(this, wxID_CANCEL, _("Close")), 0, wxALIGN_CENTER|wxALL, 10); topSizer->Fit(this); + + slider->Bind(wxEVT_SLIDER, &SliderDialog::OnSliderChange, this); } SliderDialog::~SliderDialog() { - } -void SliderDialog::OnSliderChange( wxScrollEvent & event ) +void SliderDialog::OnSliderChange( wxCommandEvent & event ) { int val = event.GetInt(); double trasp = 1.0 - val / 100.0; - slider_text->SetLabel(wxString::Format("Current Transparency: %.2f", trasp)); - //GdaConst::transparency_unhighlighted = (1-trasp) * 255; + slider_text->SetLabel(wxString::Format(_("Current Transparency: %.2f"), trasp)); canvas->tran_unhighlighted = (1-trasp) * 255; canvas->ReDraw(); } @@ -134,6 +138,7 @@ BEGIN_EVENT_TABLE(MapCanvas, TemplateCanvas) // in Linux, windows using old paint function without transparency support EVT_PAINT(TemplateCanvas::OnPaint) EVT_IDLE(MapCanvas::OnIdle) + EVT_SIZE(MapCanvas::OnSize) EVT_ERASE_BACKGROUND(TemplateCanvas::OnEraseBackground) //EVT_MOUSE_EVENTS(TemplateCanvas::OnMouseEvent) //EVT_MOUSE_CAPTURE_LOST(TemplateCanvas::OnMouseCaptureLostEvent) @@ -141,11 +146,14 @@ BEGIN_EVENT_TABLE(MapCanvas, TemplateCanvas) END_EVENT_TABLE() bool MapCanvas::has_thumbnail_saved = false; +bool MapCanvas::has_shown_empty_shps_msg = false; +std::vector MapCanvas::empty_shps_ids(0); +std::map MapCanvas::empty_dict; MapCanvas::MapCanvas(wxWindow *parent, TemplateFrame* t_frame, Project* project_s, - const std::vector& var_info_s, - const std::vector& col_ids_s, + const vector& var_info_s, + const vector& col_ids_s, CatClassification::CatClassifType theme_type, SmoothingType smoothing_type_s, int num_categories_s, @@ -158,7 +166,8 @@ num_obs(project_s->GetNumRecords()), p_datasource(project_s->GetDataSource()), num_time_vals(1), custom_classif_state(0), -data(0), +data(0), +s_data(0), var_info(0), table_int(project_s->GetTableInt()), smoothing_type(no_smoothing), @@ -166,32 +175,35 @@ is_rate_smoother(false), full_map_redraw_needed(true), display_mean_centers(false), display_centroids(false), -display_voronoi_diagram(false), +display_weights_graph(false), +display_map_boundary(false), +display_neighbors(false), +display_map_with_graph(true), +display_voronoi_diagram(false), +graph_color(GdaConst::conn_graph_outline_colour), +conn_selected_color(GdaConst::conn_select_outline_colour), +neighbor_fill_color(GdaConst::conn_neighbor_fill_colour), +weights_graph_thickness(1), voronoi_diagram_duplicates_exist(false), num_categories(num_categories_s), weights_id(weights_id_s), basemap(0), isDrawBasemap(false), basemap_bm(0), -map_type(0), -tran_unhighlighted(GdaConst::transparency_unhighlighted) +ref_var_index(-1), +tran_unhighlighted(GdaConst::transparency_unhighlighted), +print_detailed_basemap(false), +maplayer_state(project_s->GetMapLayerState()) { wxLogMessage("MapCanvas::MapCanvas()"); - using namespace Shapefile; - - cat_classif_def.cat_classif_type = theme_type; - if (theme_type == CatClassification::no_theme) { - //cat_classif_def.color_scheme = CatClassification::custom_color_scheme; - //CatClassification::ChangeNumCats(1, cat_classif_def); - //cat_classif_def.colors[0] = GdaConst::map_default_fill_colour; - } - selectable_fill_color = GdaConst::map_default_fill_colour; - + layer_name = project->layername; + bg_maps = project->CloneBackgroundMaps(); + ds_name = project->GetDataSource()->GetOGRConnectStr(); last_scale_trans.SetData(project->main_data.header.bbox_x_min, project->main_data.header.bbox_y_min, project->main_data.header.bbox_x_max, project->main_data.header.bbox_y_max); - + selectable_fill_color = GdaConst::map_default_fill_colour; if (project->main_data.header.shape_type == Shapefile::POINT_TYP) { selectable_shps_type = points; highlight_color = *wxRED; @@ -199,51 +211,318 @@ tran_unhighlighted(GdaConst::transparency_unhighlighted) selectable_shps_type = polygons; highlight_color = GdaConst::map_default_highlight_colour; } - - layer_name = project->layername; - ds_name = project->GetDataSource()->GetOGRConnectStr(); - use_category_brushes = true; - if (!ChangeMapType(theme_type, smoothing_type_s, num_categories, - weights_id, true, var_info_s, col_ids_s)) - { - // The user possibly clicked cancel. Try again with - // themeless map - std::vector vi(0); - std::vector cids(0); - ChangeMapType(CatClassification::no_theme, no_smoothing, 1, - boost::uuids::nil_uuid(), - true, vi, cids); + cat_classif_def.cat_classif_type = theme_type; + if (!ChangeMapType(theme_type, smoothing_type_s, num_categories, weights_id, true, var_info_s, col_ids_s)) { + // The user possibly clicked cancel, so try again with themeless map + vector vi(0); + vector cids(0); + ChangeMapType(CatClassification::no_theme, no_smoothing, 1, boost::uuids::nil_uuid(), true, vi, cids); } highlight_state->registerObserver(this); + maplayer_state->registerObserver(this); SetBackgroundStyle(wxBG_STYLE_CUSTOM); // default style - isDrawBasemap = GdaConst::use_basemap_by_default; if (isDrawBasemap) { - map_type = GdaConst::default_basemap_selection; + basemap_item = GetBasemapSelection(GdaConst::default_basemap_selection); } } MapCanvas::~MapCanvas() { wxLogMessage("MapCanvas::~MapCanvas()"); + for (int i=0; iremoveObserver(this); - if (custom_classif_state) custom_classif_state->removeObserver(this); - - + if (maplayer_state) + maplayer_state->removeObserver(this); if (basemap != NULL) { delete basemap; basemap = NULL; } +} + +Shapefile::Main& MapCanvas::GetGeometryData() +{ + return project->main_data; +} + +OGRLayerProxy* MapCanvas::GetOGRLayerProxy() +{ + return project->layer_proxy; +} + +vector MapCanvas::GetBackgroundMayLayers() +{ + return bg_maps; +} + +void MapCanvas::SetBackgroundMayLayers(vector& val) +{ + bg_maps = val; +} + +vector MapCanvas::GetForegroundMayLayers() +{ + return fg_maps; +} + +void MapCanvas::SetForegroundMayLayers(vector& val) +{ + fg_maps = val; +} + +int MapCanvas::GetEmptyNumber() +{ + return empty_shps_ids.size(); +} + +void MapCanvas::ResetEmptyFlag() +{ + empty_shps_ids.clear(); + empty_dict.clear(); + has_shown_empty_shps_msg = false; +} + +void MapCanvas::SetupColor() +{ +} + +void MapCanvas::UpdateSelectionPoints(bool shiftdown, bool pointsel) +{ + TemplateCanvas::UpdateSelectionPoints(shiftdown, pointsel); + + // if multi-layer presents and top layer is not current map + if ( fg_maps.empty() ) + return; + + BackgroundMapLayer* ml = fg_maps[0]; + int nn = ml->GetNumRecords(); + vector& geoms = ml->geoms; + vector& shapes = ml->shapes; + bool selection_changed = false; + if (!shiftdown) { + ml->ResetHighlight(); + } + if (pointsel) { // a point selection + for (int i=0; ipointWithin(sel1)) { + ml->SetHighlight(i); + } else { + ml->SetUnHighlight(i); + } + } + } else { // determine which obs intersect the selection region. + if (brushtype == rectangle) { + wxRegion rect(wxRect(sel1, sel2)); + for (int i=0; icenter) != + wxOutRegion); + if (contains) { + ml->SetHighlight(i); + selection_changed = true; + } else { + if (!shiftdown) + ml->SetUnHighlight(i); + } + } + + } else if (brushtype == circle) { + // using quad-tree to do pre-selection + double radius = GenUtils::distance(sel1, sel2); + // determine if each center is within radius of sel1 + for (int i=0; icenter) <= radius); + if (contains) { + ml->SetHighlight(i); + selection_changed = true; + } else { + if (!shiftdown) + ml->SetUnHighlight(i); + } + } + } else if (brushtype == line) { + wxRegion rect(wxRect(sel1, sel2)); + double p1x = sel1.x; + double p1y = sel1.y; + double p2x = sel2.x; + double p2y = sel2.y; + double p2xMp1x = p2x - p1x; + double p2yMp1y = p2y - p1y; + double dp1p2 = GenUtils::distance(sel1, sel2); + double delta = 3.0 * dp1p2; + for (int i=0; icenter) != wxOutRegion); + if (contains) { + double p0x = shapes[i]->center.x; + double p0y = shapes[i]->center.y; + // determine if selectable_shps[i]->center is within + // distance 3.0 of line passing through sel1 and sel2 + if (abs(p2xMp1x * (p1y-p0y) - (p1x-p0x) * p2yMp1y) > + delta ) contains = false; + } + if (contains) { + ml->SetHighlight(i); + selection_changed = true; + } else { + if (!shiftdown) + ml->SetUnHighlight(i); + } + } + } + } + if (selection_changed) { + int total_highlighted = 1; // used for MapCanvas::Drawlayer1 + highlight_state->SetTotalHighlighted(total_highlighted); + highlight_timer->Start(50); + } +} + +void MapCanvas::DetermineMouseHoverObjects(wxPoint pointsel) +{ + TemplateCanvas::DetermineMouseHoverObjects(pointsel); + if (layer0_bm && display_neighbors && sel1.x==0 && sel1.y==0 && sel2.x==0 && sel2.y==0) { + vector& hs = GetSelBitVec(); + if (hover_obs.empty()) { + //highlight_state->SetTotalHighlighted(0); + } else { + for (int i=0; iSetTotalHighlighted(1); + } + HighlightState& h_state = *project->GetHighlightState(); + h_state.SetEventType(HLStateInt::delta); + h_state.notifyObservers(); + layer1_valid = false; + DrawLayers(); + } +} + +void MapCanvas::SetPredefinedColor(const wxString& lbl, const wxColor& new_color) +{ + lbl_color_dict[lbl] = new_color; +} + +void MapCanvas::UpdatePredefinedColor(const wxString& lbl, const wxColor& new_color) +{ + // update predefined color, if user change the color on legend pane + map::iterator it; + for (it =lbl_color_dict.begin(); it!=lbl_color_dict.end(); it++) { + wxString predefined_lbl = it->first; + if ( lbl.StartsWith(predefined_lbl)) { + lbl_color_dict[predefined_lbl] = new_color; + } + } +} + +void MapCanvas::AddNeighborsToSelection(GalWeight* gal_weights, wxMemoryDC &dc) +{ + if (gal_weights == NULL) + return; + int ts = cat_data.GetCurrentCanvasTmStep(); + int num_obs = project->GetNumRecords(); + HighlightState& hs = *project->GetHighlightState(); + std::vector& h = hs.GetHighlight(); + std::vector add_elem(gal_weights->num_obs, false); + std::set::iterator it; + ids_of_nbrs.clear(); + ids_wo_nbrs.clear(); + for (int i=0; inum_obs; i++) { + if (h[i]) { + GalElement& e = gal_weights->gal[i]; + for (int j=0, jend=e.Size(); j new_hs(num_obs, false); + for (it=ids_of_nbrs.begin(); it!= ids_of_nbrs.end(); it++) { + new_hs[*it] = true; + } + for (int i=0; inum_obs; i++) { + if (h[i]) { + new_hs[i] = true; + } + } + bool hl_only = true; + bool revert = false; + bool crosshatch = false; + bool is_print = false; + helper_DrawSelectableShapes_dc(dc, new_hs, hl_only, revert, crosshatch, is_print); + // paint selected with specified outline color + if (conn_selected_color.Alpha() != 0) { + wxPen pen(conn_selected_color); + for (int i=0; inum_obs; i++) { + if (h[i]) { + selectable_shps[i]->setPen(pen); + selectable_shps[i]->setBrush(*wxTRANSPARENT_BRUSH); + selectable_shps[i]->paintSelf(dc); + } + } + } + if (display_neighbors) { + // paint neighbors with specified fill color + if (neighbor_fill_color.Alpha() != 0) { + wxBrush brush(neighbor_fill_color); + for (it=ids_of_nbrs.begin(); it!= ids_of_nbrs.end(); it++) { + selectable_shps[*it]->setBrush(brush); + selectable_shps[*it]->paintSelf(dc); + } + } + } + } +} + +void MapCanvas::OnSize(wxSizeEvent& event) +{ + if (!ids_of_nbrs.empty() && (display_neighbors || display_weights_graph)) { + // in case of display neighbors and weights graph, to prevent adding nbrs again when resizing window + HighlightState& hs = *project->GetHighlightState(); + std::vector& h = hs.GetHighlight(); + for (int i=0; iorigMap->west = last_scale_trans.orig_data_x_min; + basemap->origMap->east = last_scale_trans.orig_data_x_max; + basemap->origMap->south = last_scale_trans.orig_data_y_min; + basemap->origMap->north = last_scale_trans.orig_data_y_max; + } basemap->Reset(); } - - TemplateCanvas::ResetShapes(); + last_scale_trans.Reset(); + is_pan_zoom = false; + ResetBrushing(); + SetMouseMode(select); + isResize = true; } void MapCanvas::ZoomShapes(bool is_zoomin) { - if (sel2.x == 0 && sel2.y==0) + if (sel2.x == 0 && sel2.y==0) { return; - + } if (faded_layer_bm) { delete faded_layer_bm; faded_layer_bm = NULL; } if (isDrawBasemap) { - basemap->Zoom(is_zoomin, sel2.x, sel2.y, sel1.x, sel1.y); - ResizeSelectableShps(); - + bool zoom_ok = basemap->Zoom(is_zoomin, sel2.x, sel2.y, sel1.x, sel1.y); + if (zoom_ok) { + ResizeSelectableShps(); + } return; } @@ -308,26 +597,19 @@ void MapCanvas::OnIdle(wxIdleEvent& event) { if (isResize) { isResize = false; - int cs_w=0, cs_h=0; GetClientSize(&cs_w, &cs_h); - last_scale_trans.SetView(cs_w, cs_h); - resizeLayerBms(cs_w, cs_h); - if (isDrawBasemap) { - if (basemap == 0) + if (basemap == NULL) InitBasemap(); if (basemap) basemap->ResizeScreen(cs_w, cs_h); } - ResizeSelectableShps(); - event.RequestMore(); // render continuously, not only once on idle } - if (!layer2_valid || !layer1_valid || !layer0_valid || (isDrawBasemap && !layerbase_valid) ) { @@ -336,62 +618,123 @@ void MapCanvas::OnIdle(wxIdleEvent& event) } } +void MapCanvas::AddMapLayer(wxString name, BackgroundMapLayer* map_layer, bool is_hide) +{ + // geometries: projection is matched to current map + if (map_layer) { + map_layer->SetHide(is_hide); + bool added = false; + for (int i=0; iGetName() == map_layer->GetName()) { + added = true; + } + } + if (!added) { + for (int i=0; iGetName() == map_layer->GetName()) { + added = true; + } + } + } + if (!added) { + // project makes sure no overwrite here + bg_maps.push_back(map_layer); + } else { + // if already loaded before, just show it + map_layer->SetHide(false); + } + full_map_redraw_needed = true; + PopulateCanvas(); + Refresh(); + maplayer_state->notifyObservers(this); + } +} + void MapCanvas::ResizeSelectableShps(int virtual_scrn_w, int virtual_scrn_h) { - if (isDrawBasemap) { if ( virtual_scrn_w > 0 && virtual_scrn_h> 0) { basemap->ResizeScreen(virtual_scrn_w, virtual_scrn_h); } - BOOST_FOREACH( GdaShape* ms, background_shps ) { if (ms) ms->projectToBasemap(basemap); } - BOOST_FOREACH( GdaShape* ms, selectable_shps ) { + BOOST_FOREACH( GdaShape* ms, foreground_shps ) { if (ms) ms->projectToBasemap(basemap); } - BOOST_FOREACH( GdaShape* ms, foreground_shps ) { + BOOST_FOREACH( GdaShape* ms, background_maps ) { if (ms) ms->projectToBasemap(basemap); } - + BOOST_FOREACH( GdaShape* ms, foreground_maps ) { + if (ms) + ms->projectToBasemap(basemap); + } + BOOST_FOREACH( GdaShape* ms, selectable_shps ) { + if (ms) + ms->projectToBasemap(basemap); + } + if (!w_graph.empty() && display_weights_graph && boost::uuids::nil_uuid() != weights_id) { + // this is for resizing window with basemap + connectivity graph + for (int i=0; iprojectToBasemap(basemap); + } + } layerbase_valid = false; + } else { + if (virtual_scrn_w <= 0 && virtual_scrn_h <=0 ) { + GetClientSize(&virtual_scrn_w, &virtual_scrn_h); + } + // view: extent, margins, width, height + last_scale_trans.SetView(virtual_scrn_w, virtual_scrn_h); + + if (last_scale_trans.IsValid()) { + BOOST_FOREACH( GdaShape* ms, background_shps ) { + if (ms) ms->applyScaleTrans(last_scale_trans); + } + BOOST_FOREACH( GdaShape* ms, foreground_shps ) { + if (ms) ms->applyScaleTrans(last_scale_trans); + } + BOOST_FOREACH( GdaShape* ms, background_maps ) { + if (ms) ms->applyScaleTrans(last_scale_trans); + } + BOOST_FOREACH( GdaShape* ms, foreground_maps ) { + if (ms) ms->applyScaleTrans(last_scale_trans); + } + BOOST_FOREACH( GdaShape* ms, selectable_shps ) { + if (ms) ms->applyScaleTrans(last_scale_trans); + } + } layer0_valid = false; - layer1_valid = false; - layer2_valid = false; - return; } - - TemplateCanvas::ResizeSelectableShps(virtual_scrn_w, virtual_scrn_h); + ResetFadedLayer(); } bool MapCanvas::InitBasemap() { - if (basemap == 0) { + if (basemap == NULL) { wxSize sz = GetClientSize(); int screenW = sz.GetWidth(); int screenH = sz.GetHeight(); - OGRCoordinateTransformation *poCT = NULL; if (project->sourceSR != NULL) { int nGCS = project->sourceSR->GetEPSGGeogCS(); //if (nGCS != 4326) { - OGRSpatialReference destSR; - destSR.importFromEPSG(4326); - poCT = OGRCreateCoordinateTransformation(project->sourceSR, - &destSR); //} + OGRSpatialReference destSR; + destSR.importFromEPSG(4326); + poCT = OGRCreateCoordinateTransformation(project->sourceSR,&destSR); } - GDA::Screen* screen = new GDA::Screen(screenW, screenH); - double shps_orig_ymax = last_scale_trans.orig_data_y_max; - double shps_orig_xmin = last_scale_trans.orig_data_x_min; - double shps_orig_ymin = last_scale_trans.orig_data_y_min; - double shps_orig_xmax = last_scale_trans.orig_data_x_max; + double shps_orig_ymax = last_scale_trans.data_y_max; + double shps_orig_xmin = last_scale_trans.data_x_min; + double shps_orig_ymin = last_scale_trans.data_y_min; + double shps_orig_xmax = last_scale_trans.data_x_max; GDA::MapLayer* map = new GDA::MapLayer(shps_orig_ymax, shps_orig_xmin, shps_orig_ymin, @@ -409,43 +752,41 @@ bool MapCanvas::InitBasemap() } return false; } else { - basemap = new GDA::Basemap(screen, map, map_type, - GenUtils::GetBasemapCacheDir(), - poCT); + basemap = new GDA::Basemap(basemap_item, screen, map, GenUtils::GetBasemapCacheDir(), poCT, scale_factor); } } return true; } -bool MapCanvas::DrawBasemap(bool flag, int map_type_) +bool MapCanvas::DrawBasemap(bool flag, BasemapItem& _basemap_item) { - ResetShapes(); ResetBrushing(); - map_type = map_type_; isDrawBasemap = flag; - + basemap_item = _basemap_item; wxSize sz = GetClientSize(); int screenW = sz.GetWidth(); int screenH = sz.GetHeight(); - if (isDrawBasemap == true) { - if ( basemap == 0 && InitBasemap() == false ) { + if ( basemap == NULL && InitBasemap() == false ) { ResizeSelectableShps(); return false; } else { - basemap->SetupMapType(map_type); + basemap->SetupMapType(basemap_item); } } else { if ( basemap ) { - basemap->mapType=0; + basemap->basemap_item = basemap_item; + last_scale_trans.data_x_min = basemap->map->west; + last_scale_trans.data_x_max = basemap->map->east; + last_scale_trans.data_y_min = basemap->map->south; + last_scale_trans.data_y_max = basemap->map->north; + ResizeSelectableShps(); } } - layerbase_valid = false; layer0_valid = false; layer1_valid = false; layer2_valid = false; - ReDraw(); return true; } @@ -453,20 +794,21 @@ bool MapCanvas::DrawBasemap(bool flag, int map_type_) void MapCanvas::resizeLayerBms(int width, int height) { deleteLayerBms(); - int vs_w, vs_h; GetClientSize(&vs_w, &vs_h); - - if (vs_w <= 0) vs_w = 1; - if (vs_h <=0 ) vs_h = 1; - - basemap_bm = new wxBitmap(vs_w, vs_h, 32); - layerbase_valid = false; - + if (width > 0) vs_w = width; + if (height >0 ) vs_h = height; + basemap_bm = new wxBitmap(vs_w, vs_h, 32); layer0_bm = new wxBitmap(vs_w, vs_h, 32); layer1_bm = new wxBitmap(vs_w, vs_h, 32); layer2_bm = new wxBitmap(vs_w, vs_h, 32); - + if (enable_high_dpi_support) { + basemap_bm->CreateScaled(vs_w, vs_h, 32, scale_factor); + layer0_bm->CreateScaled(vs_w, vs_h, 32, scale_factor); + layer1_bm->CreateScaled(vs_w, vs_h, 32, scale_factor); + layer2_bm->CreateScaled(vs_w, vs_h, 32, scale_factor); + } + layerbase_valid = false; layer0_valid = false; layer1_valid = false; layer2_valid = false; @@ -474,22 +816,19 @@ void MapCanvas::resizeLayerBms(int width, int height) void MapCanvas::DrawLayers() { - if (!layerbase_valid && isDrawBasemap) + if (!layerbase_valid && isDrawBasemap) { DrawLayerBase(); - - if (!layer0_valid) + } + if (!layer0_valid) { DrawLayer0(); - + } if (!layer1_valid) { DrawLayer1(); } - if (!layer2_valid) { DrawLayer2(); } - wxWakeUpIdle(); - Refresh(); } @@ -511,209 +850,261 @@ void MapCanvas::DrawLayerBase() void MapCanvas::DrawLayer0() { + // draw basemap, background, and all other maps wxMemoryDC dc; - - if (isDrawBasemap || (highlight_state->GetTotalHighlighted()>0 && - GdaConst::use_cross_hatching == false)) + + if (isDrawBasemap) { // use a special color for mask transparency: 244, 243, 242c wxColour maskColor(MASK_R, MASK_G, MASK_B); wxBrush maskBrush(maskColor); dc.SetBackground(maskBrush); - } - - dc.SelectObject(*layer0_bm); - dc.Clear(); - - wxSize sz = dc.GetSize(); - + dc.SelectObject(*layer0_bm); + dc.Clear(); + } else { + dc.SelectObject(*layer0_bm); + dc.SetBackground(wxBrush(canvas_background_color)); + dc.Clear(); + } BOOST_FOREACH( GdaShape* shp, background_shps ) { shp->paintSelf(dc); } + BOOST_FOREACH( GdaShape* map, background_maps ) { + map->paintSelf(dc); + } DrawSelectableShapes_dc(dc); - + BOOST_FOREACH( GdaShape* map, foreground_maps ) { + map->paintSelf(dc); + } dc.SelectObject(wxNullBitmap); - layer0_valid = true; layer1_valid = false; } void MapCanvas::DrawLayer1() { + // draw highlight if (layer1_bm == NULL) return; - wxMemoryDC dc(*layer1_bm); dc.Clear(); - wxSize sz = dc.GetSize(); - if (isDrawBasemap) { dc.DrawBitmap(*basemap_bm,0,0); - } else { - dc.SetPen(canvas_background_color); - dc.SetBrush(canvas_background_color); - dc.DrawRectangle(wxPoint(0,0), sz); } - + TranslucentLayer0(dc); + dc.SelectObject(wxNullBitmap); + layer1_valid = true; + layer2_valid = false; +} + +void MapCanvas::DrawLayer2() +{ + // draw foreground + if (layer2_bm == NULL) + return; + wxMemoryDC dc; + dc.SelectObject(*layer2_bm); + dc.SetBackground(*wxWHITE_BRUSH); + dc.Clear(); + dc.DrawBitmap(*layer1_bm, 0, 0); + if (display_weights_graph && boost::uuids::nil_uuid() != weights_id && highlight_state->GetTotalHighlighted()==0) { + wxPen pen(graph_color, weights_graph_thickness); + for (int i=0; isetPen(pen); + w_graph[i]->setBrush(*wxTRANSPARENT_BRUSH); + } + } + BOOST_FOREACH( GdaShape* shp, foreground_shps ) { + shp->paintSelf(dc); + } + dc.SelectObject(wxNullBitmap); + layer2_valid = true; + if ( MapCanvas::has_thumbnail_saved == false) { + if (isDrawBasemap && layerbase_valid == false) { + return; + } + CallAfter(&MapCanvas::SaveThumbnail); + } + dc.SelectObject(wxNullBitmap); +} + +void MapCanvas::TranslucentLayer0(wxMemoryDC& dc) +{ + wxSize sz = dc.GetSize(); bool revert = GdaConst::transparency_highlighted < tran_unhighlighted; int alpha_value = 255; - bool mask_needed = false; - bool draw_highlight = highlight_state->GetTotalHighlighted() > 0; - - - if (isDrawBasemap) { - mask_needed = true; + bool mask_needed = false; + bool draw_highlight = highlight_state->GetTotalHighlighted() > 0; + if (isDrawBasemap) { + mask_needed = true; alpha_value = tran_unhighlighted; - } - + } if (draw_highlight && GdaConst::use_cross_hatching == false) { - mask_needed = true; + mask_needed = true; alpha_value = revert ? GdaConst::transparency_highlighted : tran_unhighlighted; - } - - if (mask_needed) - { + } + if (mask_needed) + { if (faded_layer_bm == NULL) { - wxImage image = layer0_bm->ConvertToImage(); - if (!image.HasAlpha()) { - image.InitAlpha(); - } - - unsigned char *alpha=image.GetAlpha(); - unsigned char* pixel_data = image.GetData(); - int n_pixel = image.GetWidth() * image.GetHeight(); - - int pos = 0; - for (int i=0; i< n_pixel; i++) { - // check rgb - pos = i * 3; - if (pixel_data[pos] == MASK_R && - pixel_data[pos+1] == MASK_G && - pixel_data[pos+2] == MASK_B) - { - alpha[i] = 0; - } else { - if (alpha[i] !=0 ) alpha[i] = alpha_value; - } - } + wxImage image = layer0_bm->ConvertToImage(); + if (!image.HasAlpha()) { + image.InitAlpha(); + } + unsigned char *alpha=image.GetAlpha(); + unsigned char* pixel_data = image.GetData(); + int n_pixel = image.GetWidth() * image.GetHeight(); + int pos = 0; + for (int i=0; i< n_pixel; i++) { + // check rgb + pos = i * 3; + if (pixel_data[pos] == MASK_R && + pixel_data[pos+1] == MASK_G && + pixel_data[pos+2] == MASK_B) + { + alpha[i] = 0; + } else { + if (alpha[i] !=0 ) alpha[i] = alpha_value; + } + } faded_layer_bm = new wxBitmap(image); } - dc.DrawBitmap(*faded_layer_bm,0,0); - - int hl_alpha_value = revert ? tran_unhighlighted : GdaConst::transparency_highlighted; - - if ( draw_highlight ) { + if (enable_high_dpi_support && scale_factor != 1) { + dc.SetUserScale(1/scale_factor, 1/scale_factor); + dc.DrawBitmap(*faded_layer_bm,0,0); + dc.SetUserScale(1.0, 1.0); + } else { + dc.DrawBitmap(*faded_layer_bm,0,0); + } + int hl_alpha_value = revert ? tran_unhighlighted : GdaConst::transparency_highlighted; + if ( draw_highlight ) { if ( hl_alpha_value == 255 || GdaConst::use_cross_hatching) { - DrawHighlightedShapes(dc, revert); - } else { - // draw a highlight with transparency - //wxGraphicsRenderer* renderer = wxGraphicsRenderer::GetDefaultRenderer(); - //wxGraphicsRenderer* renderer = wxGraphicsRenderer::GetDirect2DRenderer(); - //wxGraphicsContext* context = renderer->CreateContext (dc); - //helper_DrawSelectableShapes_gc(*context, true, false, false, hl_alpha_value); - wxBitmap map_hl_bm(sz.GetWidth(), sz.GetHeight()); - wxMemoryDC _dc; - - // use a special color for mask transparency: 244, 243, 242c - wxColour maskColor(MASK_R, MASK_G, MASK_B); - wxBrush maskBrush(maskColor); - _dc.SetBackground(maskBrush); - - _dc.SelectObject(map_hl_bm); - _dc.Clear(); - - DrawHighlightedShapes(_dc, revert); - - _dc.SelectObject(wxNullBitmap); - - wxImage image = map_hl_bm.ConvertToImage(); - if (!image.HasAlpha()) { - image.InitAlpha(); - } - unsigned char* alpha_vals = image.GetAlpha(); - unsigned char* pixel_data = image.GetData(); - int n_pixel = image.GetWidth() * image.GetHeight(); - - int pos = 0; - for (int i=0; i< n_pixel; i++) { - // check rgb - pos = i * 3; - if (pixel_data[pos] == MASK_R && - pixel_data[pos+1] == MASK_G && - pixel_data[pos+2] == MASK_B) - { - alpha_vals[i] = 0; - } else { - if (alpha_vals[i] !=0) alpha_vals[i] = hl_alpha_value; - } - } - - wxBitmap bm(image); - dc.DrawBitmap(bm,0,0); - } - } - - } else { + DrawHighlightedShapes(dc, revert); + } else { + // draw a highlight with transparency + wxBitmap map_hl_bm(sz.GetWidth(), sz.GetHeight()); + wxMemoryDC _dc; + // use a special color for mask transparency: 244, 243, 242c + wxColour maskColor(MASK_R, MASK_G, MASK_B); + wxBrush maskBrush(maskColor); + _dc.SetBackground(maskBrush); + _dc.SelectObject(map_hl_bm); + _dc.Clear(); + DrawHighlightedShapes(_dc, revert); + _dc.SelectObject(wxNullBitmap); + wxImage image = map_hl_bm.ConvertToImage(); + if (!image.HasAlpha()) { + image.InitAlpha(); + } + unsigned char* alpha_vals = image.GetAlpha(); + unsigned char* pixel_data = image.GetData(); + int n_pixel = image.GetWidth() * image.GetHeight(); + int pos = 0; + for (int i=0; i< n_pixel; i++) { + // check rgb + pos = i * 3; + if (pixel_data[pos] == MASK_R && + pixel_data[pos+1] == MASK_G && + pixel_data[pos+2] == MASK_B) + { + alpha_vals[i] = 0; + } else { + if (alpha_vals[i] !=0) alpha_vals[i] = hl_alpha_value; + } + } + wxBitmap bm(image); + dc.DrawBitmap(bm,0,0); + } + } + } else { if (faded_layer_bm) { - DrawLayer0(); ResetFadedLayer(); } - dc.DrawBitmap(*layer0_bm, 0, 0); + dc.DrawBitmap(*layer0_bm, 0, 0); if (GdaConst::use_cross_hatching == true) { DrawHighlightedShapes(dc, revert); } - } + } +} - dc.SelectObject(wxNullBitmap); - layer1_valid = true; - layer2_valid = false; +void MapCanvas::SetWeightsId(boost::uuids::uuid id) +{ + weights_id = id; + + bool show_graph = display_weights_graph && boost::uuids::nil_uuid() != weights_id && !w_graph.empty(); + + if (show_graph || display_neighbors) { + full_map_redraw_needed = true; + PopulateCanvas(); + } } // draw highlighted selectable shapes void MapCanvas::DrawHighlightedShapes(wxMemoryDC &dc, bool revert) { - if (selectable_shps.size() == 0) - return; + if ( !fg_maps.empty() ) { + // multi-layer highlight: using top layer + BackgroundMapLayer* ml = fg_maps[0]; + if (ml && ml->IsHide() == false) { + ml->DrawHighlight(dc, this); + } + } else { + DrawHighlight(dc, this); + //DrawHighlighted(dc, revert); + } + +} + +void MapCanvas::SetHighlight(int idx) +{ + vector& hs = highlight_state->GetHighlight(); + if (hs.size() > idx) { + hs[idx] = true; + } +} + +void MapCanvas::DrawHighlighted(wxMemoryDC &dc, bool revert) +{ + if (selectable_shps.size() == 0) { + return; + } + vector& hs = highlight_state->GetHighlight(); if (use_category_brushes) { bool highlight_only = true; DrawSelectableShapes_dc(dc, highlight_only, revert, GdaConst::use_cross_hatching); } else { - vector& hs = GetSelBitVec(); for (int i=0, iend=selectable_shps.size(); ipaintSelf(dc); } } } -} - -void MapCanvas::DrawLayer2() -{ - if (layer2_bm == NULL) - return; - - wxMemoryDC dc(*layer2_bm); - dc.Clear(); - - dc.DrawBitmap(*layer1_bm, 0, 0); - - BOOST_FOREACH( GdaShape* shp, foreground_shps ) { - shp->paintSelf(dc); + // highlight connectivity objects and graphs + bool show_graph = display_weights_graph && boost::uuids::nil_uuid() != weights_id && !w_graph.empty(); + if (show_graph || display_neighbors) { + // draw neighbors of selection if needed + WeightsManInterface* w_man_int = project->GetWManInt(); + GalWeight* gal_weights = w_man_int->GetGal(weights_id); + AddNeighborsToSelection(gal_weights, dc); } - - dc.SelectObject(wxNullBitmap); - - layer2_valid = true; - - if ( MapCanvas::has_thumbnail_saved == false) { - if (isDrawBasemap && layerbase_valid == false) { - return; - } - CallAfter(&MapCanvas::SaveThumbnail); + if (show_graph) { + // draw connectivity graph if needed + const vector& c = project->GetMeanCenters(); + if (highlight_state->GetTotalHighlighted() >0) { + wxPen pen(graph_color, weights_graph_thickness); + for (int i=0; ifrom]) { + e->setPen(pen); + e->paintSelf(dc); + } else { + e->setPen(*wxTRANSPARENT_PEN); + } + } + } } } @@ -746,28 +1137,22 @@ void MapCanvas::SaveThumbnail() void MapCanvas::DrawSelectableShapes_dc(wxMemoryDC &_dc, bool hl_only, bool revert, bool use_crosshatch) { + if (!display_map_with_graph) + return; + vector& hs = highlight_state->GetHighlight(); #ifdef __WXOSX__ - wxGraphicsRenderer* renderer = wxGraphicsRenderer::GetDefaultRenderer(); - wxGraphicsContext* gc= renderer->CreateContext (_dc); - - helper_DrawSelectableShapes_gc(*gc, hl_only, revert, use_crosshatch); + wxGCDC dc(_dc); + helper_DrawSelectableShapes_dc(dc, hs, hl_only, revert, use_crosshatch); #else - helper_DrawSelectableShapes_dc(_dc, hl_only, revert, use_crosshatch); - + helper_DrawSelectableShapes_dc(_dc, hs, hl_only, revert, use_crosshatch); #endif } -int MapCanvas::GetBasemapType() -{ - if (basemap) - return basemap->mapType; - return 0; -} - void MapCanvas::CleanBasemapCache() { - if (basemap) + if (basemap) { basemap->CleanCache(); + } } void MapCanvas::DisplayRightClickMenu(const wxPoint& pos) @@ -777,18 +1162,12 @@ void MapCanvas::DisplayRightClickMenu(const wxPoint& pos) if (MapFrame* f = dynamic_cast(template_frame)) { f->OnActivate(ae); } - wxMenu* optMenu = wxXmlResource::Get()-> - LoadMenu("ID_MAP_NEW_VIEW_MENU_OPTIONS"); + wxMenu* optMenu = wxXmlResource::Get()->LoadMenu("ID_MAP_NEW_VIEW_MENU_OPTIONS"); AddTimeVariantOptionsToMenu(optMenu); - TemplateCanvas::AppendCustomCategories(optMenu, - project->GetCatClassifManager()); + TemplateCanvas::AppendCustomCategories(optMenu, project->GetCatClassifManager()); SetCheckMarks(optMenu); - GeneralWxUtils::EnableMenuItem(optMenu, XRCID("ID_SAVE_CATEGORIES"), GetCcType() != CatClassification::no_theme); - - - if (template_frame) { template_frame->UpdateContextMenuItems(optMenu); template_frame->PopupMenu(optMenu, pos + GetPosition()); @@ -798,23 +1177,193 @@ void MapCanvas::DisplayRightClickMenu(const wxPoint& pos) void MapCanvas::AddTimeVariantOptionsToMenu(wxMenu* menu) { - wxLogMessage("MapCanvas::AddTimeVariantOptionsToMenu()"); - if (!is_any_time_variant) return; + //wxLogMessage("MapCanvas::AddTimeVariantOptionsToMenu()"); + if (!is_any_time_variant){ + return; + } wxMenu* menu1 = new wxMenu(wxEmptyString); for (size_t i=0, sz=GetNumVars(); iAppendCheckItem(GdaConst::ID_TIME_SYNC_VAR1+i, s, s); + wxString s = wxString::Format(_("Synchronize %s with Time Control"), var_info[i].name); + wxMenuItem* mi = menu1->AppendCheckItem(GdaConst::ID_TIME_SYNC_VAR1+i, s, s); mi->Check(var_info[i].sync_with_global_time); } } menu->AppendSeparator(); - menu->Append(wxID_ANY, "Time Variable Options", menu1, - "Time Variable Options"); + menu->Append(wxID_ANY, _("Time Variable Options"), menu1, _("Time Variable Options")); +} + + +void MapCanvas::RenderToDC(wxDC &dc, int w, int h) +{ + int screen_w = GetClientSize().GetWidth(); + int screen_h = GetClientSize().GetHeight(); + double basemap_scale = (double) w / screen_w; + double old_scale = scale_factor; + scale_factor = 1.0; + + double old_point_radius = point_radius; + if (GetShapeType() == points) { + point_radius = basemap_scale * point_radius; + } + deleteLayerBms(); + + layer0_bm = new wxBitmap(w, h, 32); + layer1_bm = new wxBitmap(w, h, 32); + layer2_bm = new wxBitmap(w, h, 32); + faded_layer_bm = NULL; + layer0_valid = false; + layer1_valid = false; + layer2_valid = false; + + if (isDrawBasemap) { + GDA::Screen *screen = NULL; + if (print_detailed_basemap) { + basemap_bm = new wxBitmap(w, h, 32); + basemap_scale = 1.0; + last_scale_trans.SetView(w, h); + screen = new GDA::Screen(w, h); + } else { + // scaled basemap + basemap_bm = new wxBitmap; + basemap_bm->CreateScaled(screen_w, screen_h, 32, basemap_scale); + //last_scale_trans.SetView(screen_w, screen_h); + screen = new GDA::Screen(screen_w, screen_h); + } + OGRCoordinateTransformation *poCT = NULL; + if (project->sourceSR != NULL) { + OGRSpatialReference destSR; + destSR.importFromEPSG(4326); + poCT = OGRCreateCoordinateTransformation(project->sourceSR, &destSR); + } + double shps_orig_ymax = last_scale_trans.orig_data_y_max; + double shps_orig_xmin = last_scale_trans.orig_data_x_min; + double shps_orig_ymin = last_scale_trans.orig_data_y_min; + double shps_orig_xmax = last_scale_trans.orig_data_x_max; + GDA::MapLayer *map = new GDA::MapLayer(shps_orig_ymax, shps_orig_xmin, shps_orig_ymin, shps_orig_xmax, poCT); + if (poCT && map->IsWGS84Valid()) { + if (print_detailed_basemap) { + basemap->ResizeScreen(w, h); + basemap->Refresh(); + } + BOOST_FOREACH( GdaShape* ms, background_maps ) { + if (ms) ms->projectToBasemap(basemap, basemap_scale); + } + BOOST_FOREACH( GdaShape* ms, foreground_maps ) { + if (ms) ms->projectToBasemap(basemap, basemap_scale); + } + BOOST_FOREACH( GdaShape* ms, background_shps ) { + if (ms) ms->projectToBasemap(basemap, basemap_scale); + } + BOOST_FOREACH( GdaShape* ms, selectable_shps ) { + if (ms) ms->projectToBasemap(basemap, basemap_scale); + } + BOOST_FOREACH( GdaShape* ms, foreground_shps ) { + if (ms) ms->projectToBasemap(basemap, basemap_scale); + } + if (!w_graph.empty() && display_weights_graph && boost::uuids::nil_uuid() != weights_id) { + for (int i=0; iprojectToBasemap(basemap, basemap_scale); + } + } + basemap->Draw(basemap_bm); + } + } else { + last_scale_trans.SetView(w, h); + last_scale_trans.top_margin *= basemap_scale; + last_scale_trans.left_margin *= basemap_scale; + last_scale_trans.right_margin *= basemap_scale; + last_scale_trans.bottom_margin *= basemap_scale; + ResizeSelectableShps(w, h); + } + + wxMemoryDC layer0_dc(*layer0_bm); + layer0_dc.Clear(); + if (isDrawBasemap || (highlight_state->GetTotalHighlighted()>0 && + GdaConst::use_cross_hatching == false)) + { + // use a special color for mask transparency: 244, 243, 242c + wxColour maskColor(MASK_R, MASK_G, MASK_B); + wxBrush maskBrush(maskColor); + layer0_dc.SetBackground(maskBrush); + layer0_dc.SelectObject(*layer0_bm); + layer0_dc.Clear(); + } else { + layer0_dc.SetBackground(wxBrush(canvas_background_color)); + layer0_dc.Clear(); + } + BOOST_FOREACH( GdaShape* shp, background_shps ) { + shp->paintSelf(layer0_dc); + } + BOOST_FOREACH( GdaShape* map, background_maps ) { + map->paintSelf(layer0_dc); + } + + vector& hs = highlight_state->GetHighlight(); + helper_DrawSelectableShapes_dc(layer0_dc, hs, false, false, false, true); + + BOOST_FOREACH( GdaShape* map, foreground_maps ) { + map->paintSelf(layer0_dc); + } + layer0_dc.SelectObject(wxNullBitmap); + + wxMemoryDC layer1_dc(*layer1_bm); + layer1_dc.Clear(); + if (isDrawBasemap) { + wxImage im = basemap_bm->ConvertToImage(); +#ifdef __WIN32__ + im.Rescale(w*basemap_scale, h*basemap_scale, wxIMAGE_QUALITY_HIGH); +#endif + layer1_dc.DrawBitmap(im, 0, 0); + } + //layer1_dc.SetUserScale(1.0,1.0); + + TranslucentLayer0(layer1_dc); + layer1_dc.SelectObject(wxNullBitmap); + + layer1_valid = true; + layer2_valid = false; + + DrawLayer2(); + + dc.DrawBitmap(*layer2_bm, 0, 0); + // reset + point_radius = old_point_radius; + scale_factor = old_scale; + if (!isDrawBasemap) { + last_scale_trans.SetMargin(); + ResizeSelectableShps(); + } + ReDraw(); +} + +void MapCanvas::RenderToSVG(wxDC& dc, int w, int h, int map_w, int map_h, int offset_x, int offset_y) +{ + ResizeSelectableShps(w, h); + BOOST_FOREACH( GdaShape* shp, background_shps ) { + shp->paintSelf(dc); + } + BOOST_FOREACH( GdaShape* shp, background_maps ) { + shp->paintSelf(dc); + } + + vector& hs = highlight_state->GetHighlight(); + helper_DrawSelectableShapes_dc(dc, hs, false, false); + + BOOST_FOREACH( GdaShape* shp, foreground_maps ) { + shp->paintSelf(dc); + } + BOOST_FOREACH( GdaShape* shp, foreground_shps ) { + shp->paintSelf(dc); + } + ResizeSelectableShps(); } +wxBitmap* MapCanvas::GetPrintLayer() +{ + return layer2_bm; +} void MapCanvas::SetCheckMarks(wxMenu* menu) { @@ -826,38 +1375,40 @@ void MapCanvas::SetCheckMarks(wxMenu* menu) GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_MAPANALYSIS_THEMELESS"), GetCcType() == CatClassification::no_theme); - // since XRCID is a macro, we can't make this into a loop - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_QUANTILE_1"), - (GetCcType() == CatClassification::quantile) - && GetNumCats() == 1); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_QUANTILE_2"), - (GetCcType() == CatClassification::quantile) - && GetNumCats() == 2); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_QUANTILE_3"), - (GetCcType() == CatClassification::quantile) - && GetNumCats() == 3); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_QUANTILE_4"), - (GetCcType() == CatClassification::quantile) - && GetNumCats() == 4); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_QUANTILE_5"), - (GetCcType() == CatClassification::quantile) - && GetNumCats() == 5); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_QUANTILE_6"), - (GetCcType() == CatClassification::quantile) - && GetNumCats() == 6); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_QUANTILE_7"), - (GetCcType() == CatClassification::quantile) - && GetNumCats() == 7); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_QUANTILE_8"), - (GetCcType() == CatClassification::quantile) - && GetNumCats() == 8); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_QUANTILE_9"), - (GetCcType() == CatClassification::quantile) - && GetNumCats() == 9); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_QUANTILE_10"), - (GetCcType() == CatClassification::quantile) - && GetNumCats() == 10); - + //GeneralWxUtils::EnableMenuItem(menu, XRCID("ID_MAPANALYSIS_THEMELESS"), !IS_VAR_STRING); + GeneralWxUtils::EnableMenuItem(menu, XRCID("ID_QUANTILE_SUBMENU"), !IS_VAR_STRING); + GeneralWxUtils::EnableMenuItem(menu, XRCID("ID_MAPANALYSIS_CHOROPLETH_PERCENTILE"), !IS_VAR_STRING); + GeneralWxUtils::EnableMenuItem(menu, XRCID("ID_MAPANALYSIS_HINGE_15"), !IS_VAR_STRING); + GeneralWxUtils::EnableMenuItem(menu, XRCID("ID_MAPANALYSIS_HINGE_30"), !IS_VAR_STRING); + GeneralWxUtils::EnableMenuItem(menu, XRCID("ID_MAPANALYSIS_CHOROPLETH_STDDEV"), !IS_VAR_STRING); + //GeneralWxUtils::EnableMenuItem(menu, XRCID("ID_COND_VERT_UNIQUE_VALUES"), VERT_VAR_NUM); + GeneralWxUtils::EnableMenuItem(menu, XRCID("ID_EQUAL_INTERVALS_SUBMENU"), !IS_VAR_STRING); + GeneralWxUtils::EnableMenuItem(menu, XRCID("ID_NATURAL_BREAKS_SUBMENU"), !IS_VAR_STRING); + GeneralWxUtils::EnableMenuItem(menu, XRCID("ID_NEW_CUSTOM_CAT_CLASSIF_A"), !IS_VAR_STRING); + + CatClassifManager* ccm = project->GetCatClassifManager(); + vector titles; + ccm->GetTitles(titles); + for (size_t j=0; jGetProjectTitle(); + s << _("Map") << " - " << project->GetProjectTitle(); } else if (GetCcType() == CatClassification::custom) { s << cat_classif_def.title << ": " << v; } else { @@ -1006,9 +1524,21 @@ wxString MapCanvas::GetCanvasTitle() return s; } +wxString MapCanvas::GetVariableNames() +{ + //wxLogMessage("MapCanvas::GetCanvasTitle()"); + wxString v; + if (GetNumVars() == 1) + v << GetNameWithTime(0); + else if (GetNumVars() == 2) { + v << GetNameWithTime(0) << " / " << GetNameWithTime(1); + } + return v; +} + wxString MapCanvas::GetNameWithTime(int var) { - wxLogMessage("MapCanvas::GetNameWithTime()"); + //wxLogMessage("MapCanvas::GetNameWithTime()"); if (var < 0 || var >= GetNumVars()) return wxEmptyString; wxString s(var_info[var].name); if (var_info[var].is_time_variant) { @@ -1030,10 +1560,10 @@ void MapCanvas::OnSaveCategories() if (data_undef.size()>0) { wxString label; - label << t_name << " Categories"; + label << t_name << _(" Categories"); wxString title; - title << "Save " << label; - std::vector undefs(num_obs); + title << _("Save ") << label; + vector undefs(num_obs); for (int t=0; t > var_undefs(num_time_vals); + vector > var_undefs; if (var_info.size() == 0) { VariableSettingsDlg dlg(project, VariableSettingsDlg::univariate); @@ -1061,31 +1591,41 @@ void MapCanvas::NewCustomCatClassif() table_int->GetColData(dlg.col_ids[0], data[0]); table_int->GetColUndefined(dlg.col_ids[0], data_undef[0]); - - VarInfoAttributeChange(); - cat_var_sorted.resize(num_time_vals); - - for (int t=0; t temp_cat_labels; // will be ignored + vector temp_cat_labels; // will be ignored CatClassification::SetBreakPoints(cat_classif_def.breaks, temp_cat_labels, cat_var_sorted[var_info[0].time], @@ -1101,8 +1641,9 @@ void MapCanvas::NewCustomCatClassif() int tm = var_info[0].time; cat_classif_def.assoc_db_fld_name = table_int->GetColName(col, tm); } - - CatClassifFrame* ccf = GdaFrame::GetGdaFrame()->GetCatClassifFrame(this->useScientificNotation); + + GdaFrame* gda_frame = GdaFrame::GetGdaFrame(); + CatClassifFrame* ccf = gda_frame->GetCatClassifFrame(this->useScientificNotation); if (!ccf) return; @@ -1110,7 +1651,6 @@ void MapCanvas::NewCustomCatClassif() CatClassifState* ccs = ccf->PromptNew(cat_classif_def, "", var_info[0].name, var_info[0].time); - if (!ccs) return; @@ -1126,16 +1666,14 @@ void MapCanvas::NewCustomCatClassif() if (template_frame) { template_frame->UpdateTitle(); if (template_frame->GetTemplateLegend()) { - template_frame->GetTemplateLegend()->Refresh(); + template_frame->GetTemplateLegend()->Recreate(); } } } /** ChangeMapType should always have var_info and col_ids passed in to it - when needed. */ - -/** This method initializes data array according to values in var_info - and col_ids. It calls CreateAndUpdateCategories which does all of the + when needed. This method initializes data array according to values in var_info + and col_ids. It calls CreateAndUpdateCategories which does all of the category classification including any needed data smoothing. */ bool MapCanvas::ChangeMapType(CatClassification::CatClassifType new_map_theme, @@ -1143,23 +1681,24 @@ MapCanvas::ChangeMapType(CatClassification::CatClassifType new_map_theme, int num_categories_s, boost::uuids::uuid weights_id_s, bool use_new_var_info_and_col_ids, - const std::vector& new_var_info, - const std::vector& new_col_ids, + const vector& new_var_info, + const vector& new_col_ids, const wxString& custom_classif_title) { wxLogMessage("MapCanvas::ChangeMapType()"); - // We only ask for variables when changing from no_theme or - // smoothed (with theme). + // We only ask for variables when changing from no_theme or smoothed (with theme). num_categories = num_categories_s; - weights_id = weights_id_s; + if (!weights_id_s.is_nil()) { + weights_id = weights_id_s; + } if (new_map_theme == CatClassification::custom) { new_map_smoothing = no_smoothing; } if (smoothing_type != no_smoothing && new_map_smoothing == no_smoothing) { - wxString msg = _T("The new theme chosen will no longer include rates smoothing. Please use the Rates submenu to choose a theme with rates again."); - wxMessageDialog dlg (this, msg, "Information", wxOK | wxICON_INFORMATION); + wxString msg = _("The new theme chosen will no longer include rates smoothing. Please use the Rates submenu to choose a theme with rates again."); + wxMessageDialog dlg (this, msg, _("Information"), wxOK | wxICON_INFORMATION); dlg.ShowModal(); return false; } @@ -1208,13 +1747,18 @@ MapCanvas::ChangeMapType(CatClassification::CatClassifType new_map_theme, return false; var_info.resize(1); data.resize(1); + s_data.resize(1); data_undef.resize(1); var_info[0] = new_var_info[0]; if (template_frame) { template_frame->AddGroupDependancy(var_info[0].name); } - table_int->GetColData(new_col_ids[0], data[0]); + GdaConst::FieldType f_type = table_int->GetColType(new_col_ids[0]); + IS_VAR_STRING = f_type == GdaConst::string_type; + + if (IS_VAR_STRING) table_int->GetColData(new_col_ids[0], s_data[0]); + else table_int->GetColData(new_col_ids[0], data[0]); table_int->GetColUndefined(new_col_ids[0], data_undef[0]); } else if (num_vars == 1) { @@ -1223,7 +1767,12 @@ MapCanvas::ChangeMapType(CatClassification::CatClassifType new_map_theme, if (template_frame) { template_frame->AddGroupDependancy(var_info[0].name); } - table_int->GetColData(new_col_ids[0], data[0]); + GdaConst::FieldType f_type = table_int->GetColType(new_col_ids[0]); + IS_VAR_STRING = f_type == GdaConst::string_type; + + if (IS_VAR_STRING) table_int->GetColData(new_col_ids[0], s_data[0]); + else table_int->GetColData(new_col_ids[0], data[0]); + table_int->GetColUndefined(new_col_ids[0], data_undef[0]); } // else reuse current variable settings and values @@ -1249,7 +1798,10 @@ MapCanvas::ChangeMapType(CatClassification::CatClassifType new_map_theme, // new_map_smoothing are assumed to be valid. if (!use_new_var_info_and_col_ids) return false; - + + // for rates, the variable has to be numeric + IS_VAR_STRING = false; + var_info.clear(); data.clear(); var_info.resize(2); @@ -1280,27 +1832,307 @@ MapCanvas::ChangeMapType(CatClassification::CatClassifType new_map_theme, smoothing_type = new_map_smoothing; VarInfoAttributeChange(); CreateAndUpdateCategories(); + + if (display_weights_graph && !w_graph.empty()) { + full_map_redraw_needed = true; + } PopulateCanvas(); TemplateLegend* legend = template_frame->GetTemplateLegend(); if (legend != NULL ) { legend->isDragDropAllowed = new_map_theme == CatClassification::unique_values; } - return true; + + CallAfter(&MapCanvas::show_empty_shps_msgbox); + + return true; +} + +void MapCanvas::show_empty_shps_msgbox() +{ + if (!has_shown_empty_shps_msg && !empty_shps_ids.empty()) { + CreateAndUpdateCategories(); + if (template_frame) { + if (template_frame->GetTemplateLegend()) { + template_frame->GetTemplateLegend()->Recreate(); + } + } + wxString msg = _("These are the row numbers of the records without location information."); + wxString empty_shps_msg = _("row:\n"); + + for (int i=0; iShow(true); + has_shown_empty_shps_msg = true; + } +} + +void MapCanvas::update(CatClassifState* o) +{ + wxLogMessage("In MapCanvas::update(CatClassifState*)"); + cat_classif_def = o->GetCatClassif(); + CreateAndUpdateCategories(); + PopulateCanvas(); + if (template_frame) { + template_frame->UpdateTitle(); + if (template_frame->GetTemplateLegend()) { + template_frame->GetTemplateLegend()->Recreate(); + } + } +} + +vector MapCanvas::GetLayerNames() +{ + vector names; + for (int i=0; iGetName(); + names.push_back(name); + } + for (int i=0; iGetName(); + names.push_back(name); + } + return names; +} + +void MapCanvas::update(MapLayerState* o) +{ + wxLogMessage("In MapCanvas::update(MapLayerState*)"); + vector local_names = GetLayerNames(); + + // if name not in project, remove + for (int i=0; ibg_maps.find(name) == project->bg_maps.end() && + project->fg_maps.find(name) == project->fg_maps.end()) { + int del_idx = -1; + BackgroundMapLayer* ml = NULL; + for (int i=0; iGetName() == name) { + delete ml; + del_idx = i; + break; + } + } + if (del_idx >= 0) { + bg_maps.erase(bg_maps.begin() + del_idx); + } else { + for (int i=0; iGetName() == name) { + delete ml; + del_idx = i; + break; + } + } + if (del_idx >=0) { + fg_maps.erase(fg_maps.begin() + del_idx); + } + } + full_map_redraw_needed = true; + PopulateCanvas(); + } + } + + // if project name not in local_names, add + vector proj_names = project->GetLayerNames(); + for (int i=0; iGetName() == name) { + found = true; + break; + } + } + if (found == false) { + for (int i=0; iGetName() == name) { + found = true; + break; + } + } + } + if (found == false) { + // add + bg_maps.push_back(project->GetMapLayer(name)->Clone()); + } + } + + //DisplayMapLayers(); + if (template_frame) { + MapFrame* m = dynamic_cast(template_frame); + if (m) m->UpdateMapLayer(); + } +} + +void MapCanvas::RemoveLayer(wxString name) +{ + //project->RemoveLayer(name); + + int del_idx = -1; + BackgroundMapLayer* ml = NULL; + for (int i=0; iGetName() == name) { + delete ml; + del_idx = i; + break; + } + } + if (del_idx >= 0) { + bg_maps.erase(bg_maps.begin() + del_idx); + } else { + for (int i=0; iGetName() == name) { + delete ml; + del_idx = i; + break; + } + } + if (del_idx >=0) { + fg_maps.erase(fg_maps.begin() + del_idx); + } + } + + maplayer_state->notifyObservers(this); +} + +bool MapCanvas::IsCurrentMap() +{ + return true; +} + +wxString MapCanvas::GetName() +{ + return project->GetProjectTitle(); +} + +int MapCanvas::GetNumRecords() +{ + return project->GetNumRecords(); +} + +vector MapCanvas::GetKeyNames() +{ + return project->GetIntegerAndStringFieldNames(); +} + +bool MapCanvas::GetKeyColumnData(wxString col_name, vector& data) +{ + int n = project->GetNumRecords(); + data.resize(n); + if (col_name.IsEmpty() || col_name == _("(Use Sequences)")) { + // using sequences + for (int i=0; iGetStringColumnData(col_name, data); + } + return false; +} + +void MapCanvas::ResetHighlight() +{ + vector& hs = highlight_state->GetHighlight(); + for (int i=0; i& hs = highlight_state->GetHighlight(); + + // draw any connected layers + map::iterator it; + for (it=associated_layers.begin(); it!=associated_layers.end();it++) { + AssociateLayerInt* associated_layer = it->first; + Association& al = it->second; + wxString primary_key = al.first; + wxString associated_key = al.second; + + vector pid(num_obs); // e.g. 1 2 3 4 5 + if (primary_key.IsEmpty() == false) { + GetKeyColumnData(primary_key, pid); + } else { + for (int i=0; i fid; // e.g. 2 2 1 1 3 5 4 4 + associated_layer->GetKeyColumnData(associated_key, fid); + associated_layer->ResetHighlight(); + + map > aid_idx; + for (int i=0; i& ids = aid_idx[aid]; + for (int j=0; jSetHighlight( ids[j] ); + } + } + associated_layer->DrawHighlight(dc, map_canvas); + for (int i=0; i& ids = aid_idx[aid]; + for (int j=0; jcenter, associated_layer->GetShape(ids[j])->center); + } + } + } + } + + this->DrawHighlighted(dc, false); } -void MapCanvas::update(CatClassifState* o) +GdaShape* MapCanvas::GetShape(int i) { - LOG_MSG("In MapCanvas::update(CatClassifState*)"); - cat_classif_def = o->GetCatClassif(); - CreateAndUpdateCategories(); - PopulateCanvas(); - if (template_frame) { - template_frame->UpdateTitle(); - if (template_frame->GetTemplateLegend()) { - template_frame->GetTemplateLegend()->Refresh(); - } - } + return selectable_shps[i]; +} + +void MapCanvas::SetLayerAssociation(wxString my_key, AssociateLayerInt* layer, wxString key, bool show_connline) +{ + associated_layers[layer] = make_pair(my_key, key); + associated_lines[layer] = show_connline; +} + +bool MapCanvas::IsAssociatedWith(AssociateLayerInt* layer) +{ + map::iterator it; + for (it=associated_layers.begin(); it!=associated_layers.end();it++) { + AssociateLayerInt* asso_layer = it->first; + if (layer->GetName() == asso_layer->GetName()) { + return true; + } + } + return false; } /** This method assumes that v1 is already set and valid. It will @@ -1312,7 +2144,6 @@ void MapCanvas::PopulateCanvas() { BOOST_FOREACH( GdaShape* shp, background_shps ) { delete shp; } background_shps.clear(); - int canvas_ts = cat_data.GetCurrentCanvasTmStep(); if (!map_valid[canvas_ts]) full_map_redraw_needed = true; @@ -1321,23 +2152,52 @@ void MapCanvas::PopulateCanvas() if (full_map_redraw_needed) { BOOST_FOREACH( GdaShape* shp, selectable_shps ) { delete shp; } selectable_shps.clear(); + // Background map layers + BOOST_FOREACH( GdaShape* map, background_maps ) { delete map; } + background_maps.clear(); + BackgroundMapLayer* ml = NULL; + for (int i=bg_maps.size()-1; i>=0; i--) { + ml = bg_maps[i]; + GdaShapeLayer* bg_map = new GdaShapeLayer(ml->GetName(), ml); + background_maps.push_back(bg_map); + } + // Foreground map layers + BOOST_FOREACH( GdaShape* map, foreground_maps ) { delete map; } + foreground_maps.clear(); + for (int i=fg_maps.size()-1; i>=0; i--) { + ml = fg_maps[i]; + GdaShapeLayer* fg_map = new GdaShapeLayer(ml->GetName(), ml); + foreground_maps.push_back(fg_map); + } } BOOST_FOREACH( GdaShape* shp, foreground_shps ) { delete shp; } foreground_shps.clear(); + + w_graph.clear(); + + if ( display_map_boundary ) { + GdaPolygon* bg = project->GetMapBoundary(); + if (bg) { + wxPen pen(wxColour(120, 120, 120)); + bg->setPen(pen); + bg->setBrush(*wxTRANSPARENT_BRUSH); + foreground_shps.push_back(bg); + } + } - if (map_valid[canvas_ts]) { + if ( map_valid[canvas_ts] ) { if (full_map_redraw_needed) { - CreateSelShpsFromProj(selectable_shps, project); + empty_shps_ids = CreateSelShpsFromProj(selectable_shps, project); full_map_redraw_needed = false; - if (selectable_shps_type == polygons && - (display_mean_centers || display_centroids)) { + if (selectable_shps_type == polygons && (display_mean_centers || display_centroids || display_weights_graph)) + { GdaPoint* p; wxPen cent_pen(wxColour(20, 20, 20)); wxPen cntr_pen(wxColour(55, 55, 55)); if (display_mean_centers) { - const std::vector& c = project->GetMeanCenters(); + const vector& c = project->GetMeanCenters(); for (int i=0; isetPen(cntr_pen); @@ -1346,7 +2206,7 @@ void MapCanvas::PopulateCanvas() } } if (display_centroids) { - const std::vector& c = project->GetCentroids(); + const vector& c = project->GetCentroids(); for (int i=0; isetPen(cent_pen); @@ -1355,15 +2215,43 @@ void MapCanvas::PopulateCanvas() } } } + if (selectable_shps_type == points && display_voronoi_diagram) { GdaPolygon* p; - const std::vector& polys = - project->GetVoronoiPolygons(); + const vector& polys = project->GetVoronoiPolygons(); for (int i=0, num_polys=polys.size(); iGetWManInt(); + GalWeight* gal_weights = w_man_int->GetGal(weights_id); + const vector& c = project->GetCentroids(); + vector& hs = highlight_state->GetHighlight(); + GdaPolyLine* edge; + std::set w_nodes; + wxPen pen(graph_color, weights_graph_thickness); + for (int i=0; gal_weights && inum_obs; i++) { + GalElement& e = gal_weights->gal[i]; + for (int j=0, jend=e.Size(); jnbr + edge = new GdaPolyLine(c[i]->GetX(),c[i]->GetY(), c[nbr]->GetX(), c[nbr]->GetY()); + edge->from = i; + edge->to = nbr; + edge->setPen(pen); + edge->setBrush(*wxTRANSPARENT_BRUSH); + foreground_shps.push_back(edge); + w_graph.push_back(edge); + w_nodes.insert(i); + w_nodes.insert(nbr); + } + } + } + } } } else { wxRealPoint cntr_ref_pnt = last_scale_trans.GetDataCenter(); @@ -1382,30 +2270,29 @@ void MapCanvas::TimeChange() if (!is_any_sync_with_global_time) return; int cts = project->GetTimeState()->GetCurrTime(); - int ref_time = var_info[ref_var_index].time; - int ref_time_min = var_info[ref_var_index].time_min; - int ref_time_max = var_info[ref_var_index].time_max; + int ref_time = var_info[ref_var_index].time; + int ref_time_min = var_info[ref_var_index].time_min; + int ref_time_max = var_info[ref_var_index].time_max; - if ((cts == ref_time) || - (cts > ref_time_max && ref_time == ref_time_max) || - (cts < ref_time_min && ref_time == ref_time_min)) return; - if (cts > ref_time_max) { - ref_time = ref_time_max; - } else if (cts < ref_time_min) { - ref_time = ref_time_min; - } else { - ref_time = cts; - } + if ((cts == ref_time) || + (cts > ref_time_max && ref_time == ref_time_max) || + (cts < ref_time_min && ref_time == ref_time_min)) return; + if (cts > ref_time_max) { + ref_time = ref_time_max; + } else if (cts < ref_time_min) { + ref_time = ref_time_min; + } else { + ref_time = cts; + } for (size_t i=0; i undef_res(smoothing_type == no_smoothing ? 0 : num_obs); if (smoothing_type != no_smoothing) { P = new double[num_obs]; @@ -1490,13 +2395,15 @@ void MapCanvas::CreateAndUpdateCategories() } cat_var_sorted.resize(num_time_vals); - std::vector > cat_var_undef; + if (IS_VAR_STRING) cat_str_var_sorted.resize(num_time_vals); + + vector > cat_var_undef; for (int t=0; t undef_res(num_obs, false); + vector undef_res(num_obs, false); for (int i=0; i t ) { @@ -1506,7 +2413,6 @@ void MapCanvas::CreateAndUpdateCategories() } if (smoothing_type != no_smoothing) { - for (int i=0; i& hs = highlight_state->GetHighlight(); - std::vector hs_backup = hs; + vector& hs = highlight_state->GetHighlight(); + vector hs_backup = hs; for (int i=0; iuseScientificNotation); + if (IS_VAR_STRING) + CatClassification::PopulateCatClassifData(cat_classif_def, + cat_str_var_sorted, + cat_var_undef, + cat_data, + map_valid, + map_error_message, + this->useScientificNotation); + else + CatClassification::PopulateCatClassifData(cat_classif_def, + cat_var_sorted, + cat_var_undef, + cat_data, + map_valid, + map_error_message, + this->useScientificNotation); if (ref_var_index != -1) { cat_data.SetCurrentCanvasTmStep(var_info[ref_var_index].time @@ -1642,6 +2566,13 @@ void MapCanvas::TimeSyncVariableToggle(int var_index) PopulateCanvas(); } +void MapCanvas::DisplayMapLayers() +{ + wxLogMessage("MapCanvas::DisplayMapLayers()"); + full_map_redraw_needed = true; + PopulateCanvas(); +} + void MapCanvas::DisplayMeanCenters() { wxLogMessage("MapCanvas::DisplayMeanCenters()"); @@ -1658,6 +2589,92 @@ void MapCanvas::DisplayCentroids() PopulateCanvas(); } +void MapCanvas::DisplayWeightsGraph() +{ + wxLogMessage("MapCanvas::DisplayWeightsGraph()"); + full_map_redraw_needed = true; + display_weights_graph = !display_weights_graph; + if (display_weights_graph) { + display_neighbors = false; + + } else { + display_map_with_graph = true; + } + PopulateCanvas(); +} + +void MapCanvas::DisplayNeighbors() +{ + wxLogMessage("MapCanvas::DisplayNeighbors()"); + full_map_redraw_needed = true; + display_neighbors = !display_neighbors; + if (display_neighbors) { + display_map_with_graph = true; + display_weights_graph = false; + } else { + } + PopulateCanvas(); +} + +void MapCanvas::DisplayMapWithGraph() +{ + wxLogMessage("MapCanvas::DisplayMapWithGraph()"); + if (display_weights_graph) { + full_map_redraw_needed = true; + display_map_with_graph = !display_map_with_graph; + PopulateCanvas(); + } +} + +void MapCanvas::DisplayMapBoundray(bool flag) +{ + wxLogMessage("MapCanvas::DisplayMapBoundray()"); + + display_map_boundary = flag; + if (selectable_outline_visible) display_map_boundary = false; + full_map_redraw_needed = true; + + PopulateCanvas(); + +} + +void MapCanvas::ChangeGraphThickness(int val) +{ + wxLogMessage("MapCanvas::ChangeGraphThickness()"); + if (display_weights_graph) { + weights_graph_thickness = val; + full_map_redraw_needed = true; + PopulateCanvas(); + } +} + +void MapCanvas::ChangeGraphColor() +{ + if (display_weights_graph) { + graph_color = GeneralWxUtils::PickColor(this, graph_color); + full_map_redraw_needed = true; + PopulateCanvas(); + } +} + +void MapCanvas::ChangeConnSelectedColor() +{ + if (display_neighbors || display_weights_graph) { + conn_selected_color = GeneralWxUtils::PickColor(this, conn_selected_color); + full_map_redraw_needed = true; + PopulateCanvas(); + } +} + +void MapCanvas::ChangeNeighborFillColor() +{ + if (display_neighbors) { + neighbor_fill_color = GeneralWxUtils::PickColor(this, neighbor_fill_color); + full_map_redraw_needed = true; + PopulateCanvas(); + } +} + void MapCanvas::DisplayVoronoiDiagram() { wxLogMessage("MapCanvas::DisplayVoronoiDiagram()"); @@ -1688,17 +2705,17 @@ void MapCanvas::SaveRates() wxLogMessage("MapCanvas::SaveRates()"); if (smoothing_type == no_smoothing) { wxString msg; - msg << "No rates currently calculated to save."; - wxMessageDialog dlg (this, msg, "Information", + msg << _("No rates currently calculated to save."); + wxMessageDialog dlg (this, msg, _("Information"), wxOK | wxICON_INFORMATION); dlg.ShowModal(); return; } - std::vector data(1); + vector data(1); - std::vector undefs(num_obs); - std::vector dt(num_obs); + vector undefs(num_obs); + vector dt(num_obs); int t = cat_data.GetCurrentCanvasTmStep(); for (int i=0; i& hl = highlight_state->GetHighlight(); wxString s; - s << "#obs=" << project->GetNumRecords() <<" "; + + int selected_cnt = 0; + int selected_idx = 0; + + if (GetCcType() == CatClassification::no_theme) + s << _("#obs=") << project->GetNumRecordsNoneEmpty() <<" "; + else + s << _("#obs=") << project->GetNumRecords() <<" "; if ( highlight_state->GetTotalHighlighted() > 0) { // for highlight from other windows - s << "#selected=" << highlight_state->GetTotalHighlighted()<< " "; + if (GetCcType() == CatClassification::no_theme) { + for (int i=0; i= 1) { - s << "hover obs " << hover_obs[0]+1; - } - if (total_hover_obs >= 2) { - s << ", "; - s << "obs " << hover_obs[1]+1; - } - if (total_hover_obs >= 3) { - s << ", "; - s << "obs " << hover_obs[2]+1; - } - if (total_hover_obs >= 4) { - s << ", ..."; - } - } + if ((display_neighbors || display_weights_graph) && + boost::uuids::nil_uuid() != weights_id ) + { + WeightsManInterface* w_man_int = project->GetWManInt(); + GalWeight* gal_weights = w_man_int->GetGal(weights_id); + + long cid = -1; + + if (hover_obs.size() == 1) + cid = hover_obs[0]; + else if (selected_cnt == 1) { + cid = selected_idx; + } + + if (cid >= 0) { + GalElement& e = gal_weights->gal[cid]; + + s << _("obs ") << w_man_int->RecNumToId(GetWeightsId(), cid); + s << " has " << e.Size() << " neighbor"; + if (e.Size() != 1) s << "s"; + if (e.Size() > 0) { + s << ": "; + int n_cnt = 0; + for (int j=0, jend=e.Size(); jRecNumToId(GetWeightsId(), obs); + if (n_cnt+1 < e.Size()) s << ", "; + ++n_cnt; + } + if (e.Size() > 20) s << "..."; + } else { + s << "."; + } + } + } else { + if (mousemode == select && selectstate == start) { + if (hover_obs.size() >= 1) { + s << _("#hover obs ") << hover_obs[0]+1; + } + if (hover_obs.size() >= 2) { + s << ", "; + s << _("obs ") << hover_obs[1]+1; + } + if (hover_obs.size() >= 3) { + s << ", "; + s << _("obs ") << hover_obs[2]+1; + } + if (hover_obs.size() >= 4) { + s << ", ..."; + } + } + } + sb->SetStatusText(s); } @@ -1796,6 +2871,8 @@ MapNewLegend::MapNewLegend(wxWindow *parent, TemplateCanvas* t_canvas, const wxPoint& pos, const wxSize& size) : TemplateLegend(parent, t_canvas, pos, size) { + Connect(TemplateLegend::ID_CATEGORY_COLOR, wxEVT_COMMAND_MENU_SELECTED, + wxCommandEventHandler(MapNewLegend::OnCategoryColor)); } MapNewLegend::~MapNewLegend() @@ -1803,34 +2880,78 @@ MapNewLegend::~MapNewLegend() LOG_MSG("In MapNewLegend::~MapNewLegend"); } +void MapNewLegend::OnCategoryColor(wxCommandEvent& event) +{ + int c_ts = template_canvas->cat_data.GetCurrentCanvasTmStep(); + int num_cats = template_canvas->cat_data.GetNumCategories(c_ts); + if (opt_menu_cat < 0 || opt_menu_cat >= num_cats) return; + + wxColour col = template_canvas->cat_data.GetCategoryColor(c_ts, opt_menu_cat); + wxColourData data; + data.SetColour(col); + data.SetChooseFull(true); + int ki; + for (ki = 0; ki < 16; ki++) { + wxColour colour(ki * 16, ki * 16, ki * 16); + data.SetCustomColour(ki, colour); + } + + wxColourDialog dialog(this, &data); + dialog.SetTitle(_("Choose Cateogry Color")); + if (dialog.ShowModal() == wxID_OK) { + wxColourData retData = dialog.GetColourData(); + for (int ts=0; tscat_data.GetCanvasTmSteps(); ts++) { + if (num_cats == template_canvas->cat_data.GetNumCategories(ts)) { + wxColor new_color = retData.GetColour(); + template_canvas->cat_data.SetCategoryColor(ts, opt_menu_cat, new_color); + wxString lbl = template_canvas->cat_data.GetCategoryLabel(ts, opt_menu_cat); + MapCanvas* w = dynamic_cast(template_canvas); + if (w) { + w->UpdatePredefinedColor(lbl, new_color); + } + } + } + template_canvas->invalidateBms(); + template_canvas->Refresh(); + Refresh(); + } +} + IMPLEMENT_CLASS(MapFrame, TemplateFrame) BEGIN_EVENT_TABLE(MapFrame, TemplateFrame) - EVT_ACTIVATE(MapFrame::OnActivate) + EVT_ACTIVATE(MapFrame::OnActivate) + EVT_CLOSE(MapFrame::OnClose ) END_EVENT_TABLE() MapFrame::MapFrame(wxFrame *parent, Project* project, - const std::vector& var_info, - const std::vector& col_ids, + const vector& var_info, + const vector& col_ids, CatClassification::CatClassifType theme_type, MapCanvas::SmoothingType smoothing_type, int num_categories, boost::uuids::uuid weights_id, const wxPoint& pos, const wxSize& size, const long style) -: TemplateFrame(parent, project, "Map", pos, size, style), -w_man_state(project->GetWManState()) +: TemplateFrame(parent, project, _("Map"), pos, size, style), +w_man_state(project->GetWManState()), export_dlg(NULL), +no_update_weights(false) { wxLogMessage("Open MapFrame."); template_legend = NULL; template_canvas = NULL; + map_tree = NULL; + + if (weights_id.is_nil()) { + WeightsManInterface* w_man_int = project->GetWManInt(); + weights_id = w_man_int->GetDefault(); + } int width, height; GetClientSize(&width, &height); wxSplitterWindow* splitter_win = 0; - splitter_win = new wxSplitterWindow(this,-1, wxDefaultPosition, wxDefaultSize, - wxSP_3D |wxSP_LIVE_UPDATE|wxCLIP_CHILDREN); + splitter_win = new wxSplitterWindow(this,-1, wxDefaultPosition, wxDefaultSize, wxSP_3D |wxSP_LIVE_UPDATE|wxCLIP_CHILDREN); splitter_win->SetMinimumPaneSize(10); wxPanel* rpanel = new wxPanel(splitter_win); @@ -1842,8 +2963,9 @@ w_man_state(project->GetWManState()) wxDefaultPosition, wxDefaultSize); template_canvas->SetScrollRate(1,1); - wxBoxSizer* rbox = new wxBoxSizer(wxVERTICAL); + rbox = new wxBoxSizer(wxHORIZONTAL); rbox->Add(template_canvas, 1, wxEXPAND); + rpanel->SetSizerAndFit(rbox); wxPanel* lpanel = new wxPanel(splitter_win); @@ -1862,9 +2984,9 @@ w_man_state(project->GetWManState()) wxPanel* toolbar_panel = new wxPanel(this,-1, wxDefaultPosition); wxBoxSizer* toolbar_sizer= new wxBoxSizer(wxVERTICAL); - wxToolBar* tb = wxXmlResource::Get()->LoadToolBar(toolbar_panel, "ToolBar_MAP"); + toolbar = wxXmlResource::Get()->LoadToolBar(toolbar_panel, "ToolBar_MAP"); SetupToolbar(); - toolbar_sizer->Add(tb, 0, wxEXPAND|wxALL); + toolbar_sizer->Add(toolbar, 0, wxEXPAND|wxALL); toolbar_panel->SetSizerAndFit(toolbar_sizer); wxBoxSizer* sizer = new wxBoxSizer(wxVERTICAL); @@ -1882,8 +3004,8 @@ w_man_state(project->GetWManState()) MapFrame::MapFrame(wxFrame *parent, Project* project, const wxPoint& pos, const wxSize& size, const long style) -: TemplateFrame(parent, project, "Map", pos, size, style), -w_man_state(project->GetWManState()) +: TemplateFrame(parent, project, _("Map"), pos, size, style), +w_man_state(project->GetWManState()), export_dlg(NULL) { w_man_state->registerObserver(this); } @@ -1896,6 +3018,12 @@ MapFrame::~MapFrame() } if (HasCapture()) ReleaseMouse(); DeregisterAsActive(); + + if (export_dlg) { + export_dlg->Destroy(); + delete export_dlg; + export_dlg = NULL; + } } void MapFrame::CleanBasemap() @@ -1921,16 +3049,36 @@ void MapFrame::SetupToolbar() wxCommandEventHandler(MapFrame::OnMapRefresh)); Connect(XRCID("ID_TOOLBAR_BASEMAP"), wxEVT_COMMAND_TOOL_CLICKED, wxCommandEventHandler(MapFrame::OnMapBasemap)); + Connect(XRCID("ID_ADD_LAYER"), wxEVT_COMMAND_TOOL_CLICKED, + wxCommandEventHandler(MapFrame::OnMapAddLayer)); + Connect(XRCID("ID_EDIT_LAYER"), wxEVT_COMMAND_TOOL_CLICKED, + wxCommandEventHandler(MapFrame::OnMapEditLayer)); + if (toolbar) { + toolbar->EnableTool(XRCID("ID_EDIT_LAYER"), project->GetMapLayerCount()>0); + } +} + +void MapFrame::UpdateMapLayer() +{ + if (toolbar) { + toolbar->EnableTool(XRCID("ID_EDIT_LAYER"), project->GetMapLayerCount()>0); + if (map_tree) { + map_tree->Recreate(); + map_tree->Raise(); + map_tree->Show(true); + } + } } -void MapFrame::OnDrawBasemap(bool flag, int map_type) +void MapFrame::OnDrawBasemap(bool flag, BasemapItem& bm_item) { if (!template_canvas) return; - bool drawSuccess = ((MapCanvas*)template_canvas)->DrawBasemap(flag, map_type); + MapCanvas* map_canvas = (MapCanvas*)template_canvas; + bool drawSuccess = map_canvas->DrawBasemap(flag, bm_item); if (flag == false) { - ((MapCanvas*)template_canvas)->tran_unhighlighted = GdaConst::transparency_unhighlighted; + map_canvas->tran_unhighlighted = GdaConst::transparency_unhighlighted; } if (drawSuccess==false) { @@ -1938,6 +3086,13 @@ void MapFrame::OnDrawBasemap(bool flag, int map_type) } } +void MapFrame::OnShowMapBoundary(wxCommandEvent& e) +{ + if (!template_canvas) return; + ((MapCanvas*)template_canvas)->DisplayMapBoundray(e.IsChecked()); + UpdateOptionMenuItems(); +} + void MapFrame::OnMapSelect(wxCommandEvent& e) { OnSelectionMode(e); @@ -1964,40 +3119,142 @@ void MapFrame::OnMapZoomOut(wxCommandEvent& e) } void MapFrame::OnMapExtent(wxCommandEvent& e) { - //OnFitToWindowMode(e); OnResetMap(e); } void MapFrame::OnMapRefresh(wxCommandEvent& e) { OnRefreshMap(e); } -//void MapFrame::OnMapBrush(wxCommandEvent& e) -//{ -//} + +void MapFrame::OnSelectableOutlineVisible(wxCommandEvent& event) +{ + if (!template_canvas) return; + template_canvas->SetSelectableOutlineVisible(!template_canvas->selectable_outline_visible); + wxCommandEvent ev; + if (template_canvas->selectable_outline_visible == false) { + ev.SetId(0); + } + OnShowMapBoundary(ev); + UpdateOptionMenuItems(); +} + +void MapFrame::OnMapAddLayer(wxCommandEvent& e) +{ + wxLogMessage("In MapFrame::OnMapAddLayer()"); + ConnectDatasourceDlg connect_dlg(this, wxDefaultPosition, wxDefaultSize); + if (connect_dlg.ShowModal() != wxID_OK) { + return; + } + wxString proj_title = connect_dlg.GetProjectTitle(); + wxString layer_name = connect_dlg.GetLayerName(); + IDataSource* datasource = connect_dlg.GetDataSource(); + wxString datasource_name = datasource->GetOGRConnectStr(); + GdaConst::DataSourceType ds_type = datasource->GetType(); + + BackgroundMapLayer* map_layer = project->AddMapLayer(datasource_name, ds_type, layer_name); + if (map_layer == NULL) { + wxMessageDialog dlg (this, _("GeoDa could not load this layer. Please check if the datasource is valid and not table only."), _("Load Layer Failed."), wxOK | wxICON_ERROR); + dlg.ShowModal(); + } else { + MapCanvas* m = (MapCanvas*) template_canvas; + m->AddMapLayer(layer_name, map_layer->Clone(), false); + toolbar->EnableTool(XRCID("ID_EDIT_LAYER"), true); + OnMapEditLayer(e); + } +} + +void MapFrame::OnMapEditLayer(wxCommandEvent& e) +{ + MapCanvas* m = (MapCanvas*) template_canvas; + if (map_tree == NULL) { + int n_bgmap = project->GetMapLayerCount(); + int h = n_bgmap * 25 + 120; + wxPoint pos = GetScreenPosition(); + wxSize sz = GetClientSize(); + pos.x += sz.GetWidth(); + map_tree = new MapTreeFrame(this, m, pos, wxSize(360, h)); + map_tree->Connect(wxEVT_DESTROY, wxWindowDestroyEventHandler(MapFrame::OnMapTreeClose), NULL, this); + } + map_tree->Recreate(); + map_tree->Raise(); + map_tree->Show(true); +} + +void MapFrame::OnMapTreeClose(wxWindowDestroyEvent& event) +{ + map_tree = NULL; +} + +void MapFrame::OnBasemapSelect(wxCommandEvent& event) +{ + int menu_id = event.GetId(); + + wxString basemap_sources = GdaConst::gda_basemap_sources; + std::vector items = OGRDataAdapter::GetInstance().GetHistory("gda_basemap_sources"); + if (items.size()>0) { + basemap_sources = items[0]; + } + vector basemap_groups = ExtractBasemapResources(basemap_sources); + + for (int i=0; i& items = grp.items; + for (int j=0; jLoadMenu("ID_BASEMAP_MENU"); - + + // add basemap options + wxString basemap_sources = GdaConst::gda_basemap_sources; + std::vector items = OGRDataAdapter::GetInstance().GetHistory("gda_basemap_sources"); + if (items.size()>0) { + basemap_sources = items[0]; + } + vector basemap_groups = ExtractBasemapResources(basemap_sources); + for (int i=0; i& items = grp.items; + for (int j=0; jAppendCheckItem(XRCID(xid), items[j].name); + Connect(XRCID(xid), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MapFrame::OnBasemapSelect)); + } + popupMenu->AppendSubMenu(imp, grp.name); + } if (popupMenu) { // set checkmarks - int idx = ((MapCanvas*) template_canvas)->GetBasemapType(); - - popupMenu->FindItem(XRCID("ID_NO_BASEMAP"))->Check(idx==0); - popupMenu->FindItem(XRCID("ID_BASEMAP_1"))->Check(idx==1); - popupMenu->FindItem(XRCID("ID_BASEMAP_2"))->Check(idx==2); - popupMenu->FindItem(XRCID("ID_BASEMAP_3"))->Check(idx==3); - popupMenu->FindItem(XRCID("ID_BASEMAP_4"))->Check(idx==4); - popupMenu->FindItem(XRCID("ID_BASEMAP_5"))->Check(idx==5); - popupMenu->FindItem(XRCID("ID_BASEMAP_6"))->Check(idx==6); - popupMenu->FindItem(XRCID("ID_BASEMAP_7"))->Check(idx==7); - popupMenu->FindItem(XRCID("ID_BASEMAP_8"))->Check(idx==8); - - //popupMenu->FindItem(XRCID("ID_CHANGE_TRANSPARENCY"))->Enable(idx!=0); - + BasemapItem current_item = ((MapCanvas*) template_canvas)->basemap_item; + bool no_basemap = true; + for (int i=0; i& items = grp.items; + for (int j=0; jFindItem(XRCID(xid)); + if (current_item == items[j]) { + menu->Check(true); + no_basemap = false; + } else { + menu->Check(false); + } + } + } + if (no_basemap) { + popupMenu->FindItem(XRCID("ID_NO_BASEMAP"))->Check(); + } PopupMenu(popupMenu, wxDefaultPosition); } - } void MapFrame::OnActivate(wxActivateEvent& event) @@ -2005,7 +3262,9 @@ void MapFrame::OnActivate(wxActivateEvent& event) if (event.GetActive()) { RegisterAsActive("MapFrame", GetTitle()); } - if ( event.GetActive() && template_canvas ) template_canvas->SetFocus(); + if ( event.GetActive() && template_canvas ) { + template_canvas->SetFocus(); + } } void MapFrame::MapMenus() @@ -2016,7 +3275,8 @@ void MapFrame::MapMenus() ((MapCanvas*) template_canvas)->AddTimeVariantOptionsToMenu(optMenu); TemplateCanvas::AppendCustomCategories(optMenu, project->GetCatClassifManager()); ((MapCanvas*) template_canvas)->SetCheckMarks(optMenu); - GeneralWxUtils::ReplaceMenu(mb, "Options", optMenu); + + GeneralWxUtils::ReplaceMenu(mb, _("Options"), optMenu); UpdateOptionMenuItems(); } @@ -2024,7 +3284,7 @@ void MapFrame::UpdateOptionMenuItems() { TemplateFrame::UpdateOptionMenuItems(); // set common items first wxMenuBar* mb = GdaFrame::GetGdaFrame()->GetMenuBar(); - int menu = mb->FindMenu("Options"); + int menu = mb->FindMenu(_("Options")); if (menu == wxNOT_FOUND) { } else { ((MapCanvas*) template_canvas)->SetCheckMarks(mb->GetMenu(menu)); @@ -2052,20 +3312,31 @@ void MapFrame::update(TimeState* o) /** Implementation of WeightsManStateObserver interface */ void MapFrame::update(WeightsManState* o) { - if (o->GetWeightsId() != - ((MapCanvas*) template_canvas)->GetWeightsId()) return; + if (!no_update_weights && o->GetWeightsId() != ((MapCanvas*) template_canvas)->GetWeightsId()) { + // add_evt + ((MapCanvas*) template_canvas)->SetWeightsId(o->GetWeightsId()); + return; + } if (o->GetEventType() == WeightsManState::name_change_evt) { UpdateTitle(); return; } - if (o->GetEventType() == WeightsManState::remove_evt) { - Destroy(); + if (no_update_weights == true && + o->GetEventType() == WeightsManState::remove_evt) { + Destroy(); } } int MapFrame::numMustCloseToRemove(boost::uuids::uuid id) const { - return id == ((MapCanvas*) template_canvas)->GetWeightsId() ? 1 : 0; + if (no_update_weights == false) + return 0; + else { + if (id == ((MapCanvas*) template_canvas)->GetWeightsId()) + return 1; + else + return 0; + } } void MapFrame::closeObserver(boost::uuids::uuid id) @@ -2080,6 +3351,108 @@ void MapFrame::closeObserver(boost::uuids::uuid id) } } +GalWeight* MapFrame::checkWeights() +{ + std::vector weights_ids; + WeightsManInterface* w_man_int = project->GetWManInt(); + w_man_int->GetIds(weights_ids); + if (weights_ids.size()==0) { + wxMessageDialog dlg (this, _("GeoDa could not find the required weights file. \nPlease specify weights in Tools > Weights Manager."), _("No Weights Found"), wxOK | wxICON_ERROR); + dlg.ShowModal(); + return NULL; + + } + boost::uuids::uuid w_id = w_man_int->GetDefault(); + + GalWeight* gal_weights = w_man_int->GetGal(w_id); + if (gal_weights== NULL) { + wxString msg = _("Invalid Weights Information:\n\n The selected weights file is not valid.\n Please choose another weights file, or use Tools > Weights > Weights Manager to define a valid weights file."); + wxMessageDialog dlg (this, msg, _("Warning"), wxOK | wxICON_WARNING); + dlg.ShowModal(); + return NULL; + } + return gal_weights; +} + +void MapFrame::OnDisplayWeightsGraph(wxCommandEvent& event) +{ + GalWeight* gal_weights = checkWeights(); + if (gal_weights == NULL) + return; + + if (event.GetString() == _("Connectivity")) + no_update_weights = true; + + ((MapCanvas*) template_canvas)->DisplayWeightsGraph(); + UpdateOptionMenuItems(); +} + +void MapFrame::OnAddNeighborToSelection(wxCommandEvent& event) +{ + GalWeight* gal_weights = checkWeights(); + if (gal_weights == NULL) + return; + + if (event.GetString() == _("Connectivity")) + no_update_weights = true; + + ((MapCanvas*) template_canvas)->DisplayNeighbors(); + UpdateOptionMenuItems(); +} + +void MapFrame::OnDisplayMapWithGraph(wxCommandEvent& event) +{ + GalWeight* gal_weights = checkWeights(); + if (gal_weights == NULL) + return; + + ((MapCanvas*) template_canvas)->DisplayMapWithGraph(); + UpdateOptionMenuItems(); +} + +void MapFrame::OnChangeGraphThickness(wxCommandEvent& event) +{ + GalWeight* gal_weights = checkWeights(); + if (gal_weights == NULL) + return; + if (event.GetId() == XRCID("ID_WEIGHTS_GRAPH_THICKNESS_LIGHT")) + ((MapCanvas*) template_canvas)->ChangeGraphThickness(0); + else if (event.GetId() == XRCID("ID_WEIGHTS_GRAPH_THICKNESS_NORM")) + ((MapCanvas*) template_canvas)->ChangeGraphThickness(1); + else if (event.GetId() == XRCID("ID_WEIGHTS_GRAPH_THICKNESS_STRONG")) + ((MapCanvas*) template_canvas)->ChangeGraphThickness(2); + + UpdateOptionMenuItems(); +} + +void MapFrame::OnChangeGraphColor(wxCommandEvent& event) +{ + GalWeight* gal_weights = checkWeights(); + if (gal_weights == NULL) + return; + ((MapCanvas*) template_canvas)->ChangeGraphColor(); + UpdateOptionMenuItems(); +} + +void MapFrame::OnChangeConnSelectedColor(wxCommandEvent& event) +{ + GalWeight* gal_weights = checkWeights(); + if (gal_weights == NULL) + return; + ((MapCanvas*) template_canvas)->ChangeConnSelectedColor(); + UpdateOptionMenuItems(); +} + +void MapFrame::OnChangeNeighborFillColor(wxCommandEvent& event) +{ + GalWeight* gal_weights = checkWeights(); + if (gal_weights == NULL) { + return; + } + ((MapCanvas*) template_canvas)->ChangeNeighborFillColor(); + UpdateOptionMenuItems(); +} + void MapFrame::OnNewCustomCatClassifA() { ((MapCanvas*) template_canvas)->NewCustomCatClassif(); @@ -2097,7 +3470,7 @@ void MapFrame::OnCustomCatClassifA(const wxString& cc_title) } else { ChangeMapType(CatClassification::custom, MapCanvas::no_smoothing, 4, boost::uuids::nil_uuid(), - false, std::vector(0), std::vector(0), + false, vector(0), vector(0), cc_title); } } @@ -2106,7 +3479,7 @@ void MapFrame::OnThemelessMap() { ChangeMapType(CatClassification::no_theme, MapCanvas::no_smoothing, 1, boost::uuids::nil_uuid(), - false, std::vector(0), std::vector(0)); + false, vector(0), vector(0)); } void MapFrame::OnHinge15() @@ -2121,8 +3494,8 @@ void MapFrame::OnHinge15() } else { ChangeMapType(CatClassification::hinge_15, MapCanvas::no_smoothing, 6, boost::uuids::nil_uuid(), - false, std::vector(0), - std::vector(0)); + false, vector(0), + vector(0)); } } @@ -2138,8 +3511,8 @@ void MapFrame::OnHinge30() } else { ChangeMapType(CatClassification::hinge_30, MapCanvas::no_smoothing, 6, boost::uuids::nil_uuid(), - false, std::vector(0), - std::vector(0)); + false, vector(0), + vector(0)); } } @@ -2155,7 +3528,7 @@ void MapFrame::OnQuantile(int num_cats) } else { ChangeMapType(CatClassification::quantile, MapCanvas::no_smoothing, num_cats, boost::uuids::nil_uuid(), false, - std::vector(0), std::vector(0)); + vector(0), vector(0)); } } @@ -2171,8 +3544,8 @@ void MapFrame::OnPercentile() } else { ChangeMapType(CatClassification::percentile, MapCanvas::no_smoothing, 6, boost::uuids::nil_uuid(), - false, std::vector(0), - std::vector(0)); + false, vector(0), + vector(0)); } } @@ -2188,16 +3561,20 @@ void MapFrame::OnStdDevMap() } else { ChangeMapType(CatClassification::stddev, MapCanvas::no_smoothing, 6, boost::uuids::nil_uuid(), - false, std::vector(0), - std::vector(0)); + false, vector(0), + vector(0)); } } void MapFrame::OnUniqueValues() { if (((MapCanvas*) template_canvas)->GetNumVars() != 1) { - VariableSettingsDlg dlg(project, - VariableSettingsDlg::univariate); + bool show_str_var = true; + VariableSettingsDlg dlg(project, VariableSettingsDlg::univariate, + // default values + false,false,_("Variable Settings"), + "","","","",false,false,false, + show_str_var); if (dlg.ShowModal() != wxID_OK) return; ChangeMapType(CatClassification::unique_values, MapCanvas::no_smoothing, @@ -2207,8 +3584,8 @@ void MapFrame::OnUniqueValues() ChangeMapType(CatClassification::unique_values, MapCanvas::no_smoothing, 6, boost::uuids::nil_uuid(), - false, std::vector(0), - std::vector(0)); + false, vector(0), + vector(0)); } } @@ -2226,7 +3603,7 @@ void MapFrame::OnNaturalBreaks(int num_cats) ChangeMapType(CatClassification::natural_breaks, MapCanvas::no_smoothing, num_cats, boost::uuids::nil_uuid(), - false, std::vector(0), std::vector(0)); + false, vector(0), vector(0)); } } @@ -2244,7 +3621,7 @@ void MapFrame::OnEqualIntervals(int num_cats) ChangeMapType(CatClassification::equal_intervals, MapCanvas::no_smoothing, num_cats, boost::uuids::nil_uuid(), - false, std::vector(0), std::vector(0)); + false, vector(0), vector(0)); } } @@ -2255,10 +3632,10 @@ void MapFrame::OnSaveCategories() void MapFrame::OnRawrate() { - VariableSettingsDlg dlg(project, VariableSettingsDlg::rate_smoothed, false, - false, - "Raw Rate Smoothed Variable Settings", - "Event Variable", "Base Variable"); + VariableSettingsDlg dlg(project, VariableSettingsDlg::rate_smoothed, + false, false, + _("Raw Rate Smoothed Variable Settings"), + _("Event Variable"), _("Base Variable")); if (dlg.ShowModal() != wxID_OK) return; ChangeMapType(dlg.GetCatClassifType(), MapCanvas::raw_rate, dlg.GetNumCategories(), @@ -2268,9 +3645,10 @@ void MapFrame::OnRawrate() void MapFrame::OnExcessRisk() { - VariableSettingsDlg dlg(project, VariableSettingsDlg::bivariate, false, false, - "Excess Risk Map Variable Settings", - "Event Variable", "Base Variable"); + VariableSettingsDlg dlg(project, + VariableSettingsDlg::bivariate, false, false, + _("Excess Risk Map Variable Settings"), + _("Event Variable"), _("Base Variable")); if (dlg.ShowModal() != wxID_OK) return; ChangeMapType(CatClassification::excess_risk_theme, MapCanvas::excess_risk, 6, boost::uuids::nil_uuid(), @@ -2279,10 +3657,10 @@ void MapFrame::OnExcessRisk() void MapFrame::OnEmpiricalBayes() { - VariableSettingsDlg dlg(project, VariableSettingsDlg::rate_smoothed, false, - false, - "Empirical Bayes Smoothed Variable Settings", - "Event Variable", "Base Variable"); + VariableSettingsDlg dlg(project, + VariableSettingsDlg::rate_smoothed, false, false, + _("Empirical Bayes Smoothed Variable Settings"), + _("Event Variable"), _("Base Variable")); if (dlg.ShowModal() != wxID_OK) return; ChangeMapType(dlg.GetCatClassifType(), MapCanvas::empirical_bayes, dlg.GetNumCategories(), @@ -2293,10 +3671,10 @@ void MapFrame::OnEmpiricalBayes() void MapFrame::OnSpatialRate() { - VariableSettingsDlg dlg(project, VariableSettingsDlg::rate_smoothed, true, - false, - "Spatial Rate Smoothed Variable Settings", - "Event Variable", "Base Variable"); + VariableSettingsDlg dlg(project, VariableSettingsDlg::rate_smoothed, + true, false, + _("Spatial Rate Smoothed Variable Settings"), + _("Event Variable"), _("Base Variable")); if (dlg.ShowModal() != wxID_OK) return; ChangeMapType(dlg.GetCatClassifType(), @@ -2307,10 +3685,10 @@ void MapFrame::OnSpatialRate() void MapFrame::OnSpatialEmpiricalBayes() { - VariableSettingsDlg dlg(project, VariableSettingsDlg::rate_smoothed, true, - false, - "Empirical Spatial Rate Smoothed Variable Settings", - "Event Variable", "Base Variable"); + VariableSettingsDlg dlg(project, VariableSettingsDlg::rate_smoothed, + true, false, + _("Empirical Spatial Rate Smoothed Variable Settings"), + _("Event Variable"), _("Base Variable")); if (dlg.ShowModal() != wxID_OK) return; ChangeMapType(dlg.GetCatClassifType(), MapCanvas::spatial_empirical_bayes, @@ -2328,8 +3706,8 @@ bool MapFrame::ChangeMapType(CatClassification::CatClassifType new_map_theme, int num_categories, boost::uuids::uuid weights_id, bool use_new_var_info_and_col_ids, - const std::vector& new_var_info, - const std::vector& new_col_ids, + const vector& new_var_info, + const vector& new_col_ids, const wxString& custom_classif_title) { bool r=((MapCanvas*) template_canvas)-> @@ -2364,22 +3742,50 @@ void MapFrame::OnDisplayVoronoiDiagram() UpdateOptionMenuItems(); } +void MapFrame::OnClose(wxCloseEvent& event) +{ + if (export_dlg) { + export_dlg->Close(); + } + event.Skip(); +} + void MapFrame::OnExportVoronoi() { - project->ExportVoronoi(); - ((MapCanvas*) template_canvas)->voronoi_diagram_duplicates_exist = - project->IsPointDuplicates(); - UpdateOptionMenuItems(); + if (project->ExportVoronoi()) { + if (export_dlg != NULL) { + export_dlg->Destroy(); + delete export_dlg; + } + export_dlg = new ExportDataDlg(this, project->voronoi_polygons, Shapefile::POLYGON, project); + export_dlg->ShowModal(); + ((MapCanvas*) template_canvas)->voronoi_diagram_duplicates_exist = project->IsPointDuplicates(); + UpdateOptionMenuItems(); + } } void MapFrame::OnExportMeanCntrs() { - project->ExportCenters(true); + project->ExportCenters(true); + if (export_dlg != NULL) { + export_dlg->Destroy(); + delete export_dlg; + } + export_dlg = new ExportDataDlg(this, project->mean_centers, Shapefile::NULL_SHAPE, "COORD", project); + + export_dlg->ShowModal(); } void MapFrame::OnExportCentroids() { project->ExportCenters(false); + if (export_dlg != NULL) { + export_dlg->Destroy(); + delete export_dlg; + } + export_dlg = new ExportDataDlg(this, project->centroids, Shapefile::NULL_SHAPE, "COORD", project); + + export_dlg->ShowModal(); } void MapFrame::OnSaveVoronoiDupsToTable() @@ -2397,17 +3803,16 @@ void MapFrame::OnChangeMapTransparency() SliderDialog sliderDlg(this, map_canvs_ref); sliderDlg.ShowModal(); } - } -void MapFrame::GetVizInfo(std::map >& colors) +void MapFrame::GetVizInfo(map >& colors) { if (template_canvas) { template_canvas->GetVizInfo(colors); } } -void MapFrame::GetVizInfo(wxString& shape_type, wxString& field_name, std::vector& clrs, std::vector& bins) +void MapFrame::GetVizInfo(wxString& shape_type, wxString& field_name, vector& clrs, vector& bins) { if (template_canvas) { template_canvas->GetVizInfo(shape_type, clrs, bins); @@ -2416,3 +3821,4 @@ void MapFrame::GetVizInfo(wxString& shape_type, wxString& field_name, std::vecto } } } + diff --git a/Explore/MapNewView.h b/Explore/MapNewView.h index 839c53c40..e167db8b3 100644 --- a/Explore/MapNewView.h +++ b/Explore/MapNewView.h @@ -41,16 +41,25 @@ #include "../VarTools.h" #include "../GdaShape.h" #include "../ShapeOperations/WeightsManStateObserver.h" +#include "../ShapeOperations/GalWeight.h" +#include "../MapLayerStateObserver.h" +#include "MapLayer.hpp" class CatClassifState; +class MapTreeFrame; class MapFrame; class MapCanvas; class MapNewLegend; class TableInterface; class WeightsManState; -typedef boost::multi_array d_array_type; +class ExportDataDlg; +class OGRLayerProxy; + typedef boost::multi_array b_array_type; +typedef boost::multi_array d_array_type; +typedef boost::multi_array s_array_type; +using namespace std; // Transparency SliderBar dialog for Basemap class SliderDialog: public wxDialog @@ -72,11 +81,12 @@ class SliderDialog: public wxDialog MapCanvas* canvas; wxSlider* slider; wxStaticText* slider_text; - void OnSliderChange(wxScrollEvent& event ); + void OnSliderChange(wxCommandEvent& event ); }; -class MapCanvas : public TemplateCanvas, public CatClassifStateObserver + +class MapCanvas : public TemplateCanvas, public CatClassifStateObserver, public MapLayerStateObserver, public AssociateLayerInt { DECLARE_CLASS(MapCanvas) public: @@ -87,8 +97,8 @@ class MapCanvas : public TemplateCanvas, public CatClassifStateObserver MapCanvas(wxWindow *parent, TemplateFrame* t_frame, Project* project, - const std::vector& var_info, - const std::vector& col_ids, + const vector& var_info, + const vector& col_ids, CatClassification::CatClassifType theme_type = CatClassification::no_theme, SmoothingType smoothing_type = no_smoothing, int num_categories = 1, @@ -98,129 +108,196 @@ class MapCanvas : public TemplateCanvas, public CatClassifStateObserver virtual ~MapCanvas(); - virtual void DisplayRightClickMenu(const wxPoint& pos); virtual void AddTimeVariantOptionsToMenu(wxMenu* menu); virtual wxString GetCanvasTitle(); + virtual wxString GetVariableNames(); virtual wxString GetNameWithTime(int var); - + virtual void UpdateSelectionPoints(bool shiftdown = false, + bool pointsel = false); virtual void NewCustomCatClassif(); virtual bool ChangeMapType(CatClassification::CatClassifType new_map_theme, SmoothingType new_map_smoothing, int num_categories, boost::uuids::uuid weights_id, bool use_new_var_info_and_col_ids, - const std::vector& new_var_info, - const std::vector& new_col_ids, + const vector& new_var_info, + const vector& new_col_ids, const wxString& custom_classif_title = wxEmptyString); virtual void update(HLStateInt* o); virtual void update(CatClassifState* o); + virtual void update(MapLayerState* o); virtual void SaveRates(); virtual void OnSaveCategories(); virtual void SetCheckMarks(wxMenu* menu); virtual void TimeChange(); - - int GetBasemapType(); - void CleanBasemapCache(); - - bool DrawBasemap(bool flag, int map_type); - - const wxBitmap* GetBaseLayer() { return basemap_bm; } - - void OnIdle(wxIdleEvent& event); - + virtual void OnSize(wxSizeEvent& event); + virtual void SetWeightsId(boost::uuids::uuid id); virtual void deleteLayerBms(); - virtual void DrawLayerBase(); virtual void DrawLayers(); - - // in linux, windows use old style drawing without transparency support - // the commented out functions are inherited from TemplateCanvas class - // TODO will be replace by wxImage drawing code virtual void resizeLayerBms(int width, int height); - virtual void DrawLayer0(); + virtual void DrawLayer0(); virtual void DrawLayer1(); virtual void DrawLayer2(); - //virtual void OnPaint(wxPaintEvent& event); + virtual void SetHighlight(int idx); + virtual void DrawHighlighted(wxMemoryDC &dc, bool revert); virtual void DrawHighlightedShapes(wxMemoryDC &dc, bool revert); virtual void DrawSelectableShapes_dc(wxMemoryDC &_dc, bool hl_only=false, bool revert=false, bool use_crosshatch=false); - virtual void ResetShapes(); virtual void ZoomShapes(bool is_zoomin = true); virtual void PanShapes(); - virtual void ResizeSelectableShps(int virtual_scrn_w = 0, int virtual_scrn_h = 0); - virtual void PopulateCanvas(); virtual void VarInfoAttributeChange(); virtual void CreateAndUpdateCategories(); - virtual void TimeSyncVariableToggle(int var_index); virtual void DisplayMeanCenters(); virtual void DisplayCentroids(); + virtual void DisplayWeightsGraph(); + virtual void DisplayNeighbors(); + virtual void DisplayMapWithGraph(); + virtual void DisplayMapBoundray(bool flag=false); + virtual void ChangeGraphThickness(int val); + virtual void ChangeGraphColor(); + virtual void ChangeConnSelectedColor(); + virtual void ChangeNeighborFillColor(); virtual void DisplayVoronoiDiagram(); virtual int GetNumVars(); virtual int GetNumCats(); virtual boost::uuids::uuid GetWeightsId() { return weights_id; } - virtual void SetWeightsId(boost::uuids::uuid id) { weights_id = id; } - + virtual void DetermineMouseHoverObjects(wxPoint pt); + virtual void RenderToDC(wxDC &dc, int w, int h); + virtual void UpdateStatusBar(); + virtual wxBitmap* GetPrintLayer(); + + void DisplayMapLayers(); + void AddMapLayer(wxString name, BackgroundMapLayer* map_layer, + bool is_hide = false); + void CleanBasemapCache(); + bool DrawBasemap(bool flag, BasemapItem& bm_item); + void OnIdle(wxIdleEvent& event); + void TranslucentLayer0(wxMemoryDC& dc); + void RenderToSVG(wxDC& dc, int svg_w, int svg_h, int map_w, int map_h, + int offset_x, int offset_y); + void SetupColor(); + void SetPredefinedColor(const wxString& lbl, const wxColor& new_color); + void UpdatePredefinedColor(const wxString& lbl, const wxColor& new_color); + void AddNeighborsToSelection(GalWeight* gal_weights, wxMemoryDC &dc); + void SetLegendLabel(int cat, wxString label) { + cat_data.SetCategoryLabel(0, cat, label); + } + + // multi-layers: + vector GetBackgroundMayLayers(); + vector GetForegroundMayLayers(); + void SetForegroundMayLayers(vector& val); + void SetBackgroundMayLayers(vector& val); + vector GetLayerNames(); + void RemoveLayer(wxString name); + virtual bool IsCurrentMap(); + virtual wxString GetName(); + virtual vector GetKeyNames(); + virtual int GetNumRecords(); + virtual bool GetKeyColumnData(wxString col_name, vector& data); + virtual void ResetHighlight(); + virtual void DrawHighlight(wxMemoryDC& dc, MapCanvas* map_canvas); + virtual void SetLayerAssociation(wxString my_key, AssociateLayerInt* layer, + wxString key, bool show_connline=true); + virtual bool IsAssociatedWith(AssociateLayerInt* layer); + virtual GdaShape* GetShape(int idx); + + Shapefile::Main& GetGeometryData(); + OGRLayerProxy* GetOGRLayerProxy(); + const wxBitmap* GetBaseLayer() { return basemap_bm; } + CatClassification::CatClassifType GetCcType(); + static void ResetThumbnail() { + MapCanvas::has_thumbnail_saved = false; + } + Project* GetProject() { return project; } CatClassifDef cat_classif_def; - CatClassification::CatClassifType GetCcType(); SmoothingType smoothing_type; bool is_rate_smoother; bool display_mean_centers; bool display_centroids; bool display_voronoi_diagram; bool voronoi_diagram_duplicates_exist; - - std::vector var_info; - + bool display_map_boundary; + bool display_weights_graph; + bool display_neighbors; + bool display_neighbor_color; + bool display_map_with_graph; + int weights_graph_thickness; + wxColour graph_color; + wxColour conn_selected_color; + wxColour neighbor_fill_color; + set ids_of_nbrs; + vector ids_wo_nbrs; + vector var_info; + int num_obs; bool isDrawBasemap; int tran_unhighlighted; + bool print_detailed_basemap; + + static vector empty_shps_ids; + static map empty_dict; + static bool has_shown_empty_shps_msg; + static int GetEmptyNumber(); + static void ResetEmptyFlag(); - static void ResetThumbnail() { MapCanvas::has_thumbnail_saved = false;} -private: + BasemapItem basemap_item; + +protected: + vector bg_maps; + vector fg_maps; + list background_maps; + list foreground_maps; + + bool layerbase_valid; // if false, then needs to be redrawn + + vector w_graph; IDataSource* p_datasource; static bool has_thumbnail_saved; wxString layer_name; wxString ds_name; - void SaveThumbnail(); - -protected: - bool InitBasemap(); - - int map_type; - bool layerbase_valid; // if false, then needs to be redrawn TableInterface* table_int; CatClassifState* custom_classif_state; + MapLayerState* maplayer_state; - int num_obs; + bool IS_VAR_STRING; int num_time_vals; - std::vector data; - std::vector data_undef; - std::vector cat_var_sorted; + vector data; + vector s_data; + vector data_undef; + + vector cat_var_sorted; + vector cat_str_var_sorted; int num_categories; // used for Quantile, Equal Interval and Natural Breaks int ref_var_index; bool is_any_time_variant; bool is_any_sync_with_global_time; - std::vector map_valid; - std::vector map_error_message; + vector map_valid; + vector map_error_message; bool full_map_redraw_needed; boost::uuids::uuid weights_id; - - // basemap + + // predefined/user-specified color, each label can be assigned with a color + // user can specified using: + // SetPredefinedColor(), UpdatePredifinedColor() + map lbl_color_dict; + wxBitmap* basemap_bm; GDA::Basemap* basemap; + void show_empty_shps_msgbox(); + void SaveThumbnail(); + bool InitBasemap(); - - virtual void UpdateStatusBar(); - DECLARE_EVENT_TABLE() }; @@ -229,6 +306,9 @@ class MapNewLegend : public TemplateLegend { MapNewLegend(wxWindow *parent, TemplateCanvas* template_canvas, const wxPoint& pos, const wxSize& size); virtual ~MapNewLegend(); + + // override + void OnCategoryColor(wxCommandEvent& event); }; class MapFrame : public TemplateFrame, public WeightsManStateObserver @@ -236,8 +316,8 @@ class MapFrame : public TemplateFrame, public WeightsManStateObserver DECLARE_CLASS(MapFrame) public: MapFrame(wxFrame *parent, Project* project, - const std::vector& var_info, - const std::vector& col_ids, + const vector& var_info, + const vector& col_ids, CatClassification::CatClassifType theme_type = CatClassification::no_theme, MapCanvas::SmoothingType smoothing_type = MapCanvas::no_smoothing, int num_categories = 1, @@ -254,6 +334,7 @@ class MapFrame : public TemplateFrame, public WeightsManStateObserver virtual ~MapFrame(); + void UpdateMapLayer(); void SetupToolbar(); void OnActivate(wxActivateEvent& event); @@ -268,7 +349,6 @@ class MapFrame : public TemplateFrame, public WeightsManStateObserver virtual void update(WeightsManState* o); virtual int numMustCloseToRemove(boost::uuids::uuid id) const; virtual void closeObserver(boost::uuids::uuid id); - virtual void OnNewCustomCatClassifA(); virtual void OnCustomCatClassifA(const wxString& cc_title); virtual void OnThemelessMap(); @@ -294,21 +374,25 @@ class MapFrame : public TemplateFrame, public WeightsManStateObserver virtual void OnExportMeanCntrs(); virtual void OnExportCentroids(); virtual void OnSaveVoronoiDupsToTable(); - + virtual void OnSelectableOutlineVisible(wxCommandEvent& event); virtual void OnChangeMapTransparency(); - virtual void OnDrawBasemap(bool flag, int map_type); + virtual void OnDrawBasemap(bool flag, BasemapItem& bm_item); + void OnBasemapSelect(wxCommandEvent& event); + void OnClose(wxCloseEvent& event); void CleanBasemap(); - - void GetVizInfo(std::map >& colors); - + void GetVizInfo(map >& colors); void GetVizInfo(wxString& shape_type, wxString& field_name, - std::vector& clrs, - std::vector& bins); - -protected: - + vector& clrs, + vector& bins); + void OnAddNeighborToSelection(wxCommandEvent& event); + void OnDisplayWeightsGraph(wxCommandEvent& event); + void OnDisplayMapWithGraph(wxCommandEvent& event); + void OnChangeGraphThickness(wxCommandEvent& event); + void OnChangeGraphColor(wxCommandEvent& event); + void OnChangeConnSelectedColor(wxCommandEvent& event); + void OnChangeNeighborFillColor(wxCommandEvent& event); void OnMapSelect(wxCommandEvent& e); void OnMapInvertSelect(wxCommandEvent& e); void OnMapPan(wxCommandEvent& e); @@ -316,22 +400,37 @@ class MapFrame : public TemplateFrame, public WeightsManStateObserver void OnMapZoomOut(wxCommandEvent& e); void OnMapExtent(wxCommandEvent& e); void OnMapRefresh(wxCommandEvent& e); - //void OnMapBrush(wxCommandEvent& e); void OnMapBasemap(wxCommandEvent& e); - - -protected: + void OnMapAddLayer(wxCommandEvent& e); + void OnMapEditLayer(wxCommandEvent& e); + void OnMapTreeClose(wxWindowDestroyEvent& event); + void OnShowMapBoundary(wxCommandEvent& event); bool ChangeMapType(CatClassification::CatClassifType new_map_theme, MapCanvas::SmoothingType new_map_smoothing, int num_categories, boost::uuids::uuid weights_id, bool use_new_var_info_and_col_ids, - const std::vector& new_var_info, - const std::vector& new_col_ids, + const vector& new_var_info, + const vector& new_col_ids, const wxString& custom_classif_title = wxEmptyString); + void SetLegendLabel(int cat, wxString label) { + if (!template_canvas) return; + MapCanvas* map_canvs_ref = (MapCanvas*) template_canvas; + map_canvs_ref->SetLegendLabel(cat, label); + if (!template_legend) return; + template_legend->Recreate(); + } +protected: + wxBoxSizer* rbox; + + MapTreeFrame* map_tree; WeightsManState* w_man_state; + ExportDataDlg* export_dlg; + GalWeight* checkWeights(); + bool no_update_weights; + DECLARE_EVENT_TABLE() }; diff --git a/Explore/PCPNewView.cpp b/Explore/PCPNewView.cpp index f55fb6763..c8389042c 100644 --- a/Explore/PCPNewView.cpp +++ b/Explore/PCPNewView.cpp @@ -41,7 +41,6 @@ #include "../logger.h" #include "../GeoDa.h" #include "../Project.h" -#include "../ShapeOperations/ShapeUtils.h" #include "PCPNewView.h" IMPLEMENT_CLASS(PCPCanvas, TemplateCanvas) @@ -112,6 +111,12 @@ num_categories(6), all_init(false) if (undef_markers[t][i] == false) temp_vec.push_back(data[v][t][i]); } + if (temp_vec.empty()) { + wxString m = wxString::Format(_("Variable %s is not valid. Please select another variable."), var_info[v].name); + wxMessageDialog dlg(NULL, m, _("Error"), wxOK | wxICON_ERROR); + dlg.ShowModal(); + return; + } data_stats[v][t].CalculateFromSample(temp_vec); double min = data_stats[v][t].min; double max = data_stats[v][t].max; @@ -121,8 +126,7 @@ num_categories(6), all_init(false) double s_min = (min - mean)/sd; double s_max = (max - mean)/sd; double abs_max = - GenUtils::max(GenUtils::abs(s_min), - GenUtils::abs(s_max)); + std::max(std::abs(s_min), std::abs(s_max)); if (!overall_abs_max_std_exists) { overall_abs_max_std_exists = true; overall_abs_max_std = abs_max; @@ -227,38 +231,23 @@ void PCPCanvas::SetCheckMarks(wxMenu* menu) GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_MAPANALYSIS_THEMELESS"), GetCcType() == CatClassification::no_theme); - - // since XRCID is a macro, we can't make this into a loop - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_QUANTILE_1"), - (GetCcType() == CatClassification::quantile) - && GetNumCats() == 1); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_QUANTILE_2"), - (GetCcType() == CatClassification::quantile) - && GetNumCats() == 2); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_QUANTILE_3"), - (GetCcType() == CatClassification::quantile) - && GetNumCats() == 3); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_QUANTILE_4"), - (GetCcType() == CatClassification::quantile) - && GetNumCats() == 4); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_QUANTILE_5"), - (GetCcType() == CatClassification::quantile) - && GetNumCats() == 5); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_QUANTILE_6"), - (GetCcType() == CatClassification::quantile) - && GetNumCats() == 6); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_QUANTILE_7"), - (GetCcType() == CatClassification::quantile) - && GetNumCats() == 7); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_QUANTILE_8"), - (GetCcType() == CatClassification::quantile) - && GetNumCats() == 8); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_QUANTILE_9"), - (GetCcType() == CatClassification::quantile) - && GetNumCats() == 9); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_QUANTILE_10"), - (GetCcType() == CatClassification::quantile) - && GetNumCats() == 10); + + for (int i=1; i<=10; i++) { + wxString str_xrcid; + bool flag; + + str_xrcid = wxString::Format("ID_QUANTILE_%d", i); + flag = GetCcType()==CatClassification::quantile && GetNumCats()==i; + GeneralWxUtils::CheckMenuItem(menu, XRCID(str_xrcid), flag); + + str_xrcid = wxString::Format("ID_EQUAL_INTERVALS_%d", i); + flag = GetCcType()==CatClassification::equal_intervals && GetNumCats()==i; + GeneralWxUtils::CheckMenuItem(menu, XRCID(str_xrcid), flag); + + str_xrcid = wxString::Format("ID_NATURAL_BREAKS_%d", i); + flag = GetCcType()==CatClassification::natural_breaks && GetNumCats()==i; + GeneralWxUtils::CheckMenuItem(menu, XRCID(str_xrcid), flag); + } GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_MAPANALYSIS_CHOROPLETH_PERCENTILE"), @@ -272,94 +261,12 @@ void PCPCanvas::SetCheckMarks(wxMenu* menu) GetCcType() == CatClassification::stddev); GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_MAPANALYSIS_UNIQUE_VALUES"), GetCcType() == CatClassification::unique_values); - // since XRCID is a macro, we can't make this into a loop - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_EQUAL_INTERVALS_1"), - (GetCcType() == - CatClassification::equal_intervals) - && GetNumCats() == 1); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_EQUAL_INTERVALS_2"), - (GetCcType() == - CatClassification::equal_intervals) - && GetNumCats() == 2); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_EQUAL_INTERVALS_3"), - (GetCcType() == - CatClassification::equal_intervals) - && GetNumCats() == 3); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_EQUAL_INTERVALS_4"), - (GetCcType() == - CatClassification::equal_intervals) - && GetNumCats() == 4); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_EQUAL_INTERVALS_5"), - (GetCcType() == - CatClassification::equal_intervals) - && GetNumCats() == 5); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_EQUAL_INTERVALS_6"), - (GetCcType() == - CatClassification::equal_intervals) - && GetNumCats() == 6); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_EQUAL_INTERVALS_7"), - (GetCcType() == - CatClassification::equal_intervals) - && GetNumCats() == 7); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_EQUAL_INTERVALS_8"), - (GetCcType() == - CatClassification::equal_intervals) - && GetNumCats() == 8); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_EQUAL_INTERVALS_9"), - (GetCcType() == - CatClassification::equal_intervals) - && GetNumCats() == 9); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_EQUAL_INTERVALS_10"), - (GetCcType() == - CatClassification::equal_intervals) - && GetNumCats() == 10); - - // since XRCID is a macro, we can't make this into a loop - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_NATURAL_BREAKS_1"), - (GetCcType() == - CatClassification::natural_breaks) - && GetNumCats() == 1); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_NATURAL_BREAKS_2"), - (GetCcType() == - CatClassification::natural_breaks) - && GetNumCats() == 2); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_NATURAL_BREAKS_3"), - (GetCcType() == - CatClassification::natural_breaks) - && GetNumCats() == 3); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_NATURAL_BREAKS_4"), - (GetCcType() == - CatClassification::natural_breaks) - && GetNumCats() == 4); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_NATURAL_BREAKS_5"), - (GetCcType() == - CatClassification::natural_breaks) - && GetNumCats() == 5); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_NATURAL_BREAKS_6"), - (GetCcType() == - CatClassification::natural_breaks) - && GetNumCats() == 6); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_NATURAL_BREAKS_7"), - (GetCcType() == - CatClassification::natural_breaks) - && GetNumCats() == 7); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_NATURAL_BREAKS_8"), - (GetCcType() == - CatClassification::natural_breaks) - && GetNumCats() == 8); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_NATURAL_BREAKS_9"), - (GetCcType() == - CatClassification::natural_breaks) - && GetNumCats() == 9); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_NATURAL_BREAKS_10"), - (GetCcType() == - CatClassification::natural_breaks) - && GetNumCats() == 10); } - wxString PCPCanvas::GetCanvasTitle() { + if (var_order.empty()) return wxEmptyString; + wxString s = _("Parallel Coordinate Plot: "); s << GetNameWithTime(var_order[0]) << ", "; if (num_vars > 2) s << "..., "; @@ -367,11 +274,20 @@ wxString PCPCanvas::GetCanvasTitle() return s; } +wxString PCPCanvas::GetVariableNames() +{ + if (var_order.empty()) return wxEmptyString; + + wxString s; + s << GetNameWithTime(var_order[0]); + return s; +} + wxString PCPCanvas::GetCategoriesTitle() { wxString s; if (GetCcType() == CatClassification::no_theme) { - s << "Themeless"; + s << _("Themeless"); } else if (GetCcType() == CatClassification::custom) { s << cat_classif_def.title << ": " << GetNameWithTime(theme_var); } else { @@ -454,7 +370,7 @@ void PCPCanvas::NewCustomCatClassif() if (template_frame) { template_frame->UpdateTitle(); if (template_frame->GetTemplateLegend()) { - template_frame->GetTemplateLegend()->Refresh(); + template_frame->GetTemplateLegend()->Recreate(); } } } @@ -493,7 +409,7 @@ PCPCanvas::ChangeThemeType(CatClassification::CatClassifType new_cat_theme, if (all_init && template_frame) { template_frame->UpdateTitle(); if (template_frame->GetTemplateLegend()) { - template_frame->GetTemplateLegend()->Refresh(); + template_frame->GetTemplateLegend()->Recreate(); } } } @@ -507,7 +423,7 @@ void PCPCanvas::update(CatClassifState* o) if (template_frame) { template_frame->UpdateTitle(); if (template_frame->GetTemplateLegend()) { - template_frame->GetTemplateLegend()->Refresh(); + template_frame->GetTemplateLegend()->Recreate(); } } } @@ -561,7 +477,7 @@ void PCPCanvas::PopulateCanvas() } last_scale_trans.SetData(0, 0, 100, 100); - last_scale_trans.SetMargin(25,virtual_screen_marg_bottom, 135, 25); + last_scale_trans.SetMargin(25, virtual_screen_marg_bottom, 135, 25); last_scale_trans.SetView(size.GetWidth(), size.GetHeight()); selectable_shps.resize(num_obs); @@ -604,6 +520,12 @@ void PCPCanvas::PopulateCanvas() } wxPen control_line_pen(GdaConst::pcp_horiz_line_color); control_line_pen.SetWidth(2); + + int max_label_width = 0; + wxClientDC dc(this); + int s_w =0; + int s_h = 0; + for (int v=0; vGetSize(dc, s_w, s_h); + if (s_w > max_label_width) max_label_width = s_w; + foreground_shps.push_back(s); control_labels[v] = (GdaShapeText*) s; wxString m; @@ -652,19 +577,23 @@ void PCPCanvas::PopulateCanvas() m << ", " << GenUtils::DblToStr(t_max, 4) << "]"; s = new GdaShapeText(m, *GdaConst::small_font, wxRealPoint(0, y_pos), 0, GdaShapeText::right, GdaShapeText::v_center, -25, 15+y_del); + ((GdaShapeText*)s)->GetSize(dc, s_w, s_h); + if (s_w > max_label_width) max_label_width = s_w; foreground_shps.push_back(s); int cols = 2; int rows = 2; std::vector vals(rows*cols); - vals[0] << "mean"; + vals[0] << _("mean"); vals[1] << GenUtils::DblToStr(t_mean, 4); - vals[2] << "s.d."; + vals[2] << _("s.d."); vals[3] << GenUtils::DblToStr(t_sd, 4); std::vector attribs(0); // undefined s = new GdaShapeTable(vals, attribs, rows, cols, *GdaConst::small_font, wxRealPoint(0, y_pos), GdaShapeText::right, GdaShapeText::top, GdaShapeText::right, GdaShapeText::v_center, 3, 7, -25, 25+y_del); + ((GdaShapeText*)s)->GetSize(dc, s_w, s_h); + if (s_w > max_label_width) max_label_width = s_w; foreground_shps.push_back(s); } } @@ -677,6 +606,8 @@ void PCPCanvas::PopulateCanvas() s = new GdaShapeText(wxString::Format("%d", 0), *GdaConst::small_font, wxRealPoint(50, 0), 0, GdaShapeText::h_center, GdaShapeText::v_center, 0, 12); + ((GdaShapeText*)s)->GetSize(dc, s_w, s_h); + if (s_w > max_label_width) max_label_width = s_w; foreground_shps.push_back(s); int sd_abs = overall_abs_max_std; for (int i=1; i<=sd_abs && overall_abs_max_std_exists; i++) { @@ -692,6 +623,8 @@ void PCPCanvas::PopulateCanvas() s = new GdaShapeText(wxString::Format("%d", i), *GdaConst::small_font, wxRealPoint(sd_p, 0), 0, GdaShapeText::h_center, GdaShapeText::v_center, 0, 12); + ((GdaShapeText*)s)->GetSize(dc, s_w, s_h); + if (s_w > max_label_width) max_label_width = s_w; foreground_shps.push_back(s); s = new GdaPolyLine(sd_m, 0, sd_m, 100); s->setPen(*GdaConst::scatterplot_origin_axes_pen); @@ -699,10 +632,14 @@ void PCPCanvas::PopulateCanvas() s = new GdaShapeText(wxString::Format("%d", -i), *GdaConst::small_font, wxRealPoint(sd_m, 0), 0, GdaShapeText::h_center, GdaShapeText::v_center, 0, 12); + ((GdaShapeText*)s)->GetSize(dc, s_w, s_h); + if (s_w > max_label_width) max_label_width = s_w; foreground_shps.push_back(s); } } - + + last_scale_trans.SetMargin(25, virtual_screen_marg_bottom, max_label_width + 30, 25); + delete [] pts; ResizeSelectableShps(); @@ -928,6 +865,8 @@ void PCPCanvas::OnMouseEvent(wxMouseEvent& event) // if the mouse position is at one of the control dots, then // proceed, otherwise call TemplateCanvas::OnMouseEvent(event) + if (control_labels.empty()) return; + int label_match = -1; pcp_prev = GetActualPos(event); pcp_sel1 = pcp_prev; @@ -1125,7 +1064,7 @@ void PCPCanvas::UpdateStatusBar() if (highlight_state->GetTotalHighlighted()> 0) { int n_total_hl = highlight_state->GetTotalHighlighted(); - s << "#selected=" << n_total_hl << " "; + s << _("#selected=") << n_total_hl << " "; int n_undefs = 0; for (int i=0; i 0) { - s << "(undefined:" << n_undefs << ") "; + s << _("undefined: ") << n_undefs << ") "; } } @@ -1151,7 +1090,7 @@ void PCPCanvas::UpdateStatusBar() } if (total_hover_obs != 0) { int ob = hover_obs[0]; - s << "obs " << ob+1 << " = ("; + s << _("obs ") << ob+1 << " = ("; for (int v=0; vGetCatClassifManager()); ((PCPCanvas*) template_canvas)->SetCheckMarks(optMenu); - GeneralWxUtils::ReplaceMenu(mb, "Options", optMenu); + GeneralWxUtils::ReplaceMenu(mb, _("Options"), optMenu); UpdateOptionMenuItems(); } @@ -1268,7 +1207,7 @@ void PCPFrame::UpdateOptionMenuItems() { TemplateFrame::UpdateOptionMenuItems(); // set common items first wxMenuBar* mb = GdaFrame::GetGdaFrame()->GetMenuBar(); - int menu = mb->FindMenu("Options"); + int menu = mb->FindMenu(_("Options")); if (menu == wxNOT_FOUND) { } else { ((PCPCanvas*) template_canvas)->SetCheckMarks(mb->GetMenu(menu)); diff --git a/Explore/PCPNewView.h b/Explore/PCPNewView.h index 50b016ce4..1ff1cba42 100644 --- a/Explore/PCPNewView.h +++ b/Explore/PCPNewView.h @@ -53,6 +53,7 @@ class PCPCanvas : public TemplateCanvas, public CatClassifStateObserver virtual void AddTimeVariantOptionsToMenu(wxMenu* menu); //virtual void update(HLStateInt* o); virtual wxString GetCanvasTitle(); + virtual wxString GetVariableNames(); virtual wxString GetCategoriesTitle(); // cats virtual wxString GetNameWithTime(int var); @@ -96,9 +97,9 @@ class PCPCanvas : public TemplateCanvas, public CatClassifStateObserver CatClassifDef cat_classif_def; CatClassification::CatClassifType GetCcType(); int GetNumCats() { return num_categories; } + virtual void UpdateStatusBar(); protected: - virtual void UpdateStatusBar(); CatClassifState* custom_classif_state; diff --git a/Explore/ScatterNewPlotView.cpp b/Explore/ScatterNewPlotView.cpp index 2a3f6115a..8678b8137 100644 --- a/Explore/ScatterNewPlotView.cpp +++ b/Explore/ScatterNewPlotView.cpp @@ -34,14 +34,19 @@ #include "../DataViewer/TableInterface.h" #include "../DataViewer/TimeState.h" #include "../DialogTools/CatClassifDlg.h" +#include "../DialogTools/CreatingWeightDlg.h" +#include "../ShapeOperations/GwtWeight.h" +#include "../ShapeOperations/GalWeight.h" +#include "../SpatialIndAlgs.h" #include "../GdaConst.h" #include "../GeneralWxUtils.h" #include "../GenGeomAlgs.h" #include "../logger.h" #include "../GeoDa.h" #include "../Project.h" +#include "../ShapeOperations/VoronoiUtils.h" #include "../ShapeOperations/Lowess.h" -#include "../ShapeOperations/ShapeUtils.h" +#include "MapLayoutView.h" #include "ScatterNewPlotView.h" @@ -66,19 +71,19 @@ BubbleSizeSliderDlg::BubbleSizeSliderDlg (ScatterNewPlotCanvas* _canvas, slider = new wxSlider(this, XRCID("ID_BUBBLE_SLIDER"), int(pos), -95, 80, wxDefaultPosition, wxSize(200, -1), wxSL_HORIZONTAL); - subSizer->Add(new wxStaticText(this, wxID_ANY,"small"), 0, + subSizer->Add(new wxStaticText(this, wxID_ANY, _("small")), 0, wxALIGN_CENTER_VERTICAL|wxALL); subSizer->Add(slider, 0, wxALIGN_CENTER_VERTICAL|wxALL); - subSizer->Add(new wxStaticText(this, wxID_ANY,"large"), 0, + subSizer->Add(new wxStaticText(this, wxID_ANY, _("large")), 0, wxALIGN_CENTER_VERTICAL|wxALL); boxSizer->Add(subSizer); - resetBtn = new wxButton(this, XRCID("ID_RESET"), wxT("Reset"), wxDefaultPosition, wxSize(100, -1)); + resetBtn = new wxButton(this, XRCID("ID_RESET"), _("Reset"), wxDefaultPosition, wxSize(100, -1)); topSizer->Add(resetBtn, 0, wxGROW|wxALL, 5); topSizer->Fit(this); - Connect(XRCID("ID_BUBBLE_SLIDER"), wxEVT_SCROLL_THUMBRELEASE, wxScrollEventHandler(BubbleSizeSliderDlg::OnSliderChange)); + Connect(XRCID("ID_BUBBLE_SLIDER"), wxEVT_SLIDER, wxScrollEventHandler(BubbleSizeSliderDlg::OnSliderChange)); Connect(XRCID("ID_RESET"), wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(BubbleSizeSliderDlg::OnReset)); } @@ -269,7 +274,8 @@ bubble_size_scaler(1.0) // 1 = #cats cat_data.CreateCategoriesAllCanvasTms(1, num_time_vals, num_obs); for (int t=0; tGetCatClassifManager()); optMenu->AppendSeparator(); - wxMenuItem* menu_item = optMenu->Append(XRCID("IDM_BUBBLE_SLIDER"), wxT("Adjust Bubble Size")); + wxMenuItem* menu_item = optMenu->Append(XRCID("IDM_BUBBLE_SLIDER"), _("Adjust Bubble Size")); template_frame->Connect(XRCID("IDM_BUBBLE_SLIDER"), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(ScatterNewPlotFrame::AdjustBubbleSize)); } else { optMenu = wxXmlResource::Get()-> @@ -340,10 +346,9 @@ void ScatterNewPlotCanvas::AddTimeVariantOptionsToMenu(wxMenu* menu) wxMenu* menu1 = new wxMenu(wxEmptyString); for (size_t i=0; iAppendCheckItem(GdaConst::ID_TIME_SYNC_VAR1+i, s, s); + wxString s = _("Synchronize %s with Time Control"); + s = wxString::Format(s, var_info[i].name); + wxMenuItem* mi = menu1->AppendCheckItem(GdaConst::ID_TIME_SYNC_VAR1+i, s, s); mi->Check(var_info[i].sync_with_global_time); } } @@ -387,38 +392,22 @@ void ScatterNewPlotCanvas::SetCheckMarks(wxMenu* menu) GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_MAPANALYSIS_THEMELESS"), GetCcType() == CatClassification::no_theme); - // since XRCID is a macro, we can't make this into a loop - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_QUANTILE_1"), - (GetCcType() == CatClassification::quantile) - && GetNumCats() == 1); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_QUANTILE_2"), - (GetCcType() == CatClassification::quantile) - && GetNumCats() == 2); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_QUANTILE_3"), - (GetCcType() == CatClassification::quantile) - && GetNumCats() == 3); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_QUANTILE_4"), - (GetCcType() == CatClassification::quantile) - && GetNumCats() == 4); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_QUANTILE_5"), - (GetCcType() == CatClassification::quantile) - && GetNumCats() == 5); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_QUANTILE_6"), - (GetCcType() == CatClassification::quantile) - && GetNumCats() == 6); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_QUANTILE_7"), - (GetCcType() == CatClassification::quantile) - && GetNumCats() == 7); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_QUANTILE_8"), - (GetCcType() == CatClassification::quantile) - && GetNumCats() == 8); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_QUANTILE_9"), - (GetCcType() == CatClassification::quantile) - && GetNumCats() == 9); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_QUANTILE_10"), - (GetCcType() == CatClassification::quantile) - && GetNumCats() == 10); - + for (int i=1; i<=10; i++) { + wxString str_xrcid; + bool flag; + + str_xrcid = wxString::Format("ID_QUANTILE_%d", i); + flag = GetCcType()==CatClassification::quantile && GetNumCats()==i; + GeneralWxUtils::CheckMenuItem(menu, XRCID(str_xrcid), flag); + + str_xrcid = wxString::Format("ID_EQUAL_INTERVALS_%d", i); + flag = GetCcType()==CatClassification::equal_intervals && GetNumCats()==i; + GeneralWxUtils::CheckMenuItem(menu, XRCID(str_xrcid), flag); + + str_xrcid = wxString::Format("ID_NATURAL_BREAKS_%d", i); + flag = GetCcType()==CatClassification::natural_breaks && GetNumCats()==i; + GeneralWxUtils::CheckMenuItem(menu, XRCID(str_xrcid), flag); + } GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_MAPANALYSIS_CHOROPLETH_PERCENTILE"), GetCcType() == CatClassification::percentile); @@ -431,94 +420,8 @@ void ScatterNewPlotCanvas::SetCheckMarks(wxMenu* menu) GetCcType() == CatClassification::stddev); GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_MAPANALYSIS_UNIQUE_VALUES"), GetCcType() == CatClassification::unique_values); - - // since XRCID is a macro, we can't make this into a loop - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_EQUAL_INTERVALS_1"), - (GetCcType() == - CatClassification::equal_intervals) - && GetNumCats() == 1); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_EQUAL_INTERVALS_2"), - (GetCcType() == - CatClassification::equal_intervals) - && GetNumCats() == 2); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_EQUAL_INTERVALS_3"), - (GetCcType() == - CatClassification::equal_intervals) - && GetNumCats() == 3); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_EQUAL_INTERVALS_4"), - (GetCcType() == - CatClassification::equal_intervals) - && GetNumCats() == 4); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_EQUAL_INTERVALS_5"), - (GetCcType() == - CatClassification::equal_intervals) - && GetNumCats() == 5); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_EQUAL_INTERVALS_6"), - (GetCcType() == - CatClassification::equal_intervals) - && GetNumCats() == 6); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_EQUAL_INTERVALS_7"), - (GetCcType() == - CatClassification::equal_intervals) - && GetNumCats() == 7); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_EQUAL_INTERVALS_8"), - (GetCcType() == - CatClassification::equal_intervals) - && GetNumCats() == 8); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_EQUAL_INTERVALS_9"), - (GetCcType() == - CatClassification::equal_intervals) - && GetNumCats() == 9); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_EQUAL_INTERVALS_10"), - (GetCcType() == - CatClassification::equal_intervals) - && GetNumCats() == 10); - - // since XRCID is a macro, we can't make this into a loop - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_NATURAL_BREAKS_1"), - (GetCcType() == - CatClassification::natural_breaks) - && GetNumCats() == 1); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_NATURAL_BREAKS_2"), - (GetCcType() == - CatClassification::natural_breaks) - && GetNumCats() == 2); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_NATURAL_BREAKS_3"), - (GetCcType() == - CatClassification::natural_breaks) - && GetNumCats() == 3); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_NATURAL_BREAKS_4"), - (GetCcType() == - CatClassification::natural_breaks) - && GetNumCats() == 4); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_NATURAL_BREAKS_5"), - (GetCcType() == - CatClassification::natural_breaks) - && GetNumCats() == 5); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_NATURAL_BREAKS_6"), - (GetCcType() == - CatClassification::natural_breaks) - && GetNumCats() == 6); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_NATURAL_BREAKS_7"), - (GetCcType() == - CatClassification::natural_breaks) - && GetNumCats() == 7); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_NATURAL_BREAKS_8"), - (GetCcType() == - CatClassification::natural_breaks) - && GetNumCats() == 8); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_NATURAL_BREAKS_9"), - (GetCcType() == - CatClassification::natural_breaks) - && GetNumCats() == 9); - GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_NATURAL_BREAKS_10"), - (GetCcType() == - CatClassification::natural_breaks) - && GetNumCats() == 10); - GeneralWxUtils::EnableMenuItem(menu, XRCID("ID_VIEW_LOWESS_SMOOTHER"), enableLowess); GeneralWxUtils::EnableMenuItem(menu, XRCID("ID_EDIT_LOWESS_PARAMS"), enableLowess); - } void ScatterNewPlotCanvas::UpdateSelection(bool shiftdown, bool pointsel) @@ -554,7 +457,7 @@ void ScatterNewPlotCanvas::UpdateSelection(bool shiftdown, bool pointsel) if (IsRegressionSelected() || IsRegressionExcluded()) { // we only need to redraw everything if the optional // regression lines have changed. - Refresh(); + //Refresh(); } } @@ -597,25 +500,41 @@ void ScatterNewPlotCanvas::update(HLStateInt* o) if (IsRegressionSelected() || IsRegressionExcluded()) { // we only need to redraw everything if the optional // regression lines have changed. - Refresh(); + //Refresh(); } } wxString ScatterNewPlotCanvas::GetCanvasTitle() { - wxString s(is_bubble_plot ? "Bubble Chart" : "Scatter Plot"); - s << " - x: " << GetNameWithTime(0) << ", y: " << GetNameWithTime(1); + wxString s; + wxString x_name = GetNameWithTime(0); + wxString y_name = GetNameWithTime(1); + if (is_bubble_plot) { - s << ", size: " << GetNameWithTime(2); - s << ", " << GetCategoriesTitle(); - } + s = _("Bubble Chart - x: %s, y: %s, size: %s, %s"); + s = wxString::Format(s, x_name, y_name, GetNameWithTime(2), GetCategoriesTitle()); + } else { + s = _("Scatter Plot - x: %s, y: %s"); + s = wxString::Format(s, x_name, y_name); + } return s; } +wxString ScatterNewPlotCanvas::GetVariableNames() +{ + wxString s; + wxString x_name = GetNameWithTime(0); + wxString y_name = GetNameWithTime(1); + + s << x_name << ", " << y_name; + + return s; +} + wxString ScatterNewPlotCanvas::GetCategoriesTitle() { if (GetCcType() == CatClassification::no_theme) { - return "Themeless"; + return _("Themeless"); } wxString s; if (GetCcType() == CatClassification::custom) { @@ -703,7 +622,7 @@ void ScatterNewPlotCanvas::NewCustomCatClassif() if (template_frame) { template_frame->UpdateTitle(); if (template_frame->GetTemplateLegend()) { - template_frame->GetTemplateLegend()->Refresh(); + template_frame->GetTemplateLegend()->Recreate(); } } } @@ -749,7 +668,7 @@ ChangeThemeType(CatClassification::CatClassifType new_theme, if (all_init && template_frame) { template_frame->UpdateTitle(); if (template_frame->GetTemplateLegend()) { - template_frame->GetTemplateLegend()->Refresh(); + template_frame->GetTemplateLegend()->Recreate(); } } } @@ -764,7 +683,7 @@ void ScatterNewPlotCanvas::update(CatClassifState* o) if (template_frame) { template_frame->UpdateTitle(); if (template_frame->GetTemplateLegend()) { - template_frame->GetTemplateLegend()->Refresh(); + template_frame->GetTemplateLegend()->Recreate(); } } } @@ -838,10 +757,10 @@ void ScatterNewPlotCanvas::SetSelectableOutlineColor(wxColour color) and refresh the canvas. */ void ScatterNewPlotCanvas::PopulateCanvas() { - //wxSize size(GetVirtualSize()); - //int screen_w = size.GetWidth(); - //int screen_h = size.GetHeight(); - //last_scale_trans.SetView(screen_w, screen_h); + wxSize size(GetVirtualSize()); + int screen_w = size.GetWidth(); + int screen_h = size.GetHeight(); + last_scale_trans.SetView(screen_w, screen_h); pens.SetPenColor(pens.GetRegPen(), selectable_outline_color); @@ -901,18 +820,30 @@ void ScatterNewPlotCanvas::PopulateCanvas() } if (standardized) { + double local_x_max = DBL_MIN; + double local_x_min = DBL_MAX; + double local_y_max = DBL_MIN; + double local_y_min = DBL_MAX; for (int i=0, iend=X.size(); i X[i]) local_x_min = X[i]; + if (local_y_max < Y[i]) local_y_max = Y[i]; + if (local_y_min > Y[i]) local_y_min = Y[i]; } + x_max = local_x_max; + x_min = local_x_min; + y_max = local_y_max; + y_min = local_y_min; // we are ignoring the global scaling option here - x_max = (statsX.max - statsX.mean)/statsX.sd_with_bessel; - x_min = (statsX.min - statsX.mean)/statsX.sd_with_bessel; - y_max = (statsY.max - statsY.mean)/statsY.sd_with_bessel; - y_min = (statsY.min - statsY.mean)/statsY.sd_with_bessel; + //x_max = (statsX.max - statsX.mean)/statsX.sd_with_bessel; + //x_min = (statsX.min - statsX.mean)/statsX.sd_with_bessel; + //y_max = (statsY.max - statsY.mean)/statsY.sd_with_bessel; + //y_min = (statsY.min - statsY.mean)/statsY.sd_with_bessel; statsX = SampleStatistics(X, XYZ_undef); statsY = SampleStatistics(Y, XYZ_undef); @@ -944,10 +875,18 @@ void ScatterNewPlotCanvas::PopulateCanvas() if (var_info[0].is_moran || (!var_info[0].fixed_scale && !standardized)) { x_max = var_info[0].max[var_info[0].time]; x_min = var_info[0].min[var_info[0].time]; + } else if (var_info[0].fixed_scale && !standardized) { + // this is for fixed x-axis over time + x_max = var_info[0].max_over_time; + x_min = var_info[0].min_over_time; } if (var_info[1].is_moran || (!var_info[1].fixed_scale && !standardized)) { y_max = var_info[1].max[var_info[1].time]; y_min = var_info[1].min[var_info[1].time]; + } else if (var_info[1].fixed_scale&& !standardized){ + // this is for fixed y-axis over time + y_max = var_info[1].max_over_time; + y_min = var_info[1].min_over_time; } double x_pad = 0.1 * (x_max - x_min); @@ -1168,8 +1107,6 @@ void ScatterNewPlotCanvas::TimeChange() invalidateBms(); PopulateCanvas(); UpdateStatusBar(); - - Refresh(); } /** Update Secondary Attributes based on Primary Attributes. @@ -1362,8 +1299,7 @@ void ScatterNewPlotCanvas::CreateAndUpdateCategories() void ScatterNewPlotCanvas::TimeSyncVariableToggle(int var_index) { - var_info[var_index].sync_with_global_time = - !var_info[var_index].sync_with_global_time; + var_info[var_index].sync_with_global_time = !var_info[var_index].sync_with_global_time; VarInfoAttributeChange(); CreateAndUpdateCategories(); @@ -1401,12 +1337,14 @@ void ScatterNewPlotCanvas::ShowLinearSmoother(bool display) show_linear_smoother = display; UpdateDisplayStats(); UpdateDisplayLinesAndMargins(); + isResize = true; PopulateCanvas(); } void ScatterNewPlotCanvas::ShowLowessSmoother(bool display) { show_lowess_smoother = display; + isResize = true; PopulateCanvas(); } @@ -1418,7 +1356,10 @@ void ScatterNewPlotCanvas::ChangeLoessParams(double f, int iter, lowess.SetF(f); lowess.SetIter(iter); lowess.SetDeltaFactor(delta_factor); - if (IsShowLowessSmoother()) PopulateCanvas(); + if (IsShowLowessSmoother()) { + isResize = true; + PopulateCanvas(); + } } void ScatterNewPlotCanvas::ViewRegressionSelected(bool display) @@ -1464,7 +1405,6 @@ void ScatterNewPlotCanvas::ViewRegressionSelected(bool display) if (changed) ResizeSelectableShps(); } } - Refresh(); } void ScatterNewPlotCanvas::UpdateRegSelectedLine() @@ -1532,7 +1472,6 @@ void ScatterNewPlotCanvas::ViewRegressionSelectedExcluded(bool display) if (changed) ResizeSelectableShps(); } } - Refresh(); } void ScatterNewPlotCanvas::UpdateRegExcludedLine() @@ -1648,7 +1587,7 @@ void ScatterNewPlotCanvas::ComputeChowTest() s << ", ratio=" << GenUtils::DblToStr(chow_ratio, 4); s << ", p-val=" << GenUtils::DblToStr(chow_pval, 4); } else { - s << "need two valid regressions"; + s << _("need two valid regressions"); } chow_test_text->setText(s); } @@ -1866,7 +1805,7 @@ void ScatterNewPlotCanvas::UpdateStatusBar() if (highlight_state->GetTotalHighlighted()> 0) { int n_total_hl = highlight_state->GetTotalHighlighted(); - s << "#selected=" << n_total_hl << " "; + s << _("#selected=") << n_total_hl << " "; int n_undefs = 0; for (int i=0; i 0) { - s << "(undefined:" << n_undefs << ") "; + s << _("undefined: ") << n_undefs << ") "; } if (brushtype == rectangle) { wxRealPoint pt1 = MousePntToObsPnt(sel1); wxRealPoint pt2 = MousePntToObsPnt(sel2); - wxString xmin = GenUtils::DblToStr(GenUtils::min(pt1.x, - pt2.x)); - wxString xmax = GenUtils::DblToStr(GenUtils::max(pt1.x, - pt2.x)); - wxString ymin = GenUtils::DblToStr(GenUtils::min(pt1.y, - pt2.y)); - wxString ymax = GenUtils::DblToStr(GenUtils::max(pt1.y, - pt2.y)); + wxString xmin = GenUtils::DblToStr(std::min(pt1.x, pt2.x)); + wxString xmax = GenUtils::DblToStr(std::max(pt1.x, pt2.x)); + wxString ymin = GenUtils::DblToStr(std::min(pt1.y, pt2.y)); + wxString ymax = GenUtils::DblToStr(std::max(pt1.y, pt2.y)); } s <<" "; } if (mousemode == select && selectstate == start) { if (total_hover_obs >= 1) { - s << "hover obs " << hover_obs[0]+1 << " = ("; + s << _("#hover obs ") << hover_obs[0]+1 << " = ("; s << X[hover_obs[0]] << ", " << Y[hover_obs[0]]; if (is_bubble_plot) { s << ", " << Z[hover_obs[0]]; @@ -1904,7 +1839,7 @@ void ScatterNewPlotCanvas::UpdateStatusBar() } if (total_hover_obs >= 2) { s << ", "; - s << "obs " << hover_obs[1]+1 << " = ("; + s << _("obs ") << hover_obs[1]+1 << " = ("; s << X[hover_obs[1]] << ", " << Y[hover_obs[1]]; if (is_bubble_plot) { s << ", " << Z[hover_obs[1]]; @@ -1914,7 +1849,7 @@ void ScatterNewPlotCanvas::UpdateStatusBar() } if (total_hover_obs >= 3) { s << ", "; - s << "obs " << hover_obs[2]+1 << " = ("; + s << _("obs ") << hover_obs[2]+1 << " = ("; s << X[hover_obs[2]] << ", " << Y[hover_obs[2]]; if (is_bubble_plot) { s << ", " << Z[hover_obs[2]]; @@ -1962,16 +1897,24 @@ ScatterNewPlotFrame::ScatterNewPlotFrame(wxFrame *parent, Project* project, const wxString& title, const wxPoint& pos, const wxSize& size, - const long style) + const long style, + bool no_init) : TemplateFrame(parent, project, title, pos, size, style), var_info(var_info), is_bubble_plot(is_bubble_plot_s), lowess_param_frame(0) { wxLogMessage("Open ScatterNewPlotFrame."); + if (!no_init) + Init(var_info, col_ids, title); +} + +void ScatterNewPlotFrame::Init(const std::vector& var_info, + const std::vector& col_ids, + const wxString& title) +{ + int width, height; + GetClientSize(&width, &height); - int width, height; - GetClientSize(&width, &height); - wxSplitterWindow* splitter_win = 0; if (is_bubble_plot) { splitter_win = new wxSplitterWindow(this,-1,wxDefaultPosition, wxDefaultSize, wxSP_3D|wxSP_LIVE_UPDATE|wxCLIP_CHILDREN); @@ -2000,7 +1943,10 @@ is_bubble_plot(is_bubble_plot_s), lowess_param_frame(0) } template_canvas->SetScrollRate(1,1); DisplayStatusBar(true); - SetTitle(template_canvas->GetCanvasTitle()); + if (title.empty()) + SetTitle(template_canvas->GetCanvasTitle()); + else + SetTitle(title); if (is_bubble_plot) { lpanel = new wxPanel(splitter_win); @@ -2055,7 +2001,7 @@ void ScatterNewPlotFrame::MapMenus() ((ScatterNewPlotCanvas*) template_canvas)-> AddTimeVariantOptionsToMenu(optMenu); ((ScatterNewPlotCanvas*) template_canvas)->SetCheckMarks(optMenu); - GeneralWxUtils::ReplaceMenu(mb, "Options", optMenu); + GeneralWxUtils::ReplaceMenu(mb, _("Options"), optMenu); UpdateOptionMenuItems(); } @@ -2069,7 +2015,7 @@ void ScatterNewPlotFrame::UpdateOptionMenuItems() { TemplateFrame::UpdateOptionMenuItems(); // set common items first wxMenuBar* mb = GdaFrame::GetGdaFrame()->GetMenuBar(); - int menu = mb->FindMenu("Options"); + int menu = mb->FindMenu(_("Options")); if (menu == wxNOT_FOUND) { } else { ((ScatterNewPlotCanvas*) template_canvas)-> @@ -2278,3 +2224,126 @@ void ScatterNewPlotFrame::GetVizInfo(wxString& x, wxString& y) } } +void ScatterNewPlotFrame::ExportImage(TemplateCanvas* canvas, const wxString& type) +{ + if (is_bubble_plot) { + // main map + wxBitmap* main_map = template_canvas->GetPrintLayer(); + int map_width = main_map->GetWidth(); + int map_height = main_map->GetHeight(); + + // try to keep maplayout dialog fixed size + int dlg_width = 900; + int dlg_height = dlg_width * map_height / (double)map_width + 160; + + CanvasLayoutDialog ml_dlg(project->GetProjectTitle(), + template_legend, template_canvas, + _("Canvas Layout Preview"), + wxDefaultPosition, + wxSize(dlg_width, dlg_height) ); + + ml_dlg.ShowModal(); + } else { + TemplateFrame::ExportImage(canvas, type); + } +} +///////////////////////////////////////////////////// +IMPLEMENT_CLASS(MDSPlotCanvas, TemplateCanvas) +BEGIN_EVENT_TABLE(MDSPlotCanvas, TemplateCanvas) +END_EVENT_TABLE() + +MDSPlotCanvas::MDSPlotCanvas(wxWindow *parent, TemplateFrame* t_frame, Project* project, const wxPoint& pos, const wxSize& size) +: ScatterNewPlotCanvas(parent, t_frame, project, pos, size) +{ + +} + +MDSPlotCanvas::MDSPlotCanvas(wxWindow *parent, TemplateFrame* t_frame, Project* project, const std::vector& var_info, const std::vector& col_ids,bool is_bubble_plot, bool standardized, const wxPoint& pos, const wxSize& size) +: ScatterNewPlotCanvas(parent, t_frame, project, var_info, col_ids, is_bubble_plot, standardized, pos, size) +{ + +} + +MDSPlotCanvas::~MDSPlotCanvas() +{ + +} + +void MDSPlotCanvas::DisplayRightClickMenu(const wxPoint& pos) +{ + // Workaround for right-click not changing window focus in OSX / wxW 3.0 + wxActivateEvent ae(wxEVT_NULL, true, 0, wxActivateEvent::Reason_Mouse); + ((MDSPlotFrame*) template_frame)->OnActivate(ae); + + wxMenu* optMenu = wxXmlResource::Get()-> + LoadMenu("ID_SCATTER_NEW_PLOT_VIEW_MENU_OPTIONS"); + AddTimeVariantOptionsToMenu(optMenu); + + wxString menu_txt = _("Create Weights"); + optMenu->Prepend(XRCID("MDS_WEIGHTS"), menu_txt); + optMenu->AppendSeparator(); + + template_frame->Connect(XRCID("MDS_WEIGHTS"), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MDSPlotFrame::OnCreateWeights)); + + SetCheckMarks(optMenu); + + template_frame->UpdateContextMenuItems(optMenu); + template_frame->PopupMenu(optMenu, pos + GetPosition()); + template_frame->UpdateOptionMenuItems(); +} + +void MDSPlotCanvas::OnCreateWeights() +{ + wxLogMessage("On MDSPlotCanvas::OnCreateWeights()"); + + CreatingWeightDlg dlg(this, project, true); + dlg.SetXCOO(X); + dlg.SetYCOO(Y); + dlg.ShowModal(); +} + + +IMPLEMENT_CLASS(MDSPlotFrame, TemplateFrame) +BEGIN_EVENT_TABLE(MDSPlotFrame, TemplateFrame) +EVT_ACTIVATE(MDSPlotFrame::OnActivate) +END_EVENT_TABLE() + +MDSPlotFrame::MDSPlotFrame(wxFrame *parent, Project* project, const wxPoint& pos, const wxSize& size, const long style) +: ScatterNewPlotFrame(parent, project, pos, size, style) +{ +} + +MDSPlotFrame::MDSPlotFrame(wxFrame *parent, Project* project, const std::vector& var_info, const std::vector& col_ids, bool is_bubble_plot, const wxString& title, const wxPoint& pos, const wxSize& size, const long style) +: ScatterNewPlotFrame(parent, project, var_info, col_ids, is_bubble_plot, title, pos, size, style, true) +{ + wxLogMessage("Open MDSPlotFrame."); + int width, height; + GetClientSize(&width, &height); + wxSplitterWindow* splitter_win = 0; + if (is_bubble_plot) { + splitter_win = new wxSplitterWindow(this,-1,wxDefaultPosition, wxDefaultSize, wxSP_3D|wxSP_LIVE_UPDATE|wxCLIP_CHILDREN); + splitter_win->SetMinimumPaneSize(10); + } + template_canvas = new MDSPlotCanvas(this, this, project, + var_info, col_ids, + is_bubble_plot, + false, wxDefaultPosition, + wxSize(width,height)); + template_canvas->SetScrollRate(1,1); + DisplayStatusBar(true); + SetTitle(title); + if (title.empty()) + SetTitle(template_canvas->GetCanvasTitle()); + Show(true); +} + +MDSPlotFrame::~MDSPlotFrame() +{ + wxLogMessage("Close ~MDSPlotFrame."); +} + +void MDSPlotFrame::OnCreateWeights(wxCommandEvent& event) +{ + wxLogMessage("In MDSPlotFrame::OnCreateWeights()"); + ((MDSPlotCanvas*) template_canvas)->OnCreateWeights(); +} diff --git a/Explore/ScatterNewPlotView.h b/Explore/ScatterNewPlotView.h index 68bc659b5..f675fc961 100644 --- a/Explore/ScatterNewPlotView.h +++ b/Explore/ScatterNewPlotView.h @@ -48,7 +48,7 @@ typedef boost::multi_array i_array_type; class BubbleSizeSliderDlg: public wxDialog { public: - BubbleSizeSliderDlg (ScatterNewPlotCanvas* _canvas, const wxString & caption="Bubble Size Adjust Dialog"); + BubbleSizeSliderDlg (ScatterNewPlotCanvas* _canvas, const wxString & caption=_("Bubble Size Adjust Dialog")); private: ScatterNewPlotCanvas* canvas; @@ -81,6 +81,7 @@ public TemplateCanvas, public CatClassifStateObserver virtual void AddTimeVariantOptionsToMenu(wxMenu* menu); virtual void update(HLStateInt* o); virtual wxString GetCanvasTitle(); + virtual wxString GetVariableNames(); virtual wxString GetCategoriesTitle(); virtual wxString GetNameWithTime(int var); virtual void NewCustomCatClassif(); @@ -98,16 +99,8 @@ public TemplateCanvas, public CatClassifStateObserver /// Override from TemplateCanvas virtual void SetSelectableOutlineColor(wxColour color); -protected: - virtual void TimeChange(); - virtual void PopulateCanvas(); - virtual void PopCanvPreResizeShpsHook(); - void VarInfoAttributeChange(); - -public: void CreateAndUpdateCategories(); -public: virtual void UpdateSelection(bool shiftdown, bool pointsel); virtual void TimeSyncVariableToggle(int var_index); virtual void FixedScaleVariableToggle(int var_index); @@ -139,18 +132,22 @@ public TemplateCanvas, public CatClassifStateObserver double bubble_size_scaler; -protected: void ComputeChowTest(); void UpdateRegSelectedLine(); void UpdateRegExcludedLine(); void UpdateDisplayStats(); void UpdateAxesThroughOrigin(); - - ScatterPlotPens pens; virtual void UpdateStatusBar(); - + +protected: + virtual void TimeChange(); + virtual void PopulateCanvas(); + virtual void PopCanvPreResizeShpsHook(); + void VarInfoAttributeChange(); + + ScatterPlotPens pens; bool is_bubble_plot; Project* project; CatClassifState* custom_classif_state; @@ -251,16 +248,16 @@ public TemplateCanvas, public CatClassifStateObserver int table_display_lines; bool UpdateDisplayLinesAndMargins(); bool all_init; - - + DECLARE_EVENT_TABLE() }; class ScatterNewPlotLegend : public TemplateLegend { public: - ScatterNewPlotLegend(wxWindow *parent, TemplateCanvas* template_canvas, - const wxPoint& pos, const wxSize& size); + ScatterNewPlotLegend(wxWindow *parent, + TemplateCanvas* template_canvas, + const wxPoint& pos, const wxSize& size); virtual ~ScatterNewPlotLegend(); }; @@ -280,7 +277,8 @@ class ScatterNewPlotFrame : public TemplateFrame, public LowessParamObserver const wxString& title = _("Scatter Plot"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, - const long style = wxDEFAULT_FRAME_STYLE); + const long style = wxDEFAULT_FRAME_STYLE, + bool no_init = false); virtual ~ScatterNewPlotFrame(); @@ -320,7 +318,8 @@ class ScatterNewPlotFrame : public TemplateFrame, public LowessParamObserver virtual void OnNaturalBreaks(int num_cats); virtual void OnEqualIntervals(int num_cats); virtual void OnSaveCategories(); - + virtual void ExportImage(TemplateCanvas* canvas, const wxString& type); + /** Implementation of LowessParamObserver interface */ virtual void update(LowessParamObservable* o); virtual void notifyOfClosing(LowessParamObservable* o); @@ -328,9 +327,11 @@ class ScatterNewPlotFrame : public TemplateFrame, public LowessParamObserver void GetVizInfo(wxString& x, wxString& y); protected: - void ChangeThemeType(CatClassification::CatClassifType new_theme, - int num_categories, - const wxString& custom_classif_title = wxEmptyString); + void Init(const std::vector& var_info, + const std::vector& col_ids, const wxString& title); + void ChangeThemeType(CatClassification::CatClassifType new_theme, + int num_categories, + const wxString& custom_classif_title = wxEmptyString); bool is_bubble_plot; LowessParamFrame* lowess_param_frame; @@ -340,5 +341,54 @@ class ScatterNewPlotFrame : public TemplateFrame, public LowessParamObserver DECLARE_EVENT_TABLE() }; +class MDSPlotCanvas : public ScatterNewPlotCanvas +{ + DECLARE_CLASS(MDSPlotCanvas) +public: + MDSPlotCanvas(wxWindow *parent, TemplateFrame* t_frame, + Project* project, + const wxPoint& pos = wxDefaultPosition, + const wxSize& size = wxDefaultSize); + MDSPlotCanvas(wxWindow *parent, TemplateFrame* t_frame, + Project* project, + const std::vector& var_info, + const std::vector& col_ids, + bool is_bubble_plot = false, + bool standardized = false, + const wxPoint& pos = wxDefaultPosition, + const wxSize& size = wxDefaultSize); + virtual ~MDSPlotCanvas(); + + virtual void DisplayRightClickMenu(const wxPoint& pos); + + void OnCreateWeights(); + + DECLARE_EVENT_TABLE() +}; + +class MDSPlotFrame : public ScatterNewPlotFrame +{ + DECLARE_CLASS(MDSPlotFrame) +public: + MDSPlotFrame(wxFrame *parent, Project* project, + const wxPoint& pos = wxDefaultPosition, + const wxSize& size = wxDefaultSize, + const long style = wxDEFAULT_FRAME_STYLE); + + MDSPlotFrame(wxFrame *parent, Project* project, + const std::vector& var_info, + const std::vector& col_ids, + bool is_bubble_plot, + const wxString& title = _("MDS Plot"), + const wxPoint& pos = wxDefaultPosition, + const wxSize& size = wxDefaultSize, + const long style = wxDEFAULT_FRAME_STYLE); + + virtual ~MDSPlotFrame(); + + void OnCreateWeights(wxCommandEvent& event); + + DECLARE_EVENT_TABLE() +}; #endif diff --git a/Explore/ScatterPlotMatView.cpp b/Explore/ScatterPlotMatView.cpp index 424155123..4e9133428 100644 --- a/Explore/ScatterPlotMatView.cpp +++ b/Explore/ScatterPlotMatView.cpp @@ -22,6 +22,7 @@ #include #include #include +#include "../GeneralWxUtils.h" #include "../DialogTools/AdjustYAxisDlg.h" #include "../HighlightState.h" #include "../GeneralWxUtils.h" @@ -47,7 +48,7 @@ ScatterPlotMatFrame::ScatterPlotMatFrame(wxFrame *parent, Project* project, : TemplateFrame(parent, project, title, pos, size, wxDEFAULT_FRAME_STYLE), lowess_param_frame(0), vars_chooser_frame(0), panel(0), panel_v_szr(0), bag_szr(0), top_h_sizer(0), view_standardized_data(false), -show_regimes(true), show_outside_titles(true), show_linear_smoother(true), +show_regimes(false), show_outside_titles(true), show_linear_smoother(true), show_lowess_smoother(false), show_slope_values(true), brush_rectangle(true), brush_circle(false), brush_line(false), selectable_outline_color(GdaConst::scatterplot_regression_color), @@ -68,7 +69,7 @@ axis_display_precision(1) GetClientSize(&width, &height); panel = new wxPanel(this); - panel->SetBackgroundColour(*wxWHITE); + SetBackgroundColour(*wxWHITE); panel->Bind(wxEVT_MOTION, &ScatterPlotMatFrame::OnMouseEvent, this); @@ -90,7 +91,8 @@ axis_display_precision(1) panel_h_szr->Add(panel_v_szr, 1, wxEXPAND); panel->SetSizer(panel_h_szr); - + panel->SetBackgroundColour(*wxWHITE); + UpdateMessageWin(); // Top Sizer for Frame @@ -133,6 +135,12 @@ void ScatterPlotMatFrame::OnActivate(wxActivateEvent& event) //if ( event.GetActive() && template_canvas ) template_canvas->SetFocus(); } +void ScatterPlotMatFrame::OnSaveScreen(wxCommandEvent& event) +{ + wxString title = project->GetProjectTitle(); + GeneralWxUtils::SaveWindowAsImage(panel, title); +} + void ScatterPlotMatFrame::MapMenus() { wxMenuBar* mb = GdaFrame::GetGdaFrame()->GetMenuBar(); @@ -140,15 +148,14 @@ void ScatterPlotMatFrame::MapMenus() wxMenu* optMenu; optMenu = wxXmlResource::Get()->LoadMenu("ID_SCATTER_PLOT_MAT_MENU_OPTIONS"); ScatterPlotMatFrame::UpdateContextMenuItems(optMenu); - - GeneralWxUtils::ReplaceMenu(mb, "Options", optMenu); + GeneralWxUtils::ReplaceMenu(mb, _("Options"), optMenu); UpdateOptionMenuItems(); } void ScatterPlotMatFrame::UpdateOptionMenuItems() { wxMenuBar* mb = GdaFrame::GetGdaFrame()->GetMenuBar(); - int menu = mb->FindMenu("Options"); + int menu = mb->FindMenu(_("Options")); if (menu == wxNOT_FOUND) { } else { ScatterPlotMatFrame::UpdateContextMenuItems(mb->GetMenu(menu)); @@ -161,6 +168,13 @@ void ScatterPlotMatFrame::UpdateContextMenuItems(wxMenu* menu) // following menu items if they were specified for this particular // view in the xrc file. Items that cannot be enable/disabled, // or are not checkable do not appear. + menu->AppendSeparator(); + wxString menu_txt = _("Save Image As"); + menu->Append(XRCID("SAVE_SCATTER_MAT"), menu_txt); + + + Connect(XRCID("SAVE_SCATTER_MAT"), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(ScatterPlotMatFrame::OnSaveScreen)); + GeneralWxUtils::CheckMenuItem(menu, XRCID("ID_SELECT_WITH_RECT"), brush_rectangle); @@ -219,7 +233,7 @@ void ScatterPlotMatFrame::OnSelectWithLine(wxCommandEvent& event) void ScatterPlotMatFrame::OnSelectableOutlineColor(wxCommandEvent& event) { wxColour new_color; - if (GetColorFromUser(this,selectable_outline_color,new_color,"Outline Color")) + if (GetColorFromUser(this,selectable_outline_color,new_color, _("Outline Color"))) { for (size_t i=0, sz=scatt_plots.size(); iSetSelectableOutlineColor(new_color); @@ -230,7 +244,7 @@ void ScatterPlotMatFrame::OnSelectableOutlineColor(wxCommandEvent& event) void ScatterPlotMatFrame::OnSelectableFillColor(wxCommandEvent& event) { wxColour new_color; - if (GetColorFromUser(this,selectable_fill_color,new_color,"Fill Color")) + if (GetColorFromUser(this,selectable_fill_color,new_color, _("Fill Color"))) { for (size_t i=0, sz=scatt_plots.size(); iSetSelectableFillColor(new_color); @@ -508,12 +522,11 @@ void ScatterPlotMatFrame::SetupPanelForNumVariables(int num_vars) continue; } wxString col_nm(var_man.GetName(col)); - int col_tm(var_man.GetTime(col)); - - if (data_map[row_nm].size() == 1) - col_tm = 0; - - const vector& X_undef(data_undef_map[col_nm][col_tm]); + int col_tm = 0; + if (!var_man.IsTimeVariant(col)) { + col_tm = var_man.GetTime(col); + } + const vector& X_undef = data_undef_map[col_nm][col_tm]; for (size_t ii=0; iiAdd(sa_can, wxGBPosition(row, 0), wxGBSpan(1,1), wxEXPAND); + sa_can->SetBackgroundColour(*wxWHITE); vert_labels.push_back(sa_can); sa_can = new SimpleAxisCanvas(panel, this, project, diff --git a/Explore/ScatterPlotMatView.h b/Explore/ScatterPlotMatView.h index 81419f1db..7112ab6b0 100644 --- a/Explore/ScatterPlotMatView.h +++ b/Explore/ScatterPlotMatView.h @@ -127,6 +127,8 @@ class ScatterPlotMatFrame : public TemplateFrame, public LowessParamObserver, pu virtual void notifyOfClosing(VarsChooserObservable* o); virtual void OnSetDisplayPrecision(wxCommandEvent& event); + + void OnSaveScreen(wxCommandEvent& event); void GetVizInfo(vector& vars); diff --git a/Explore/SimpleAxisCanvas.cpp b/Explore/SimpleAxisCanvas.cpp index 02df5e0af..58b15aadf 100644 --- a/Explore/SimpleAxisCanvas.cpp +++ b/Explore/SimpleAxisCanvas.cpp @@ -78,9 +78,8 @@ is_standardized(is_standardized_) PopulateCanvas(); ResizeSelectableShps(); - - SetBackgroundStyle(wxBG_STYLE_CUSTOM); // default style } + SimpleAxisCanvas::SimpleAxisCanvas(wxWindow *parent, TemplateFrame* t_frame, Project* project, HLStateInt* hl_state_int, @@ -125,7 +124,6 @@ is_standardized(is_standardized_) PopulateCanvas(); ResizeSelectableShps(); - SetBackgroundStyle(wxBG_STYLE_CUSTOM); // default style LOG_MSG("Exiting SimpleAxisCanvas::SimpleAxisCanvas"); } @@ -160,7 +158,7 @@ void SimpleAxisCanvas::PopulateCanvas() selectable_shps.clear(); BOOST_FOREACH( GdaShape* shp, foreground_shps ) { delete shp; } foreground_shps.clear(); - + wxSize size(GetVirtualSize()); int win_width = size.GetWidth(); int win_height = size.GetHeight(); @@ -210,10 +208,12 @@ void SimpleAxisCanvas::PopulateCanvas() // create axes if (horiz_orient) { x_baseline = new GdaAxis(Xname, axis_scale_x, - wxRealPoint(0,0), wxRealPoint(100, 0)); + wxRealPoint(0,0), wxRealPoint(100, 0), + 0, 0, true); } else { x_baseline = new GdaAxis(Xname, axis_scale_x, - wxRealPoint(0,0), wxRealPoint(0, 100)); + wxRealPoint(0,0), wxRealPoint(0, 100), + 0, 0, true); } x_baseline->autoDropScaleValues(true); x_baseline->moveOuterValTextInwards(true); diff --git a/Explore/SimpleAxisCanvas.h b/Explore/SimpleAxisCanvas.h index b38153d67..b3cc96b48 100644 --- a/Explore/SimpleAxisCanvas.h +++ b/Explore/SimpleAxisCanvas.h @@ -71,6 +71,7 @@ class SimpleAxisCanvas : public TemplateCanvas virtual ~SimpleAxisCanvas(); virtual void UpdateStatusBar(); + virtual wxString GetVariableNames() {return wxEmptyString;} void ShowAxes(bool display); bool IsShowAxes() { return show_axes; } diff --git a/Explore/SimpleBinsHistCanvas.cpp b/Explore/SimpleBinsHistCanvas.cpp index c636b2e48..ca242b857 100644 --- a/Explore/SimpleBinsHistCanvas.cpp +++ b/Explore/SimpleBinsHistCanvas.cpp @@ -36,7 +36,8 @@ #include "../logger.h" #include "../GeoDa.h" #include "../Project.h" -#include "../ShapeOperations/ShapeUtils.h" + +#include "CorrelogramView.h" #include "SimpleBinsHistCanvas.h" IMPLEMENT_CLASS(SimpleBinsHistCanvas, TemplateCanvas) @@ -105,17 +106,10 @@ SimpleBinsHistCanvas::~SimpleBinsHistCanvas() void SimpleBinsHistCanvas::DisplayRightClickMenu(const wxPoint& pos) { LOG_MSG("Entering SimpleBinsHistCanvas::DisplayRightClickMenu"); - if (right_click_menu_id.IsEmpty()) return; - // Workaround for right-click not changing window focus in OSX / wxW 3.0 - wxActivateEvent ae(wxEVT_NULL, true, 0, wxActivateEvent::Reason_Mouse); - template_frame->OnActivate(ae); - - wxMenu* optMenu; - optMenu = wxXmlResource::Get()->LoadMenu(right_click_menu_id); - - template_frame->UpdateContextMenuItems(optMenu); - template_frame->PopupMenu(optMenu, pos + GetPosition()); - template_frame->UpdateOptionMenuItems(); + if (right_click_menu_id.IsEmpty()) return; + if (sbh_canv_cb) { + sbh_canv_cb->OnRightClick(pos+ GetPosition()); + } LOG_MSG("Exiting SimpleBinsHistCanvas::DisplayRightClickMenu"); } @@ -134,6 +128,13 @@ wxString SimpleBinsHistCanvas::GetCanvasTitle() return s; } +wxString SimpleBinsHistCanvas::GetVariableNames() +{ + wxString s; + s << Xname; + return s; +} + void SimpleBinsHistCanvas::TimeSyncVariableToggle(int var_index) { LOG_MSG("In SimpleBinsHistCanvas::TimeSyncVariableToggle"); @@ -166,7 +167,7 @@ void SimpleBinsHistCanvas::PopulateCanvas() selectable_shps.clear(); BOOST_FOREACH( GdaShape* shp, foreground_shps ) { delete shp; } foreground_shps.clear(); - + double num_ivals_d = (double) hist_bins.size(); double x_min = 0; double x_max = left_pad_const + right_pad_const @@ -183,10 +184,11 @@ void SimpleBinsHistCanvas::PopulateCanvas() double y_max = hist_bins_max; last_scale_trans.SetData(x_min, 0, x_max, y_max); + if (show_axes) { axis_scale_y = AxisScale(0, y_max, 5, axis_display_precision); y_max = axis_scale_y.scale_max; - y_axis = new GdaAxis("Frequency", axis_scale_y, + y_axis = new GdaAxis(_("Frequency"), axis_scale_y, wxRealPoint(0,0), wxRealPoint(0, y_max), -9, 0); foreground_shps.push_back(y_axis); @@ -210,7 +212,10 @@ void SimpleBinsHistCanvas::PopulateCanvas() axis_scale_x.data_min + range*((double) i)/((double) axis_scale_x.ticks-1); std::ostringstream ss; - ss << std::fixed << std::setprecision(3) << axis_scale_x.tics[i]; + if ( axis_scale_x.tics[i] == (int) axis_scale_x.tics[i]) + ss << wxString::Format("%d", (int)axis_scale_x.tics[i]); + else + ss << std::fixed << std::setprecision(3) << axis_scale_x.tics[i]; axis_scale_x.tics_str[i] = ss.str(); axis_scale_x.tics_str_show[i] = false; } diff --git a/Explore/SimpleBinsHistCanvas.h b/Explore/SimpleBinsHistCanvas.h index 679dc7db0..ce43b3a8b 100644 --- a/Explore/SimpleBinsHistCanvas.h +++ b/Explore/SimpleBinsHistCanvas.h @@ -36,8 +36,8 @@ class Project; class SimpleBinsHistCanvasCbInt { public: - virtual void notifyNewHistHover(const std::vector& hover_obs, - int total_hover_obs) = 0; + virtual void notifyNewHistHover(const std::vector& hover_obs, int total_hover_obs) = 0; + virtual void OnRightClick(const wxPoint& pos) = 0; }; @@ -67,16 +67,17 @@ class SimpleBinsHistCanvas : public TemplateCanvas virtual void DisplayRightClickMenu(const wxPoint& pos); virtual void update(HLStateInt* o); virtual wxString GetCanvasTitle(); - + virtual wxString GetVariableNames(); virtual void TimeSyncVariableToggle(int var_index); virtual void FixedScaleVariableToggle(int var_index); void ShowAxes(bool show_axes); bool IsShowAxes() { return show_axes; } -protected: virtual void PopulateCanvas(); virtual void UpdateStatusBar(); + +protected: std::vector hist_bins; wxString Xname; diff --git a/Explore/SimpleHistCanvas.cpp b/Explore/SimpleHistCanvas.cpp index d31e8959f..a9dbfa55a 100644 --- a/Explore/SimpleHistCanvas.cpp +++ b/Explore/SimpleHistCanvas.cpp @@ -36,7 +36,7 @@ #include "../logger.h" #include "../GeoDa.h" #include "../Project.h" -#include "../ShapeOperations/ShapeUtils.h" + #include "SimpleHistCanvas.h" using namespace std; @@ -69,7 +69,6 @@ labels(lbls), values(vals), stats(stats_), right_click_menu_id(right_click_menu_ { last_scale_trans.SetFixedAspectRatio(false); PopulateCanvas(); - SetBackgroundStyle(wxBG_STYLE_CUSTOM); // default style highlight_state->registerObserver(this); } @@ -78,6 +77,10 @@ SimpleHistStatsCanvas::~SimpleHistStatsCanvas() highlight_state->removeObserver(this); } +void SimpleHistStatsCanvas::UpdateStatusBar() +{ + +} void SimpleHistStatsCanvas::PopulateCanvas() { BOOST_FOREACH( GdaShape* shp, background_shps ) { delete shp; } @@ -128,17 +131,17 @@ void SimpleHistStatsCanvas::PopulateCanvas() GdaShapeText::VertAlignment cell_v_align = GdaShapeText::v_center; int row_gap = 3; int col_gap = 10; - int x_nudge = -22; + int x_nudge = -12; #ifdef __WIN32__ - int y_nudge = -80; + int y_nudge = -100; #else - int y_nudge = -70; + int y_nudge = -95; #endif int virtual_screen_marg_top = 0;//20; int virtual_screen_marg_right = 0;//20; - int virtual_screen_marg_bottom = 5;//45; + int virtual_screen_marg_bottom = 0;//45; int virtual_screen_marg_left = 45;//45; last_scale_trans.SetMargin(virtual_screen_marg_top, virtual_screen_marg_bottom, @@ -154,7 +157,11 @@ void SimpleHistStatsCanvas::PopulateCanvas() wxClientDC dc(this); ((GdaShapeTable*) s)->GetSize(dc, table_w, table_h); - + // get row gap in multi-language case + wxSize sz_0 = dc.GetTextExtent(labels[0]); + wxSize sz_1 = dc.GetTextExtent("0.0"); + row_gap = 3 + sz_0.GetHeight() - sz_1.GetHeight(); + for (int i=0; i vals(rows); vals[0] << GenUtils::DblToStr(values[i][0], 3); @@ -169,17 +176,17 @@ void SimpleHistStatsCanvas::PopulateCanvas() wxRealPoint(orig_x_pos[i], 0), GdaShapeText::h_center, GdaShapeText::top, GdaShapeText::h_center, GdaShapeText::v_center, - 3, 10, 0, y_nudge); + row_gap, 10, 10, y_nudge); foreground_shps.push_back(s1); } wxString sts; - sts << "min: " << stats[0]; - sts << ", max: " << wxString::Format("%.3f", stats[1]); - sts << ", total # pairs: " << stats[2]; + sts << _("min:") <<" " << stats[0]; + sts << ", " << _("max:") << " " << wxString::Format("%.3f", stats[1]); + sts << ", " << _("total # pairs") << ": " << stats[2]; if (stats[5] >= 0) { - sts << ", Autocorr. = 0 at " << wxString::Format("~%.3f", stats[5]); - sts << " in range: [" << wxString::Format("%.3f", stats[3]) << "," << wxString::Format("%.3f", stats[4]) << "]"; + sts << ", " << _("Autocorr.") << _(" = 0 at ") << wxString::Format("~%.3f", stats[5]); + sts << _(" in range:") << " [" << wxString::Format("%.3f", stats[3]) << ", " << wxString::Format("%.3f", stats[4]) << "]"; } s = new GdaShapeText(sts, *GdaConst::small_font, @@ -262,12 +269,12 @@ obs_id_to_ival(X.size()) hinge_stats.CalculateHingeStats(data_sorted, noundef); int num_obs = data_sorted.size(); - max_intervals = GenUtils::min(MAX_INTERVALS, num_obs); - cur_intervals = GenUtils::min(max_intervals, default_intervals); + max_intervals = std::min(MAX_INTERVALS, num_obs); + cur_intervals = std::min(max_intervals, default_intervals); if (num_obs > 49) { int c = sqrt((double) num_obs); - cur_intervals = GenUtils::min(max_intervals, c); - cur_intervals = GenUtils::min(cur_intervals, 25); + cur_intervals = std::min(max_intervals, c); + cur_intervals = std::min(cur_intervals, 25); } highlight_color = GdaConst::highlight_color; @@ -319,6 +326,13 @@ wxString SimpleHistCanvas::GetCanvasTitle() return s; } +wxString SimpleHistCanvas::GetVariableNames() +{ + wxString s; + s << Xname; + return s; +} + void SimpleHistCanvas::TimeSyncVariableToggle(int var_index) { invalidateBms(); @@ -570,7 +584,7 @@ void SimpleHistCanvas::PopulateCanvas() selectable_shps.clear(); BOOST_FOREACH( GdaShape* shp, foreground_shps ) { delete shp; } foreground_shps.clear(); - + double x_min = 0; double x_max = left_pad_const + right_pad_const + interval_width_const * cur_intervals + interval_gap_const * (cur_intervals-1); @@ -582,10 +596,11 @@ void SimpleHistCanvas::PopulateCanvas() double y_max = overall_max_num_obs_in_ival; last_scale_trans.SetData(x_min, 0, x_max, y_max); + if (show_axes) { axis_scale_y = AxisScale(0, y_max, 5, axis_display_precision); y_max = axis_scale_y.scale_max; - y_axis = new GdaAxis("Frequency", axis_scale_y, + y_axis = new GdaAxis(_("Frequency"), axis_scale_y, wxRealPoint(0,0), wxRealPoint(0, y_max), -9, 0); foreground_shps.push_back(y_axis); @@ -633,11 +648,11 @@ void SimpleHistCanvas::PopulateCanvas() int cols = 1; int rows = 5; std::vector vals(rows); - vals[0] << "from"; - vals[1] << "to"; - vals[2] << "#obs"; - vals[3] << "% of total"; - vals[4] << "sd from mean"; + vals[0] << _("from"); + vals[1] << _("to"); + vals[2] << _("#obs"); + vals[3] << _("% of total"); + vals[4] << _("sd from mean"); std::vector attribs(0); // undefined s = new GdaShapeTable(vals, attribs, rows, cols, *GdaConst::small_font, wxRealPoint(0, 0), GdaShapeText::h_center, @@ -645,10 +660,15 @@ void SimpleHistCanvas::PopulateCanvas() GdaShapeText::right, GdaShapeText::v_center, 3, 10, -62, 53+y_d); foreground_shps.push_back(s); - { - wxClientDC dc(this); - ((GdaShapeTable*) s)->GetSize(dc, table_w, table_h); - } + + wxClientDC dc(this); + ((GdaShapeTable*) s)->GetSize(dc, table_w, table_h); + + // get row gap in multi-language case + wxSize sz_0 = dc.GetTextExtent(vals[0]); + wxSize sz_1 = dc.GetTextExtent("0.0"); + int row_gap = 3 + sz_0.GetHeight() - sz_1.GetHeight(); + int num_obs = X.size(); for (int i=0; i vals(rows); @@ -675,18 +695,18 @@ void SimpleHistCanvas::PopulateCanvas() wxRealPoint(orig_x_pos[i], 0), GdaShapeText::h_center, GdaShapeText::top, GdaShapeText::h_center, GdaShapeText::v_center, - 3, 10, 0, + row_gap, 10, 0, 53+y_d); foreground_shps.push_back(s); } - wxString sts; - sts << "min: " << data_stats.min; - sts << ", max: " << data_stats.max; - sts << ", median: " << hinge_stats.Q2; - sts << ", mean: " << data_stats.mean; - sts << ", s.d.: " << data_stats.sd_with_bessel; - sts << ", #obs: " << X.size(); + wxString sts; + sts << _("min:") << " " << data_stats.min; + sts << ", " << _("max:") << " " << data_stats.max; + sts << ", " << _("median:") << " " << hinge_stats.Q2; + sts << ", " << _("mean:") << " " << data_stats.mean; + sts << ", " << _("s.d.:") << " " << data_stats.sd_with_bessel; + sts << ", " << _("#obs:") << " " << X.size(); s = new GdaShapeText(sts, *GdaConst::small_font, wxRealPoint(x_max/2.0, 0), 0, @@ -728,7 +748,7 @@ void SimpleHistCanvas::PopulateCanvas() selectable_shps[i]->setPen(GdaConst::qualitative_colors[i%sz]); selectable_shps[i]->setBrush(GdaConst::qualitative_colors[i%sz]); } - + ResizeSelectableShps(); LOG_MSG("Exiting SimpleHistCanvas::PopulateCanvas"); } diff --git a/Explore/SimpleHistCanvas.h b/Explore/SimpleHistCanvas.h index 21c660fb4..5dffe76af 100644 --- a/Explore/SimpleHistCanvas.h +++ b/Explore/SimpleHistCanvas.h @@ -53,7 +53,9 @@ class SimpleHistStatsCanvas : public TemplateCanvas virtual void DisplayRightClickMenu(const wxPoint& pos); virtual void update(HLStateInt* o); - + virtual void UpdateStatusBar(); + virtual wxString GetVariableNames() {return wxEmptyString;} + protected: virtual void PopulateCanvas(); @@ -81,7 +83,7 @@ class SimpleHistCanvas : public TemplateCanvas virtual void DisplayRightClickMenu(const wxPoint& pos); virtual void update(HLStateInt* o); virtual wxString GetCanvasTitle(); - + virtual wxString GetVariableNames(); virtual void TimeSyncVariableToggle(int var_index); virtual void FixedScaleVariableToggle(int var_index); @@ -98,10 +100,10 @@ class SimpleHistCanvas : public TemplateCanvas void HistogramIntervals(); void InitIntervals(); void UpdateIvalSelCnts(); -protected: virtual void PopulateCanvas(); virtual void UpdateStatusBar(); +protected: const vector& X; const vector& X_undef; wxString Xname; diff --git a/Explore/SimpleScatterPlotCanvas.cpp b/Explore/SimpleScatterPlotCanvas.cpp index 4baedf71b..d638baa53 100644 --- a/Explore/SimpleScatterPlotCanvas.cpp +++ b/Explore/SimpleScatterPlotCanvas.cpp @@ -99,7 +99,8 @@ view_standardized_data(view_standardized_data_) selectable_outline_color = GdaConst::scatterplot_regression_color; // 1 = #cats cat_data.CreateCategoriesAllCanvasTms(1, 1, X.size()); - cat_data.SetCategoryColor(0, 0, selectable_fill_color); + cat_data.SetCategoryPenColor(0, 0, selectable_fill_color); + cat_data.SetCategoryBrushColor(0, 0, *wxWHITE); for (int i=0, sz=X.size(); iregisterObserver(this); - SetBackgroundStyle(wxBG_STYLE_CUSTOM); // default style } SimpleScatterPlotCanvas::~SimpleScatterPlotCanvas() { - LOG_MSG("Entering SimpleScatterPlotCanvas::~SimpleScatterPlotCanvas"); + wxLogMessage("Entering SimpleScatterPlotCanvas::~SimpleScatterPlotCanvas"); EmptyLowessCache(); highlight_state->removeObserver(this); - LOG_MSG("Exiting SimpleScatterPlotCanvas::~SimpleScatterPlotCanvas"); + wxLogMessage("Exiting SimpleScatterPlotCanvas::~SimpleScatterPlotCanvas"); } void SimpleScatterPlotCanvas::DisplayRightClickMenu(const wxPoint& pos) { - LOG_MSG("Entering SimpleScatterPlotCanvas::DisplayRightClickMenu"); - if (right_click_menu_id.IsEmpty()) return; - // Workaround for right-click not changing window focus in OSX / wxW 3.0 - wxActivateEvent ae(wxEVT_NULL, true, 0, wxActivateEvent::Reason_Mouse); - template_frame->OnActivate(ae); - - wxMenu* optMenu; - optMenu = wxXmlResource::Get()->LoadMenu(right_click_menu_id); - if (!optMenu) return; - - template_frame->UpdateContextMenuItems(optMenu); - template_frame->PopupMenu(optMenu, pos + GetPosition()); - template_frame->UpdateOptionMenuItems(); - LOG_MSG("Exiting SimpleScatterPlotCanvas::DisplayRightClickMenu"); + wxLogMessage("Entering SimpleScatterPlotCanvas::DisplayRightClickMenu"); + if (right_click_menu_id.IsEmpty()) return; + if (ssp_canv_cb) { + ssp_canv_cb->OnRightClick(pos+ GetPosition()); + } else { + wxMenu* optMenu; + optMenu = wxXmlResource::Get()->LoadMenu("ID_SCATTER_PLOT_MAT_MENU_OPTIONS"); + + template_frame->UpdateContextMenuItems(optMenu); + template_frame->PopupMenu(optMenu, pos + GetPosition()); + template_frame->UpdateOptionMenuItems(); + } + wxLogMessage("Exiting SimpleScatterPlotCanvas::DisplayRightClickMenu"); } void SimpleScatterPlotCanvas::UpdateSelection(bool shiftdown, bool pointsel) @@ -168,7 +167,7 @@ void SimpleScatterPlotCanvas::UpdateSelection(bool shiftdown, bool pointsel) as needed. */ void SimpleScatterPlotCanvas::update(HLStateInt* o) { - LOG_MSG("Entering SimpleScatterPlotCanvas::update"); + wxLogMessage("Entering SimpleScatterPlotCanvas::update"); if (IsShowRegimes() && IsShowLinearSmoother()) { SmoothingUtils::CalcStatsRegimes(X, Y, X_undef, Y_undef, @@ -198,7 +197,7 @@ void SimpleScatterPlotCanvas::update(HLStateInt* o) UpdateStatusBar(); - LOG_MSG("Exiting ScatterNewPlotCanvas::update"); + wxLogMessage("Exiting ScatterNewPlotCanvas::update"); } void SimpleScatterPlotCanvas::AddTimeVariantOptionsToMenu(wxMenu* menu) @@ -207,15 +206,23 @@ void SimpleScatterPlotCanvas::AddTimeVariantOptionsToMenu(wxMenu* menu) wxString SimpleScatterPlotCanvas::GetCanvasTitle() { - wxString s("Scatter Plot"); - s << " - x: " << Xname << ", y: " << Yname; + wxString s = _("Scatter Plot- x: %s, y: %s"); + s = wxString::Format(s, Xname, Yname); return s; } +wxString SimpleScatterPlotCanvas::GetVariableNames() +{ + wxString s; + s << Xname << ", " << Yname; + return s; +} + void SimpleScatterPlotCanvas::UpdateStatusBar() { if (template_frame) { wxStatusBar* sb = template_frame->GetStatusBar(); + if (sb == NULL) return; if (mousemode == select && selectstate == start) { if (template_frame->GetStatusBarStringFromFrame()) { wxString str = template_frame->GetUpdateStatusBarString(hover_obs, total_hover_obs); @@ -228,7 +235,7 @@ void SimpleScatterPlotCanvas::UpdateStatusBar() if (highlight_state->GetTotalHighlighted()> 0) { int n_total_hl = highlight_state->GetTotalHighlighted(); - s << "#selected=" << n_total_hl << " "; + s << _("#selected=") << n_total_hl << " "; int n_undefs = 0; for (int i=0; i= 1) { - s << "hover obs " << hover_obs[0]+1 << " = ("; + s << _("#hover obs ") << hover_obs[0]+1 << " = ("; s << X[hover_obs[0]] << ", " << Y[hover_obs[0]]; s << ")"; } if (total_hover_obs >= 2) { s << ", "; - s << "obs " << hover_obs[1]+1 << " = ("; + s << _("obs ") << hover_obs[1]+1 << " = ("; s << X[hover_obs[1]] << ", " << Y[hover_obs[1]]; s << ")"; } if (total_hover_obs >= 3) { s << ", "; - s << "obs " << hover_obs[2]+1 << " = ("; + s << _("obs ") << hover_obs[2]+1 << " = ("; s << X[hover_obs[2]] << ", " << Y[hover_obs[2]]; s << ")"; } @@ -282,7 +289,6 @@ void SimpleScatterPlotCanvas::UpdateStatusBar() } } sb->SetStatusText(s); - } } @@ -379,12 +385,13 @@ void SimpleScatterPlotCanvas::ChangeLoessParams(double f, int iter, double delta lowess.SetF(f); lowess.SetIter(iter); lowess.SetDeltaFactor(delta_factor); - if (IsShowLowessSmoother()) PopulateCanvas(); + if (IsShowLowessSmoother()) + PopulateCanvas(); } void SimpleScatterPlotCanvas::UpdateLinearRegimesRegLines() { - LOG_MSG("In SimpleScatterPlotCanvas::UpdateLinearRegimesRegLines"); + wxLogMessage("In SimpleScatterPlotCanvas::UpdateLinearRegimesRegLines"); if (IsShowLinearSmoother()) { pens.SetPenColor(pens.GetRegSelPen(), highlight_color); pens.SetPenColor(pens.GetRegExlPen(), GdaConst::scatterplot_regression_excluded_color); diff --git a/Explore/SimpleScatterPlotCanvas.h b/Explore/SimpleScatterPlotCanvas.h index 49efdfe98..6801212cd 100644 --- a/Explore/SimpleScatterPlotCanvas.h +++ b/Explore/SimpleScatterPlotCanvas.h @@ -43,8 +43,8 @@ class Project; class SimpleScatterPlotCanvasCbInt { public: - virtual void notifyNewHover(const std::vector& hover_obs, - int total_hover_obs) = 0; + virtual void notifyNewHover(const std::vector& hover_obs, int total_hover_obs) = 0; + virtual void OnRightClick(const wxPoint& pos) = 0; }; class SimpleScatterPlotCanvas : public TemplateCanvas @@ -82,6 +82,7 @@ class SimpleScatterPlotCanvas : public TemplateCanvas virtual void AddTimeVariantOptionsToMenu(wxMenu* menu); virtual void update(HLStateInt* o); virtual wxString GetCanvasTitle(); + virtual wxString GetVariableNames(); virtual void UpdateStatusBar(); virtual void UpdateSelection(bool shiftdown, bool pointsel); diff --git a/Explore/VarsChooserDlg.cpp b/Explore/VarsChooserDlg.cpp index 0506c15cd..9bddeeb2c 100644 --- a/Explore/VarsChooserDlg.cpp +++ b/Explore/VarsChooserDlg.cpp @@ -49,8 +49,8 @@ vars_list(0), include_list(0) SetBackgroundColour(*wxWHITE); wxPanel* panel = new wxPanel(this); - wxStaticText* vars_list_text = new wxStaticText(panel, wxID_ANY, "Variables"); - wxStaticText* include_list_text = new wxStaticText(panel, wxID_ANY, "Include"); + wxStaticText* vars_list_text = new wxStaticText(panel, wxID_ANY, _("Variables")); + wxStaticText* include_list_text = new wxStaticText(panel, wxID_ANY, _("Include")); vars_list = new wxListBox(panel, XRCID("ID_VARS_LIST"), wxDefaultPosition, wxSize(-1, 150), 0, 0, wxLB_SINGLE); @@ -70,15 +70,15 @@ vars_list(0), include_list(0) wxButton* remove_btn = new wxButton(panel, XRCID("ID_REMOVE_BTN"), "<", wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT); - wxButton* up_btn = new wxButton(panel, XRCID("ID_UP_BTN"), "Up", + wxButton* up_btn = new wxButton(panel, XRCID("ID_UP_BTN"), _("Up"), wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT); - wxButton* down_btn = new wxButton(panel, XRCID("ID_DOWN_BTN"), "Down", + wxButton* down_btn = new wxButton(panel, XRCID("ID_DOWN_BTN"), _("Down"), wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT); wxButton* help_btn = 0; if (!help_html.IsEmpty()) { - help_btn = new wxButton(panel, XRCID("ID_HELP_BTN"), "Help", + help_btn = new wxButton(panel, XRCID("ID_HELP_BTN"), _("Help"), wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT); } @@ -294,6 +294,16 @@ void VarsChooserFrame::IncludeFromVarsListSel(int sel) std::vector min_vals; std::vector max_vals; table_int->GetMinMaxVals(col_id, min_vals, max_vals); + + if (min_vals.empty() && max_vals.empty()) { + // no min_vals and max_vals, this might be an exceptional case: + // e.g. selected variable is not valid + wxString m = wxString::Format(_("Variable %s is not valid. Please select another variable."), name); + wxMessageDialog dlg(NULL, m, _("Error"), wxOK | wxICON_ERROR); + dlg.ShowModal(); + return; + } + var_man.AppendVar(name, min_vals, max_vals, time); include_list->Append(name); vars_list->Delete(sel); diff --git a/GdaCartoDB.cpp b/GdaCartoDB.cpp index 08f129f07..25ab3ab44 100644 --- a/GdaCartoDB.cpp +++ b/GdaCartoDB.cpp @@ -37,7 +37,7 @@ CartoDBProxy::CartoDBProxy() } -CartoDBProxy::CartoDBProxy(const string& _user_name, const string& _api_key) +CartoDBProxy::CartoDBProxy(const wxString& _user_name, const wxString& _api_key) { user_name = _user_name; api_key = _api_key; @@ -48,11 +48,11 @@ CartoDBProxy::~CartoDBProxy() { } -string CartoDBProxy::GetKey() const { +wxString CartoDBProxy::GetKey() const { return api_key; } -string CartoDBProxy::GetUserName() const { +wxString CartoDBProxy::GetUserName() const { return user_name; } @@ -60,22 +60,22 @@ void CartoDBProxy::Close() { } -void CartoDBProxy::SetKey(const string& key) { +void CartoDBProxy::SetKey(const wxString& key) { api_key = key; } -void CartoDBProxy::SetUserName(const string& name) { +void CartoDBProxy::SetUserName(const wxString& name) { user_name = name; } -string CartoDBProxy::buildBaseUrl() +wxString CartoDBProxy::buildBaseUrl() { - ostringstream url; - url << "https://" << user_name << ".cartodb.com/api/v2/sql"; - return url.str(); + wxString url; + url << "https://" << user_name << ".carto.com/api/v2/sql"; + return url; } -string CartoDBProxy::buildUpdateSQL(const string& table_name, const string& col_name, const string &new_table) +wxString CartoDBProxy::buildUpdateSQL(const wxString& table_name, const wxString& col_name, const wxString &new_table) { /** update test as t set @@ -87,28 +87,29 @@ string CartoDBProxy::buildUpdateSQL(const string& table_name, const string& col_ where c.column_b = t.column_b; */ - ostringstream sql; + wxString sql; sql << "UPDATE " << table_name << " t " << "SET " << col_name << " = c.val FROM (VALUES" << new_table.substr(0, new_table.length()-1) << ") AS c(id,val) " << "WHERE c.id = t.cartodb_id "; - return sql.str(); + return sql; } -void CartoDBProxy::UpdateColumn(const string& table_name, const string& col_name, vector& vals) +void CartoDBProxy::UpdateColumn(const wxString& table_name, const wxString& col_name, vector& vals) { - ostringstream ss_newtable; + wxString ss_newtable; for (size_t i=0, n=vals.size(); i& vals); - void UpdateColumn(const string& table_name, - const string& col_name, + void UpdateColumn(const wxString& table_name, + const wxString& col_name, vector& vals); - void UpdateColumn(const string& table_name, - const string& col_name, + void UpdateColumn(const wxString& table_name, + const wxString& col_name, vector& vals); private: CartoDBProxy(); - CartoDBProxy(const string& _user_name, const string& _api_key); + CartoDBProxy(const wxString& _user_name, const wxString& _api_key); ~CartoDBProxy(); - string api_key; - string user_name; - string api_url; + wxString api_key; + wxString user_name; + wxString api_url; - void doGet(string parameter); - void doPost(string parameter); - void _doGet(string parameter); - void _doPost(string parameter); + void doGet(wxString parameter); + void doPost(wxString parameter); + void _doGet(wxString parameter); + void _doPost(wxString parameter); - string buildUpdateSQL(const string& table_name, - const string& col_name, - const string &new_table); + wxString buildUpdateSQL(const wxString& table_name, + const wxString& col_name, + const wxString &new_table); - string buildBaseUrl(); + wxString buildBaseUrl(); }; -#endif \ No newline at end of file +#endif diff --git a/GdaConst.cpp b/GdaConst.cpp index 55e93af73..d1e284ea9 100644 --- a/GdaConst.cpp +++ b/GdaConst.cpp @@ -53,16 +53,30 @@ const char* GdaConst::sample_layer_names[] = { const char* GdaConst::sample_datasources[] = { "samples.sqlite", - "samples.sqlite", - "samples.sqlite", - "samples.sqlite", - "samples.sqlite", - "samples.sqlite", - "samples.sqlite", - "samples.sqlite", - "samples.sqlite", - "samples.sqlite", - "samples.sqlite" + "samples.sqlite", + "samples.sqlite", + "samples.sqlite", + "samples.sqlite", + "samples.sqlite", + "samples.sqlite", + "samples.sqlite", + "samples.sqlite", + "samples.sqlite", + "samples.sqlite" +}; + +const char* GdaConst::sample_meta_urls[] = { + "https://geodacenter.github.io/data-and-lab/Guerry/", + "https://geodacenter.github.io/data-and-lab/ncovr/", + "https://geodacenter.github.io/data-and-lab/baltim/", + "https://geodacenter.github.io/data-and-lab/boston-housing/", + "https://geodacenter.github.io/data-and-lab/columbus/", + "https://geodacenter.github.io/data-and-lab/sids2/", + "https://geodacenter.github.io/data-and-lab/nepal/", + "https://geodacenter.github.io/data-and-lab/nyc/", + "https://geodacenter.github.io/data-and-lab/colomb_malaria/", + "https://geodacenter.github.io/data-and-lab/phx/", + "https://geodacenter.github.io/data-and-lab/SFcrimes_vars/" }; const char* GdaConst::raw_zoom_in[] = { @@ -304,13 +318,19 @@ wxFont* GdaConst::extra_small_font = 0; wxFont* GdaConst::small_font = 0; wxFont* GdaConst::medium_font = 0; wxFont* GdaConst::large_font = 0; - -uint64_t GdaConst::gda_user_seed = 0; -bool GdaConst::use_gda_user_seed = false; + +bool GdaConst::gda_use_gpu = false; +int GdaConst::gda_ui_language = 0; +double GdaConst::gda_eigen_tol = 1.0E-8; +bool GdaConst::gda_set_cpu_cores = true; +int GdaConst::gda_cpu_cores = 8; +wxString GdaConst::gda_user_email = ""; +uint64_t GdaConst::gda_user_seed = 123456789; +bool GdaConst::use_gda_user_seed = true; int GdaConst::gdal_http_timeout = 5; -bool GdaConst::enable_high_dpi_support = false; -bool GdaConst::show_csv_configure_in_merge = false; +bool GdaConst::enable_high_dpi_support = true; +bool GdaConst::show_csv_configure_in_merge = true; bool GdaConst::show_recent_sample_connect_ds_dialog = true; bool GdaConst::use_cross_hatching = false; int GdaConst::transparency_highlighted = 255; @@ -324,8 +344,66 @@ bool GdaConst::disable_crash_detect = false; bool GdaConst::disable_auto_upgrade = false; int GdaConst::plot_transparency_highlighted = 255; int GdaConst::plot_transparency_unhighlighted = 50; - int GdaConst::gda_ogr_csv_header = 2; +wxString GdaConst::gda_display_datetime_format = ""; +std::vector GdaConst::gda_datetime_formats(10); +wxString GdaConst::gda_datetime_formats_str = "%Y-%m-%d %H:%M:%S,%Y/%m/%d %H:%M:%S,%d.%m.%Y %H:%M:%S,%m/%d/%Y %H:%M:%S,%Y-%m-%d,%m/%d/%Y,%Y/%m/%d,%H:%M:%S,%H:%M,%Y/%m/%d %H:%M %p"; +wxString GdaConst::gda_basemap_sources = +"Carto.Light,https://a.basemaps.cartocdn.com/light_all/{z}/{x}/{y}@2x.png" +"\nCarto.Dark,https://a.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}@2x.png" +"\nCarto.Light(No Label),https://a.basemaps.cartocdn.com/light_nolabels/{z}/{x}/{y}@2x.png" +"\nCarto.Dark(No Label),https://a.basemaps.cartocdn.com/dark_nolabels/{z}/{x}/{y}@2x.png" +"\nESRI.WorldStreetMap,https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}" +"\nESRI.WorldTopoMap,https://server.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer/tile/{z}/{y}/{x}" +"\nESRI.WorldTerrain,https://server.arcgisonline.com/ArcGIS/rest/services/World_Terrain_Base/MapServer/tile/{z}/{y}/{x}" +"\nESRI.Ocean,https://server.arcgisonline.com/ArcGIS/rest/services/Ocean_Basemap/MapServer/tile/{z}/{y}/{x}" +"\nHERE.Day,http://1.base.maps.api.here.com/maptile/2.1/maptile/newest/normal.day/{z}/{x}/{y}/256/png8?app_id=HERE_APP_ID&app_code=HERE_APP_CODE" +"\nHERE.Night,http://4.base.maps.api.here.com/maptile/2.1/maptile/newest/normal.night/{z}/{x}/{y}/256/png8?app_id=HERE_APP_ID&app_code=HERE_APP_CODE" +"\nHERE.Hybrid,http://3.aerial.maps.api.here.com/maptile/2.1/maptile/newest/hybrid.day/{z}/{x}/{y}/256/png8?app_id=HERE_APP_ID&app_code=HERE_APP_CODE" +"\nHERE.Satellite,http://4.aerial.maps.api.here.com/maptile/2.1/maptile/newest/satellite.day/{z}/{x}/{y}/256/png8?app_id=HERE_APP_ID&app_code=HERE_APP_CODE" +"\nOpenStreetMap.Mapnik,https://a.tile.openstreetmap.org/{z}/{x}/{y}.png" +"\nOpenStreetMap.BlackAndWhite,http://a.tiles.wmflabs.org/bw-mapnik/{z}/{x}/{y}.png" +"\nStamen.Toner,https://stamen-tiles-a.a.ssl.fastly.net/toner/{z}/{x}/{y}@2x.png" +"\nStamen.TonerLite,https://stamen-tiles-a.a.ssl.fastly.net/toner-lite/{z}/{x}/{y}@2x.png" +"\nStamen.Watercolor,https://stamen-tiles-a.a.ssl.fastly.net/watercolor/{z}/{x}/{y}@2x.png" +"\nOther.高德,http://webrd01.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}" +"\nOther.高德(卫星),http://webst01.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}" +"\nOther.高德(卫星有标签),http://webst01.is.autonavi.com/appmaptile?style=8&x={x}&y={y}&z={z}" +"\nOther.天地图,http://t0.tianditu.cn/DataServer?T=vec_w&X={x}&Y={y}&L={z}" +"\nOther.天地图(卫星),http://t0.tianditu.cn/DataServer?T=cia_w&X={x}&Y={y}&L={z}" +"\nOther.天地图(地形),http://t0.tianditu.cn/DataServer?T=cta_w&X={x}&Y={y}&L={z}" +; + + + +const wxString GdaConst::gda_lbl_not_sig = _("Not Significant"); +const wxString GdaConst::gda_lbl_undefined = _("Undefined"); +const wxString GdaConst::gda_lbl_neighborless = _("Neighborless"); +const wxString GdaConst::gda_lbl_highhigh = _("High-High"); +const wxString GdaConst::gda_lbl_lowlow = _("Low-Low"); +const wxString GdaConst::gda_lbl_lowhigh = _("Low-High"); +const wxString GdaConst::gda_lbl_highlow = _("High-Low"); +const wxString GdaConst::gda_lbl_otherpos = _("Other Pos"); +const wxString GdaConst::gda_lbl_negative = _("Negative"); +const wxString GdaConst::gda_lbl_positive = _("Positive"); +const wxString GdaConst::gda_lbl_1p = "< 1%"; +const wxString GdaConst::gda_lbl_1p_10p = "1% - 10%"; +const wxString GdaConst::gda_lbl_10p_50p = "10% - 50%"; +const wxString GdaConst::gda_lbl_50p_90p = "50% - 90%"; +const wxString GdaConst::gda_lbl_90p_99p = "90% - 99%"; +const wxString GdaConst::gda_lbl_99p = "> 99%"; +const wxString GdaConst::gda_lbl_loweroutlier = _("Lower outlier"); +const wxString GdaConst::gda_lbl_25p = "< 25%"; +const wxString GdaConst::gda_lbl_25p_50p = "25% - 50%"; +const wxString GdaConst::gda_lbl_50p_75p = "50% - 75%"; +const wxString GdaConst::gda_lbl_75p = "> 75%"; +const wxString GdaConst::gda_lbl_upperoutlier = _("Upper outlier"); +const wxString GdaConst::gda_lbl_n2sigma = "< -2Std"; +const wxString GdaConst::gda_lbl_n2sigma_n1sigma = "[-2Std, -1Std)"; +const wxString GdaConst::gda_lbl_n1sigma = "[-1Std, Mean)"; +const wxString GdaConst::gda_lbl_1sigma = "(Mean, 1Std]"; +const wxString GdaConst::gda_lbl_1sigma_2sigma = "(1Std, 2Std]"; +const wxString GdaConst::gda_lbl_2sigma = "> 2Std"; const wxPen* GdaConst::default_myshape_pen=0; const wxBrush* GdaConst::default_myshape_brush=0; @@ -356,7 +434,11 @@ const wxColour GdaConst::map_default_outline_colour(0, 0, 0); const wxColour GdaConst::map_default_highlight_colour(255, 255, 0); // yellow // Connectivity Map -const wxSize GdaConst::conn_map_default_size(480, 350); +const wxSize GdaConst::conn_map_default_size(480, 350); +const wxColour GdaConst::conn_graph_outline_colour(55,55,55,100); +const wxColour GdaConst::conn_select_outline_colour(55,55,55,0); +const wxColour GdaConst::conn_neighbor_fill_colour(255,255,255,0); + // HTML Tan const wxColour GdaConst::conn_map_default_fill_colour(210, 180, 140); const wxColour GdaConst::conn_map_default_outline_colour(0, 0, 0); @@ -372,7 +454,7 @@ const wxSize GdaConst::hist_default_size(600, 500); // Table const wxString GdaConst::placeholder_str(""); -const wxString GdaConst::table_frame_title("Table"); +const wxString GdaConst::table_frame_title(_("Table")); const wxSize GdaConst::table_default_size(750, 500); const wxColour GdaConst::table_no_edit_color(80, 80, 80); // grey const wxColour GdaConst::table_row_sel_color(230, 220, 40); // golden @@ -410,7 +492,7 @@ const wxColour GdaConst::three_d_plot_default_background_colour(0, 0, 0); const wxSize GdaConst::three_d_default_size(700, 500); // Boxplot -const wxSize GdaConst::boxplot_default_size(300, 500); +const wxSize GdaConst::boxplot_default_size(380, 500); const wxColour GdaConst::boxplot_point_color(0, 0, 255); const wxColour GdaConst::boxplot_median_color(219, 99, 28); // orange const wxColour GdaConst::boxplot_mean_point_color(20, 200, 20); // green @@ -440,13 +522,11 @@ const wxSize GdaConst::cond_view_default_size(700, 500); // Category Classification const wxSize GdaConst::cat_classif_default_size(780, 520); - const wxSize GdaConst::weights_man_dlg_default_size(700, 500); - const wxSize GdaConst::data_change_type_frame_default_size(600, 400); std::vector GdaConst::qualitative_colors(10); - +std::vector GdaConst::unique_colors_60(60); const wxString GdaConst::html_submenu_title("Web Plugins"); @@ -494,7 +574,18 @@ void GdaConst::init() large_font = wxFont::New(ref_large_pt_sz, wxFONTFAMILY_SWISS, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL, false, wxEmptyString, wxFONTENCODING_DEFAULT); - + + GdaConst::gda_datetime_formats[0] = "%Y-%m-%d %H:%M:%S"; + GdaConst::gda_datetime_formats[1] = "%Y/%m/%d %H:%M:%S"; + GdaConst::gda_datetime_formats[2] = "%d.%m.%Y %H:%M:%S"; + GdaConst::gda_datetime_formats[3] = "%m/%d/%Y %H:%M:%S"; + GdaConst::gda_datetime_formats[4] = "%Y-%m-%d"; + GdaConst::gda_datetime_formats[5] = "%m/%d/%Y"; + GdaConst::gda_datetime_formats[6] = "%Y/%m/%d"; + GdaConst::gda_datetime_formats[7] = "%H:%M:%S"; + GdaConst::gda_datetime_formats[8] = "%H:%M"; + GdaConst::gda_datetime_formats[9] = "%Y/%m/%d %H:%M %p"; + // GdaShape resources default_myshape_pen = wxBLACK_PEN; default_myshape_brush = wxTRANSPARENT_BRUSH; @@ -544,6 +635,71 @@ void GdaConst::init() qualitative_colors[7] = wxColour(255, 127, 0); qualitative_colors[8] = wxColour(202, 178, 214); qualitative_colors[9] = wxColour(106, 61, 154); + + // From http://phrogz.net/css/distinct-colors.html + + unique_colors_60[0] = wxColour(166,206,227), + unique_colors_60[1] = wxColour(31,120,180), + unique_colors_60[2] = wxColour(178,223,138), + unique_colors_60[3] = wxColour(51,160,44), + unique_colors_60[4] = wxColour(251,154,153), + unique_colors_60[5] = wxColour(227,26,28), + unique_colors_60[6] = wxColour(253,191,111), + unique_colors_60[7] = wxColour(255,127,0), + unique_colors_60[8] = wxColour(106,61,154), + unique_colors_60[9] = wxColour(255,255,153), + unique_colors_60[10] = wxColour(177,89,40), + unique_colors_60[11] = wxColour(255,255,179), + unique_colors_60[12] = wxColour(190,186,218), + unique_colors_60[13] = wxColour(251,128,114), + unique_colors_60[14] = wxColour(128,177,211), + unique_colors_60[15] = wxColour(179,222,105), + unique_colors_60[16] = wxColour(252,205,229), + unique_colors_60[17] = wxColour(217,217,217), + unique_colors_60[18] = wxColour(188,128,189), + unique_colors_60[19] = wxColour(204,235,197), + unique_colors_60[20] = wxColour(140,70,70); + unique_colors_60[21] = wxColour(229,126,57); + unique_colors_60[22] = wxColour(242,162,0); + unique_colors_60[23] = wxColour(166,160,83); + unique_colors_60[24] = wxColour(0,77,41); + unique_colors_60[25] = wxColour(0,48,51); + unique_colors_60[26] = wxColour(0,61,115); + unique_colors_60[27] = wxColour(198,182,242); + unique_colors_60[28] = wxColour(87,26,102); + unique_colors_60[29] = wxColour(255,191,217); + unique_colors_60[30] = wxColour(229,130,115); + unique_colors_60[31] = wxColour(140,98,70); + unique_colors_60[32] = wxColour(76,51,0); + unique_colors_60[33] = wxColour(52,115,29); + unique_colors_60[34] = wxColour(96,128,113); + unique_colors_60[35] = wxColour(64,217,255); + unique_colors_60[36] = wxColour(153,173,204); + unique_colors_60[37] = wxColour(31,0,77); + unique_colors_60[38] = wxColour(166,0,111); + unique_colors_60[39] = wxColour(255,64,115); + unique_colors_60[40] = wxColour(166,44,0); + unique_colors_60[41] = wxColour(217,184,163); + unique_colors_60[42] = wxColour(89,85,67); + unique_colors_60[43] = wxColour(170,217,163); + unique_colors_60[44] = wxColour(0,191,128); + unique_colors_60[45] = wxColour(57,103,115); + unique_colors_60[46] = wxColour(0,58,217); + unique_colors_60[47] = wxColour(98,86,115); + unique_colors_60[48] = wxColour(242,121,186); + unique_colors_60[49] = wxColour(242,0,32); + unique_colors_60[50] = wxColour(76,20,0); + unique_colors_60[51] = wxColour(51,39,26); + unique_colors_60[52] = wxColour(229,218,57); + unique_colors_60[53] = wxColour(61,242,61); + unique_colors_60[54] = wxColour(102,204,197); + unique_colors_60[55] = wxColour(0,162,242); + unique_colors_60[56] = wxColour(89,101,179); + unique_colors_60[57] = wxColour(184,54,217); + unique_colors_60[58] = wxColour(89,0,36); + unique_colors_60[59] = wxColour(0,0,36); + + // Filenames or field names start with a letter, and they can contain any @@ -705,9 +861,9 @@ void GdaConst::init() datasrc_field_illegal_regex[ds_postgresql] = db_field_name_illegal_regex; datasrc_field_casesensitive[ds_postgresql] = true; - datasrc_str_to_type["CartoDB"] = ds_cartodb; - datasrc_type_to_prefix[ds_cartodb] = "CartoDB:"; - datasrc_type_to_fullname[ds_cartodb] = "CartoDB"; + datasrc_str_to_type["Carto"] = ds_cartodb; + datasrc_type_to_prefix[ds_cartodb] = "Carto:"; + datasrc_type_to_fullname[ds_cartodb] = "Carto"; datasrc_table_lens[ds_cartodb] = 31; datasrc_field_lens[ds_cartodb] = 31; datasrc_field_warning[ds_cartodb] = db_field_warning; diff --git a/GdaConst.h b/GdaConst.h index fd53d857e..a6df5b925 100644 --- a/GdaConst.h +++ b/GdaConst.h @@ -146,97 +146,8 @@ class GdaConst { static const int ID_HISTOGRAM_CLASSIFICATION = wxID_HIGHEST + 3300; static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_A0 = wxID_HIGHEST + 4000; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_A1 = wxID_HIGHEST + 4001; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_A2 = wxID_HIGHEST + 4002; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_A3 = wxID_HIGHEST + 4003; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_A4 = wxID_HIGHEST + 4004; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_A5 = wxID_HIGHEST + 4005; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_A6 = wxID_HIGHEST + 4006; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_A7 = wxID_HIGHEST + 4007; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_A8 = wxID_HIGHEST + 4008; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_A9 = wxID_HIGHEST + 4009; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_A10 = wxID_HIGHEST + 4010; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_A11 = wxID_HIGHEST + 4011; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_A12 = wxID_HIGHEST + 4012; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_A13 = wxID_HIGHEST + 4013; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_A14 = wxID_HIGHEST + 4014; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_A15 = wxID_HIGHEST + 4015; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_A16 = wxID_HIGHEST + 4016; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_A17 = wxID_HIGHEST + 4017; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_A18 = wxID_HIGHEST + 4018; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_A19 = wxID_HIGHEST + 4019; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_A20 = wxID_HIGHEST + 4020; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_A21 = wxID_HIGHEST + 4021; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_A22 = wxID_HIGHEST + 4022; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_A23 = wxID_HIGHEST + 4023; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_A24 = wxID_HIGHEST + 4024; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_A25 = wxID_HIGHEST + 4025; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_A26 = wxID_HIGHEST + 4026; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_A27 = wxID_HIGHEST + 4027; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_A28 = wxID_HIGHEST + 4028; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_A29 = wxID_HIGHEST + 4029; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_B0 = wxID_HIGHEST + 4100; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_B1 = wxID_HIGHEST + 4101; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_B2 = wxID_HIGHEST + 4102; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_B3 = wxID_HIGHEST + 4103; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_B4 = wxID_HIGHEST + 4104; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_B5 = wxID_HIGHEST + 4105; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_B6 = wxID_HIGHEST + 4106; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_B7 = wxID_HIGHEST + 4107; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_B8 = wxID_HIGHEST + 4108; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_B9 = wxID_HIGHEST + 4109; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_B10 = wxID_HIGHEST + 4110; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_B11 = wxID_HIGHEST + 4111; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_B12 = wxID_HIGHEST + 4112; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_B13 = wxID_HIGHEST + 4113; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_B14 = wxID_HIGHEST + 4114; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_B15 = wxID_HIGHEST + 4115; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_B16 = wxID_HIGHEST + 4116; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_B17 = wxID_HIGHEST + 4117; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_B18 = wxID_HIGHEST + 4118; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_B19 = wxID_HIGHEST + 4119; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_B20 = wxID_HIGHEST + 4120; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_B21 = wxID_HIGHEST + 4121; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_B22 = wxID_HIGHEST + 4122; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_B23 = wxID_HIGHEST + 4123; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_B24 = wxID_HIGHEST + 4124; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_B25 = wxID_HIGHEST + 4125; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_B26 = wxID_HIGHEST + 4126; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_B27 = wxID_HIGHEST + 4127; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_B28 = wxID_HIGHEST + 4128; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_B29 = wxID_HIGHEST + 4129; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_C0 = wxID_HIGHEST + 4200; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_C1 = wxID_HIGHEST + 4201; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_C2 = wxID_HIGHEST + 4202; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_C3 = wxID_HIGHEST + 4203; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_C4 = wxID_HIGHEST + 4204; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_C5 = wxID_HIGHEST + 4205; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_C6 = wxID_HIGHEST + 4206; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_C7 = wxID_HIGHEST + 4207; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_C8 = wxID_HIGHEST + 4208; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_C9 = wxID_HIGHEST + 4209; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_C10 = wxID_HIGHEST + 4210; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_C11 = wxID_HIGHEST + 4211; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_C12 = wxID_HIGHEST + 4212; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_C13 = wxID_HIGHEST + 4213; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_C14 = wxID_HIGHEST + 4214; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_C15 = wxID_HIGHEST + 4215; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_C16 = wxID_HIGHEST + 4216; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_C17 = wxID_HIGHEST + 4217; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_C18 = wxID_HIGHEST + 4218; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_C19 = wxID_HIGHEST + 4219; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_C20 = wxID_HIGHEST + 4220; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_C21 = wxID_HIGHEST + 4221; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_C22 = wxID_HIGHEST + 4222; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_C23 = wxID_HIGHEST + 4223; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_C24 = wxID_HIGHEST + 4224; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_C25 = wxID_HIGHEST + 4225; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_C26 = wxID_HIGHEST + 4226; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_C27 = wxID_HIGHEST + 4227; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_C28 = wxID_HIGHEST + 4228; - static const int ID_CUSTOM_CAT_CLASSIF_CHOICE_C29 = wxID_HIGHEST + 4229; static const wxString html_submenu_title; static const int ID_HTML_SUBMENU = wxID_HIGHEST + 5000; @@ -250,7 +161,9 @@ class GdaConst { static const int ID_HTML_MENU_ENTRY_CHOICE_7 = ID_HTML_SUBMENU + 8; static const int ID_HTML_MENU_ENTRY_CHOICE_8 = ID_HTML_SUBMENU + 9; static const int ID_HTML_MENU_ENTRY_CHOICE_9 = ID_HTML_SUBMENU + 10; - + + static const int ID_CONNECT_POPUP_MENU = wxID_HIGHEST + 6000; + // Standard wxFont pointers. static wxFont* extra_small_font; static wxFont* small_font; @@ -266,6 +179,8 @@ class GdaConst { // Shared Colours static std::vector qualitative_colors; + + static std::vector unique_colors_60; //background color -- this is light gray static const wxColour backColor; @@ -294,8 +209,45 @@ class GdaConst { static const wxColour highlight_color; // yellow static const wxColour canvas_background_color; // white static const wxColour legend_background_color; // white - + + // Strings + static const wxString gda_lbl_not_sig; + static const wxString gda_lbl_undefined; + static const wxString gda_lbl_neighborless; + static const wxString gda_lbl_highhigh; + static const wxString gda_lbl_lowlow; + static const wxString gda_lbl_lowhigh; + static const wxString gda_lbl_highlow; + static const wxString gda_lbl_otherpos; + static const wxString gda_lbl_negative; + static const wxString gda_lbl_positive; + static const wxString gda_lbl_1p; + static const wxString gda_lbl_1p_10p; + static const wxString gda_lbl_10p_50p; + static const wxString gda_lbl_50p_90p; + static const wxString gda_lbl_90p_99p; + static const wxString gda_lbl_99p; + static const wxString gda_lbl_loweroutlier; + static const wxString gda_lbl_25p; + static const wxString gda_lbl_25p_50p; + static const wxString gda_lbl_50p_75p; + static const wxString gda_lbl_75p; + static const wxString gda_lbl_upperoutlier; + static const wxString gda_lbl_n2sigma; + static const wxString gda_lbl_n2sigma_n1sigma; + static const wxString gda_lbl_n1sigma; + static const wxString gda_lbl_1sigma; + static const wxString gda_lbl_1sigma_2sigma; + static const wxString gda_lbl_2sigma; + // Preferences + static wxString gda_basemap_sources; + static bool gda_use_gpu; + static int gda_ui_language; + static double gda_eigen_tol; + static int gda_cpu_cores; + static bool gda_set_cpu_cores; + static wxString gda_user_email; static uint64_t gda_user_seed; static bool use_gda_user_seed; static int gdal_http_timeout; @@ -314,7 +266,9 @@ class GdaConst { static bool disable_auto_upgrade; static int plot_transparency_highlighted; static int plot_transparency_unhighlighted; - + static std::vector gda_datetime_formats; + static wxString gda_datetime_formats_str; + static wxString gda_display_datetime_format; static int gda_ogr_csv_header; static const wxSize map_default_size; @@ -330,6 +284,10 @@ class GdaConst { static const wxColour conn_map_default_fill_colour; static const wxColour conn_map_default_outline_colour; static const wxColour conn_map_default_highlight_colour; + + static const wxColour conn_graph_outline_colour; + static const wxColour conn_select_outline_colour; + static const wxColour conn_neighbor_fill_colour; // Map Movie static const wxColour map_movie_default_fill_colour; @@ -433,6 +391,7 @@ class GdaConst { static const char* sample_names[255]; static const char* sample_layer_names[255]; static const char* sample_datasources[255]; + static const char* sample_meta_urls[255]; }; #endif diff --git a/GdaShape.cpp b/GdaShape.cpp index 58cfead65..ca7154e28 100644 --- a/GdaShape.cpp +++ b/GdaShape.cpp @@ -201,6 +201,9 @@ void GdaScaleTrans::calcAffineParams() trans_y = screen_height - slack_y - bottom_margin - scale_y * data_y_min; } } else { // fixed_aspect_ratio == false, fit_to_window == true/false + slack_x = 0; + slack_y = 0; + scale_x = drawing_area_width / data_width; scale_y = -(drawing_area_height / data_height); @@ -410,9 +413,13 @@ void GdaShape::applyScaleTrans(const GdaScaleTrans& A) A.transform(center_o, ¢er); } -void GdaShape::projectToBasemap(GDA::Basemap* basemap) +void GdaShape::projectToBasemap(GDA::Basemap* basemap, double scale_factor) { basemap->LatLngToXY(center_o.x, center_o.y, center.x, center.y); + if (scale_factor != 1) { + center.x = center.x * scale_factor; + center.y = center.y * scale_factor; + } } void GdaShape::setNudge(int x_nudge, int y_nudge) @@ -525,7 +532,15 @@ wxRealPoint GdaShapeAlgs::calculateCentroid(GdaPolygon* poly) if (poly->points_o) { return calculateCentroid(poly->n, poly->points_o); } else { - return calculateCentroid(poly->count[0], poly->pc->points); + int start = 0; + int n_size = poly->count[0]; + for (int i=1; ipc->num_parts; i++) { + if (poly->count[i] > n_size) { + start = n_size; + n_size = poly->count[i]; + } + } + return calculateCentroid(start, poly->pc->points); } } @@ -546,15 +561,16 @@ wxRealPoint GdaShapeAlgs::calculateCentroid(int n, wxRealPoint* pts) return wxRealPoint(cx, cy); } -wxRealPoint GdaShapeAlgs::calculateCentroid(int n, +wxRealPoint GdaShapeAlgs::calculateCentroid(int start, const std::vector& pts) { + int n = pts.size() - start; double area = GdaShapeAlgs::calculateArea(n, pts); - if (area == 0) return wxRealPoint(pts[0].x, pts[0].y); + if (area == 0) return wxRealPoint(pts[start].x, pts[start].y); // polygon is a p-gon. Handle case when polygon is not closed - int p = (pts[0].x==pts[n-1].x && pts[0].y==pts[n-1].y) ? n-1 : n; + int p = (pts[0].x==pts[n-1 + start].x && pts[0 + start].y==pts[n-1 + start].y) ? n-1 : n; double cx=0, cy=0, d; - for (int i=0, j=1, k=0; k& pts) { + int n = pts.size() - start; if (n <= 2) return 0; double a = 0; - int p = (pts[0].x==pts[n-1].x && pts[0].y==pts[n-1].y) ? n-1 : n; - for (int i=0, j=1, k=0; kCreatePath(); - path.AddCircle(n_center.x, n_center.y, GdaConst::my_point_click_radius); + path.AddCircle(n_center.x, n_center.y, radius); gc->StrokePath(path); } @@ -1033,16 +1056,23 @@ void GdaRectangle::applyScaleTrans(const GdaScaleTrans& A) } -void GdaRectangle::projectToBasemap(GDA::Basemap* basemap) +void GdaRectangle::projectToBasemap(GDA::Basemap* basemap, double scale_factor) { if (null_shape) return; - GdaShape::projectToBasemap(basemap); // apply affine transform to base class + GdaShape::projectToBasemap(basemap, scale_factor); // apply affine transform to base class basemap->LatLngToXY(lower_left_o.x, lower_left_o.y, lower_left.x, lower_left.y); basemap->LatLngToXY(upper_right_o.x, upper_right_o.y, upper_right.x, upper_right.y); + + if (scale_factor != 1) { + lower_left.x = lower_left.x * scale_factor; + lower_left.y = lower_left.y * scale_factor; + upper_right.x = upper_right.x * scale_factor; + upper_right.y = upper_right.y * scale_factor; + } } void GdaRectangle::paintSelf(wxDC& dc) @@ -1050,9 +1080,11 @@ void GdaRectangle::paintSelf(wxDC& dc) if (null_shape) return; dc.SetPen(getPen()); dc.SetBrush(getBrush()); - dc.DrawRectangle(lower_left.x+getXNudge(), lower_left.y+getYNudge(), - upper_right.x - lower_left.x, - upper_right.y - lower_left.y); + int x = lower_left.x+getXNudge(); + int y = upper_right.y+getYNudge(); + int w = upper_right.x - lower_left.x; + int h = lower_left.y - upper_right.y; + dc.DrawRectangle(x,y,w,h); } void GdaRectangle::paintSelf(wxGraphicsContext* gc) @@ -1231,60 +1263,51 @@ void GdaPolygon::applyScaleTrans(const GdaScaleTrans& A) { if (null_shape) return; GdaShape::applyScaleTrans(A); // apply affine transform to base class - all_points_same = true; - wxPoint tpt; - A.transform(bb_ll_o, &tpt); - if (tpt == center) A.transform(bb_ur_o, &tpt); - if (tpt == center) return; + //all_points_same = true; + //wxPoint tpt; + //A.transform(bb_ll_o, &tpt); + //if (tpt == center) A.transform(bb_ur_o, &tpt); + //if (tpt == center) return; if (points_o) { for (int i=0; ipoints[i], &(points[i])); - if (points[i] != center) all_points_same = false; + //if (points[i] != center) all_points_same = false; } //region = wxRegion(n, points); // MMM: needs to support multi-part } } -void GdaPolygon::projectToBasemap(GDA::Basemap* basemap) +void GdaPolygon::projectToBasemap(GDA::Basemap* basemap, double scale_factor) { if (null_shape) return; - GdaShape::projectToBasemap(basemap); // apply transform to base class - all_points_same = true; - wxPoint tpt; - - basemap->LatLngToXY(bb_ll_o.x, bb_ll_o.y, tpt.x, tpt.y); - - if (tpt == center) - basemap->LatLngToXY(bb_ur_o.x, bb_ur_o.y, tpt.x, tpt.y); - - if (tpt == center) - return; - + GdaShape::projectToBasemap(basemap, scale_factor); if (points_o) { for (int i=0; iLatLngToXY(points_o[i].x, points_o[i].y, points[i].x, points[i].y); - if (points[i] != center) - all_points_same = false; + if (scale_factor != 1) { + points[i].x = points[i].x * scale_factor; + points[i].y = points[i].y * scale_factor; + } } - //region = wxRegion(n, points); } else { for (int i=0; iLatLngToXY(pc->points[i].x, pc->points[i].y, points[i].x, points[i].y); - if (points[i] != center) - all_points_same = false; + if (scale_factor != 1) { + points[i].x = points[i].x * scale_factor; + points[i].y = points[i].y * scale_factor; + } } - //region = wxRegion(n, points); // MMM: needs to support multi-part } } @@ -1468,8 +1491,6 @@ GdaPolyLine::GdaPolyLine(wxPoint pt1, wxPoint pt2) } - - /** This constructs a potentially multi-part polyline. Only a pointer to the original data is kept, and this memory is not deleted in the destructor. */ GdaPolyLine::GdaPolyLine(Shapefile::PolyLineContents* pc_s) @@ -1517,6 +1538,17 @@ GdaPolyLine::~GdaPolyLine() if (count) delete [] count; count = 0; } +void GdaPolyLine::projectToBasemap(GDA::Basemap* basemap, double scale_factor) +{ + for (int i=0; iLatLngToXY(points_o[i].x, points_o[i].y, points[i].x, points[i].y); + if (scale_factor != 1) { + points[i].x = points[i].x * scale_factor; + points[i].y = points[i].y * scale_factor; + } + } +} + void GdaPolyLine::Offset(double dx, double dy) { for (int i=0; i #include #include #include @@ -39,9 +40,16 @@ class GdaPolygon; struct GdaScaleTrans { GdaScaleTrans(); - GdaScaleTrans(double s_x, double s_y, double t_x, double t_y) : - scale_x(s_x), scale_y(s_y), max_scale(GenUtils::max(s_x, s_y)), - trans_x(t_x), trans_y(t_y) {} + GdaScaleTrans(double s_x, double s_y, double t_x, double t_y) + { + scale_x = s_x; + scale_y = s_y; + max_scale = std::max(s_x, s_y); + trans_x = t_x; + trans_y = t_y; + slack_x = 0; + slack_y = 0; + } virtual GdaScaleTrans& operator=(const GdaScaleTrans& s); void SetData(double x_min, double y_min, double x_max, double y_max); @@ -76,7 +84,8 @@ struct GdaScaleTrans { int GetXNudge(); wxRealPoint GetDataCenter(); - + + // attributes bool fixed_aspect_ratio; double drawing_area_width; @@ -174,7 +183,7 @@ class GdaShape { virtual bool Contains(const wxPoint& pt) { return pointWithin(pt); }; virtual bool regionIntersect(const wxRegion& region) { return false; }; virtual void applyScaleTrans(const GdaScaleTrans& A); - virtual void projectToBasemap(GDA::Basemap* basemap); + virtual void projectToBasemap(GDA::Basemap* basemap, double scale_factor = 1.0); virtual void paintSelf(wxDC& dc) = 0; virtual void paintSelf(wxGraphicsContext* gc) = 0; @@ -201,7 +210,10 @@ class GdaShape { class GdaPoint: public GdaShape { + public: + int radius; + GdaPoint(); // creates a null shape GdaPoint(const GdaPoint& s); GdaPoint(wxRealPoint point_o_s); @@ -272,7 +284,7 @@ class GdaRectangle: public GdaShape { virtual bool pointWithin(const wxPoint& pt); virtual bool regionIntersect(const wxRegion& r); virtual void applyScaleTrans(const GdaScaleTrans& A); - virtual void projectToBasemap(GDA::Basemap* basemap); + virtual void projectToBasemap(GDA::Basemap* basemap, double scale_factor = 1.0); virtual void paintSelf(wxDC& dc); virtual void paintSelf(wxGraphicsContext* gc); @@ -300,7 +312,7 @@ class GdaPolygon: public GdaShape { virtual bool pointWithin(const wxPoint& pt); virtual bool regionIntersect(const wxRegion& r); virtual void applyScaleTrans(const GdaScaleTrans& A); - virtual void projectToBasemap(GDA::Basemap* basemap); + virtual void projectToBasemap(GDA::Basemap* basemap, double scale_factor = 1.0); static wxRealPoint CalculateCentroid(int n, wxRealPoint* pts); virtual void paintSelf(wxDC& dc); virtual void paintSelf(wxGraphicsContext* gc); @@ -346,6 +358,8 @@ class GdaPolyLine: public GdaShape { virtual bool pointWithin(const wxPoint& pt); virtual bool regionIntersect(const wxRegion& r); virtual void applyScaleTrans(const GdaScaleTrans& A); + + virtual void projectToBasemap(GDA::Basemap* basemap, double scale_factor = 1); virtual void paintSelf(wxDC& dc); virtual void paintSelf(wxGraphicsContext* gc); @@ -366,6 +380,8 @@ class GdaPolyLine: public GdaShape { wxRealPoint* points_o; //wxRegion region; + int from; + int to; }; class GdaSpline: public GdaShape { @@ -458,6 +474,8 @@ class GdaShapeText: public GdaShape { virtual void Offset(double dx, double dy); virtual void Offset(int dx, int dy); + virtual void GetSize(wxDC& dc, int& w, int& h); + virtual bool pointWithin(const wxPoint& pt); virtual void applyScaleTrans(const GdaScaleTrans& A); virtual void paintSelf(wxDC& dc); @@ -538,13 +556,19 @@ class GdaAxis: public GdaShape { public: GdaAxis(); GdaAxis(const GdaAxis& s); - GdaAxis(const wxString& caption_s, const AxisScale& s, - const wxRealPoint& a_s, const wxRealPoint& b_s, - int x_nudge = 0, int y_nudge = 0); + GdaAxis(const wxString& caption_s, + const AxisScale& s, + const wxRealPoint& a_s, + const wxRealPoint& b_s, + int x_nudge = 0, + int y_nudge = 0, + bool inSubview = false); GdaAxis(const wxString& caption_s, const std::vector& tic_labels_s, - const wxRealPoint& a_s, const wxRealPoint& b_s, - int x_nudge = 0, int y_nudge = 0); + const wxRealPoint& a_s, + const wxRealPoint& b_s, + int x_nudge = 0, + int y_nudge = 0); virtual ~GdaAxis() {} virtual GdaAxis* clone() { return new GdaAxis(*this); } @@ -569,18 +593,20 @@ class GdaAxis: public GdaShape { wxPoint a, b; wxString caption; bool hidden; + wxFont font; protected: bool is_horizontal; wxRealPoint a_o; wxRealPoint b_o; - wxFont font; + wxFont caption_font; bool hide_scale_values; bool hide_caption; bool auto_drop_scale_values; bool hide_negative_labels; bool move_outer_val_text_inwards; + bool inSubview; }; class GdaSelRegion { @@ -606,4 +632,5 @@ class GdaSelRegion { // { return lhs->z < rhs->z; } //}; + #endif diff --git a/GenUtils.cpp b/GenUtils.cpp index 3b5175581..093ab3325 100644 --- a/GenUtils.cpp +++ b/GenUtils.cpp @@ -26,11 +26,446 @@ #include #include #include +#include #include "GdaConst.h" #include "GenUtils.h" +#include "Explore/CatClassification.h" using namespace std; +int StringUtils::utf8_strlen(const string& str) +{ + int c,i,ix,q; + for (q=0, i=0, ix=str.length(); i < ix; i++, q++) + { + c = (unsigned char) str[i]; + if (c>=0 && c<=127) i+=0; + else if ((c & 0xE0) == 0xC0) i+=1; + else if ((c & 0xF0) == 0xE0) i+=2; + else if ((c & 0xF8) == 0xF0) i+=3; + //else if (($c & 0xFC) == 0xF8) i+=4; // 111110bb //byte 5, unnecessary in 4 byte UTF-8 + //else if (($c & 0xFE) == 0xFC) i+=5; // 1111110b //byte 6, unnecessary in 4 byte UTF-8 + else return 0;//invalid utf8 + } + return q; +} + +void DbfFileUtils::SuggestDoubleParams(int length, int decimals, + int* suggest_len, int* suggest_dec) +{ + // doubles have 52 bits for the mantissa, so we can allow at most + // floor(log(2^52)) = 15 digits of precision. + // We require that there length-2 >= decimals to allow for "x." . when + // writing to disk, and when decimals = 15, require length >= 17 to + // allow for "0." prefex. If length-2 == decimals, then negative numbers + // are not allowed since there is not room for the "-0." prefix. + if (GdaConst::max_dbf_double_len < length) { + length = GdaConst::max_dbf_double_len; + } + if (length < 3) length = 3; + if (decimals < 1) decimals = 1; + if (decimals > 15) decimals = 15; + if (length-2 < decimals) length = decimals + 2; + + *suggest_len = length; + *suggest_dec = decimals; +} + +double DbfFileUtils::GetMaxDouble(int length, int decimals, + int* suggest_len, int* suggest_dec) +{ + // make sure that length and decimals have legal values + SuggestDoubleParams(length, decimals, &length, &decimals); + + int len_inter = length - (1+decimals); + if (len_inter + decimals > 15) len_inter = 15-decimals; + double r = 0; + for (int i=0; i 18) length = 18; + wxInt64 r=0; + for (int i=0; i 19) length = 19; + return -GetMaxInt(length-1); +} + +wxString DbfFileUtils::GetMinIntString(int length) +{ + return wxString::Format("%lld", GetMinInt(length)); +} + +wxString Gda::DetectDateFormat(wxString s, vector& date_items) +{ + // input s could be sth. like: %Y-%m-%d %H:%M:%S + // 2015-1-11 13:57:24 %Y-%m-%d %H:%M:%S + wxString YY = "([0-9]{4})"; + wxString yy = "([0-9]{2})"; + wxString MM = "([0-9]{1,2})";//"(0?[1-9]|1[0-2])"; + wxString DD = "([0-9]{1,2})";//"(0?[1-9]|[12][0-9]|3[01])"; + wxString hh = "([0-9]{1,2})";//"(00|[0-9]|1[0-9]|2[0-3])"; + wxString mm = "([0-9]{1,2})";//"([0-9]|[0-5][0-9])"; + wxString ss = "([0-9]{1,2})"; //"([0-9]|[0-5][0-9])"; + wxString pp = "([AP]M)"; //"(AM | PM)"; + + wxString pattern; + wxString original_pattern; + for (int i=0; i0) { + pattern = select_pattern; + break; + } + } + } + } + + if (!pattern.IsEmpty()){ + wxString select_pattern = original_pattern; + wxRegEx regex("(%[YymdHMSp])"); + while (regex.Matches(select_pattern) ) { + size_t start, len; + regex.GetMatch(&start, &len, 0); + date_items.push_back(regex.GetMatch(select_pattern, 1)); + select_pattern = select_pattern.Mid (start + len); + } + } + return pattern; +} + +// wxRegEx regex +// regex.Compile(pattern); +unsigned long long Gda::DateToNumber(wxString s_date, wxRegEx& regex, vector& date_items) +{ + unsigned long long val = 0; + + if (regex.Matches(s_date)) { + int n = regex.GetMatchCount(); + wxString _year, _short_year, _month, _day, _hour, _minute, _second, _am_pm; + long _l_year =0, _l_short_year=0, _l_month=0, _l_day=0, _l_hour=0, _l_minute=0, _l_second=0; + for (int i=1; i& colors) +{ + colors.clear(); + colors.push_back(wxColour(166,206,227)); + colors.push_back(wxColour(31,120,180)); + colors.push_back(wxColour(178,223,138)); + colors.push_back(wxColour(51,160,44)); + colors.push_back(wxColour(251,154,153)); + colors.push_back(wxColour(227,26,28)); + colors.push_back(wxColour(253,191,111)); + colors.push_back(wxColour(255,127,0)); + colors.push_back(wxColour(106,61,154)); + colors.push_back(wxColour(255,255,153)); + colors.push_back(wxColour(177,89,40)); + colors.push_back(wxColour(255,255,179)); + colors.push_back(wxColour(190,186,218)); + colors.push_back(wxColour(251,128,114)); + colors.push_back(wxColour(128,177,211)); + colors.push_back(wxColour(179,222,105)); + colors.push_back(wxColour(252,205,229)); + colors.push_back(wxColour(217,217,217)); + colors.push_back(wxColour(188,128,189)); + colors.push_back(wxColour(204,235,197)); +}; + +void GdaColorUtils::GetLISAColors(std::vector& colors) +{ + colors.clear(); + colors.push_back(wxColour(240, 240, 240)); + colors.push_back(wxColour(255, 0, 0)); + colors.push_back(wxColour(0, 0, 255)); + colors.push_back(wxColour(150, 150, 255)); + colors.push_back(wxColour(255, 150, 150)); +} + +void GdaColorUtils::GetLISAColorLabels(std::vector& labels) +{ + labels.clear(); + labels.push_back(GdaConst::gda_lbl_not_sig); + labels.push_back(GdaConst::gda_lbl_highhigh); + labels.push_back(GdaConst::gda_lbl_lowlow); + labels.push_back(GdaConst::gda_lbl_lowhigh); + labels.push_back(GdaConst::gda_lbl_highlow); +} + +void GdaColorUtils::GetLocalGColors(std::vector& colors) +{ + colors.clear(); + colors.push_back(wxColour(240, 240, 240)); + colors.push_back(wxColour(255, 0, 0)); + colors.push_back(wxColour(0, 0, 255)); +} +void GdaColorUtils::GetLocalGColorLabels(std::vector& labels) +{ + labels.clear(); + labels.push_back(GdaConst::gda_lbl_not_sig); + labels.push_back(GdaConst::gda_lbl_highhigh); + labels.push_back(GdaConst::gda_lbl_lowlow); +} + +void GdaColorUtils::GetLocalJoinCountColors(std::vector& colors) +{ + colors.clear(); + colors.push_back(wxColour(240, 240, 240)); + colors.push_back(wxColour(255, 0, 0)); +} +void GdaColorUtils::GetLocalJoinCountColorLabels(std::vector& labels) +{ + labels.clear(); + labels.push_back(GdaConst::gda_lbl_not_sig); + labels.push_back(GdaConst::gda_lbl_highhigh); +} + +void GdaColorUtils::GetLocalGearyColors(std::vector& colors) +{ + colors.clear(); + colors.push_back(wxColour(240, 240, 240)); + colors.push_back(wxColour(178,24,43)); + colors.push_back(wxColour(239,138,98)); + colors.push_back(wxColour(253,219,199)); + colors.push_back(wxColour(103,173,199)); +} +void GdaColorUtils::GetLocalGearyColorLabels(std::vector& labels) +{ + labels.clear(); + labels.push_back(GdaConst::gda_lbl_not_sig); + labels.push_back(GdaConst::gda_lbl_highhigh); + labels.push_back(GdaConst::gda_lbl_lowlow); + labels.push_back(GdaConst::gda_lbl_otherpos); + labels.push_back(GdaConst::gda_lbl_negative); +} + +void GdaColorUtils::GetMultiLocalGearyColors(std::vector& colors) +{ + colors.clear(); + colors.push_back(wxColour(240, 240, 240)); + colors.push_back(wxColour(51,110,161)); +} +void GdaColorUtils::GetMultiLocalGearyColorLabels(std::vector& labels) +{ + labels.clear(); + labels.push_back(GdaConst::gda_lbl_not_sig); + labels.push_back(GdaConst::gda_lbl_positive); +} + +void GdaColorUtils::GetPercentileColors(std::vector& colors) +{ + colors.clear(); + CatClassification::PickColorSet(colors, CatClassification::diverging_color_scheme, 6, false); + colors.insert(colors.begin(), wxColour(240, 240, 240)); +} +void GdaColorUtils::GetPercentileColorLabels(std::vector& labels) +{ + labels.clear(); + labels.push_back(GdaConst::gda_lbl_1p); + labels.push_back(GdaConst::gda_lbl_1p_10p); + labels.push_back(GdaConst::gda_lbl_10p_50p); + labels.push_back(GdaConst::gda_lbl_50p_90p); + labels.push_back(GdaConst::gda_lbl_90p_99p); + labels.push_back(GdaConst::gda_lbl_99p); +} + +void GdaColorUtils::GetBoxmapColors(std::vector& colors) +{ + colors.clear(); + CatClassification::PickColorSet(colors, CatClassification::diverging_color_scheme, 6, false); + colors.insert(colors.begin(), wxColour(240, 240, 240)); +} +void GdaColorUtils::GetBoxmapColorLabels(std::vector& labels) +{ + labels.clear(); + labels.push_back(GdaConst::gda_lbl_loweroutlier); + labels.push_back(GdaConst::gda_lbl_25p); + labels.push_back(GdaConst::gda_lbl_25p_50p); + labels.push_back(GdaConst::gda_lbl_50p_75p); + labels.push_back(GdaConst::gda_lbl_75p); + labels.push_back(GdaConst::gda_lbl_upperoutlier); +} + +void GdaColorUtils::GetStddevColors(std::vector& colors) +{ + colors.clear(); + CatClassification::PickColorSet(colors, CatClassification::diverging_color_scheme, 6, false); + colors.insert(colors.begin(), wxColour(240, 240, 240)); +} +void GdaColorUtils::GetStddevColorLabels(std::vector& labels) +{ + labels.clear(); + labels.push_back(GdaConst::gda_lbl_n2sigma); + labels.push_back(GdaConst::gda_lbl_n2sigma_n1sigma); + labels.push_back(GdaConst::gda_lbl_n1sigma); + labels.push_back(GdaConst::gda_lbl_1sigma); + labels.push_back(GdaConst::gda_lbl_1sigma_2sigma); + labels.push_back(GdaConst::gda_lbl_2sigma); +} + +void GdaColorUtils::GetQuantile2Colors(std::vector& colors) +{ + colors.clear(); + CatClassification::PickColorSet(colors, CatClassification::sequential_color_scheme, 2, false); + colors.insert(colors.begin(), wxColour(240, 240, 240)); +} +void GdaColorUtils::GetQuantile3Colors(std::vector& colors) +{ + colors.clear(); + CatClassification::PickColorSet(colors, CatClassification::sequential_color_scheme, 3, false); + colors.insert(colors.begin(), wxColour(240, 240, 240)); + +} +void GdaColorUtils::GetQuantile4Colors(std::vector& colors) +{ + colors.clear(); + CatClassification::PickColorSet(colors, CatClassification::sequential_color_scheme, 4, false); + colors.insert(colors.begin(), wxColour(240, 240, 240)); + +} +void GdaColorUtils::GetQuantile5Colors(std::vector& colors) +{ + colors.clear(); + CatClassification::PickColorSet(colors, CatClassification::sequential_color_scheme, 5, false); + colors.insert(colors.begin(), wxColour(240, 240, 240)); + +} +void GdaColorUtils::GetQuantile6Colors(std::vector& colors) +{ + colors.clear(); + CatClassification::PickColorSet(colors, CatClassification::sequential_color_scheme, 6, false); + colors.insert(colors.begin(), wxColour(240, 240, 240)); + +} +void GdaColorUtils::GetQuantile7Colors(std::vector& colors) +{ + colors.clear(); + CatClassification::PickColorSet(colors, CatClassification::sequential_color_scheme, 7, false); + colors.insert(colors.begin(), wxColour(240, 240, 240)); + +} +void GdaColorUtils::GetQuantile8Colors(std::vector& colors) +{ + colors.clear(); + CatClassification::PickColorSet(colors, CatClassification::sequential_color_scheme, 8, false); + colors.insert(colors.begin(), wxColour(240, 240, 240)); + +} +void GdaColorUtils::GetQuantile9Colors(std::vector& colors) +{ + colors.clear(); + CatClassification::PickColorSet(colors, CatClassification::sequential_color_scheme, 9, false); + colors.insert(colors.begin(), wxColour(240, 240, 240)); +} +void GdaColorUtils::GetQuantile10Colors(std::vector& colors) +{ + colors.clear(); + CatClassification::PickColorSet(colors, CatClassification::sequential_color_scheme, 10, false); + colors.insert(colors.begin(), wxColour(240, 240, 240)); +} wxString GdaColorUtils::ToHexColorStr(const wxColour& c) { @@ -70,6 +505,56 @@ double Gda::ThomasWangHashDouble(uint64_t key) { return 5.42101086242752217E-20 * key; } +double Gda::ThomasWangDouble(uint64_t& key) { + key = (~key) + (key << 21); // key = (key << 21) - key - 1; + key = key ^ (key >> 24); + key = (key + (key << 3)) + (key << 8); // key * 265 + key = key ^ (key >> 14); + key = (key + (key << 2)) + (key << 4); // key * 21 + key = key ^ (key >> 28); + key = key + (key << 31); + return 5.42101086242752217E-20 * key; +} + +double Gda::factorial(unsigned int n) +{ + double r; + int i; + for(i = n-1; i > 1; i--) + r *= i; + + return r; +} + +double Gda::nChoosek(unsigned int n, unsigned int k) { + + double r = 1; + double s = 1; + int i; + int kk = k > n/2 ? k : n-k; + + for(i=n; i > kk; i--) r *= i; + for(i=(n-kk); i>0; i--) s *= i; + return r/s; +} + +wxString Gda::CreateUUID(int nSize) +{ + if (nSize < 0 || nSize >= 38) + nSize = 8; + + wxString letters = "abcdefghijklmnopqrstuvwxyz0123456789"; + + srand (time(NULL)); + + wxString uid; + while (uid.length() < nSize) { + int iSecret = rand() % letters.size(); + uid += letters[iSecret]; + } + return uid; +} + /** Use with std::sort for sorting in ascending order */ bool Gda::dbl_int_pair_cmp_less(const dbl_int_pair_type& ind1, const dbl_int_pair_type& ind2) @@ -169,6 +654,7 @@ CalculateHingeStats(const std::vector& data, } N = data_valid.size(); + is_even_num_obs = (data_valid.size() % 2) == 0; Q2_ind = (N+1)/2.0 - 1; @@ -179,6 +665,9 @@ CalculateHingeStats(const std::vector& data, Q1_ind = (N+3)/4.0 - 1; Q3_ind = (3*N+1)/4.0 - 1; } + + if (N == 0 || N < Q3_ind) return; + Q1 = (data_valid[(int) floor(Q1_ind)] + data_valid[(int) ceil(Q1_ind)])/2.0; Q2 = (data_valid[(int) floor(Q2_ind)] + data_valid[(int) ceil(Q2_ind)])/2.0; Q3 = (data_valid[(int) floor(Q3_ind)] + data_valid[(int) ceil(Q3_ind)])/2.0; @@ -226,6 +715,9 @@ double Gda::percentile(double x, const std::vector& v) double Nd = (double) N; double p_0 = (100.0/Nd) * (1.0-0.5); double p_Nm1 = (100.0/Nd) * (Nd-0.5); + + if (v.empty()) return 0; + if (x <= p_0) return v[0]; if (x >= p_Nm1) return v[N-1]; @@ -277,13 +769,20 @@ double Gda::percentile(double x, const Gda::dbl_int_pair_vec_type& v) return v[i].first; if (x < p_i) { double p_im1 = (100.0/Nd) * ((((double) i))-0.5); - return v[i-1].first + Nd*((x-p_im1)/100.0)*(v[i].first - -v[i-1].first); + return v[i-1].first + Nd*((x-p_im1)/100.0)*(v[i].first-v[i-1].first); } } return v[N-1].first; // execution should never get here } + +SampleStatistics::SampleStatistics() + : sample_size(0), min(0), max(0), mean(0), + var_with_bessel(0), var_without_bessel(0), + sd_with_bessel(0), sd_without_bessel(0) +{ +} + SampleStatistics::SampleStatistics(const std::vector& data) : sample_size(0), min(0), max(0), mean(0), var_with_bessel(0), var_without_bessel(0), @@ -599,6 +1098,12 @@ string SimpleLinearRegression::ToString() return ss.str(); } +AxisScale::AxisScale() +: data_min(0), data_max(0), scale_min(0), scale_max(0), +scale_range(0), tic_inc(0), p(0) +{ +} + AxisScale::AxisScale(double data_min_s, double data_max_s, int ticks_s, int lbl_precision_s) : data_min(0), data_max(0), scale_min(0), scale_max(0), scale_range(0), tic_inc(0), p(0), ticks(ticks_s), lbl_precision(lbl_precision_s) @@ -759,10 +1264,24 @@ wxString GenUtils::DblToStr(double x, int precision) ss << std::fixed; } ss << std::setprecision(precision); - ss << x; + ss << x; return wxString(ss.str().c_str(), wxConvUTF8); } +wxString GenUtils::IntToStr(int x, int precision) +{ + std::stringstream ss; + + + if (x < 10000000) { + ss << std::fixed; + } + ss << std::setprecision(precision); + ss << x; + + return wxString(ss.str().c_str(), wxConvUTF8); +} + wxString GenUtils::PtToStr(const wxPoint& p) { std::stringstream ss; @@ -778,7 +1297,6 @@ wxString GenUtils::PtToStr(const wxRealPoint& p) return wxString(ss.str().c_str(), wxConvUTF8); } -// NOTE: should take into account undefined values. void GenUtils::DeviationFromMean(int nObs, double* data) { if (nObs == 0) return; @@ -815,6 +1333,118 @@ void GenUtils::DeviationFromMean(std::vector& data) for (int i=0, iend=data.size(); i& undef) +{ + if (nObs == 0) return; + + double nValid = 0; + double sum = 0.0; + for (int i=0, iend=nObs; i& data) +{ + if (data.size() == 0) return; + double sum = 0.0; + double nn = data.size(); + for (int i=0, iend=data.size(); i& data, std::vector& undef) +{ + if (data.size() == 0) return; + double sum = 0.0; + double nValid = 0; + double nn = data.size(); + for (int i=0, iend=data.size(); i& x, std::vector& y) +{ + int nObs = x.size(); + double sum_x = 0; + double sum_y = 0; + for (int i=0; i& data) +{ + double sum = 0; + int nObs = data.size(); + for (int i=0; i& data) +{ + int nObs = data.size(); + if (nObs <= 1) return 0; + GenUtils::DeviationFromMean(data); + double ssum = 0.0; + for (int i=0, iend=nObs; i& data) +{ + if (data.size() <= 1) return 0; + GenUtils::DeviationFromMean(data); + double ssum = 0.0; + for (int i=0, iend=data.size(); i& undef) return true; } + bool GenUtils::StandardizeData(std::vector& data) { if (data.size() <= 1) return false; diff --git a/GenUtils.h b/GenUtils.h index 6870bf61a..c3f562a95 100644 --- a/GenUtils.h +++ b/GenUtils.h @@ -24,8 +24,10 @@ #include #include #include +#include #include #include +#include #include #include // for wxPoint / wxRealPoint #include @@ -44,9 +46,27 @@ #endif #endif +using namespace std; + class wxDC; class TableState; +namespace StringUtils { + int utf8_strlen(const string& str); +} + +namespace DbfFileUtils { + void SuggestDoubleParams(int length, int decimals, int* suggest_len, int* suggest_dec); + double GetMaxDouble(int length, int decimals,int* suggest_len=0, int* suggest_dec=0); + wxString GetMaxDoubleString(int length, int decimals); + double GetMinDouble(int length, int decimals, int* suggest_len=0, int* suggest_dec=0); + wxString GetMinDoubleString(int length, int decimals); + wxInt64 GetMaxInt(int length); + wxString GetMaxIntString(int length); + wxInt64 GetMinInt(int length); + wxString GetMinIntString(int length); +} + namespace GdaColorUtils { /** Returns colour in 6-hex-digit HTML format. Eg wxColour(255,0,0) -> "#FF0000" */ @@ -55,6 +75,42 @@ namespace GdaColorUtils { brightness = 75 by default, will slightly darken the input color. brightness = 0 is black, brightness = 200 is white. */ wxColour ChangeBrightness(const wxColour& input_col, int brightness = 75); + + void GetUnique20Colors(vector& colors); + + void GetLISAColors(vector& colors); + void GetLISAColorLabels(vector& labels); + + void GetLocalGColors(vector& colors); + void GetLocalGColorLabels(vector& labels); + + void GetLocalJoinCountColors(vector& colors); + void GetLocalJoinCountColorLabels(vector& labels); + + void GetLocalGearyColors(vector& colors); + void GetLocalGearyColorLabels(vector& labels); + + void GetMultiLocalGearyColors(vector& colors); + void GetMultiLocalGearyColorLabels(vector& labels); + + void GetPercentileColors(vector& colors); + void GetPercentileColorLabels(vector& labels); + + void GetBoxmapColors(vector& colors); + void GetBoxmapColorLabels(vector& labels); + + void GetStddevColors(vector& colors); + void GetStddevColorLabels(vector& labels); + + void GetQuantile2Colors(vector& colors); + void GetQuantile3Colors(vector& colors); + void GetQuantile4Colors(vector& colors); + void GetQuantile5Colors(vector& colors); + void GetQuantile6Colors(vector& colors); + void GetQuantile7Colors(vector& colors); + void GetQuantile8Colors(vector& colors); + void GetQuantile9Colors(vector& colors); + void GetQuantile10Colors(vector& colors); } namespace Gda { @@ -71,18 +127,27 @@ namespace Gda { good random numbers. This is useful for doing parallel Monte Carlo simulations with a common random seed for reproducibility. */ double ThomasWangHashDouble(uint64_t key); + + double ThomasWangDouble(uint64_t& key); inline bool IsNaN(double x) { return x != x; } inline bool IsFinite(double x) { return x-x == 0; } -} - - -namespace Gda { + + double factorial(unsigned int n); + + double nChoosek(unsigned int n, unsigned int r); + + wxString CreateUUID(int nSize); + + wxString DetectDateFormat(wxString s, vector& date_items); + + unsigned long long DateToNumber(wxString s_date, wxRegEx& regex, vector& date_items); + // useful for sorting a vector of double with their original indexes: - // std::vector data; - // std::sort(data.begin(), data.end(), Gda::dbl_int_pair_cmp_less); - typedef std::pair dbl_int_pair_type; - typedef std::vector dbl_int_pair_vec_type; + // vector data; + // sort(data.begin(), data.end(), Gda::dbl_int_pair_cmp_less); + typedef pair dbl_int_pair_type; + typedef vector dbl_int_pair_vec_type; bool dbl_int_pair_cmp_less(const dbl_int_pair_type& ind1, const dbl_int_pair_type& ind2); bool dbl_int_pair_cmp_greater(const dbl_int_pair_type& ind1, @@ -91,6 +156,18 @@ namespace Gda { const dbl_int_pair_type& ind2); bool dbl_int_pair_cmp_second_greater(const dbl_int_pair_type& ind1, const dbl_int_pair_type& ind2); + typedef pair str_int_pair_type; + typedef vector str_int_pair_vec_type; + + // Percentile using Linear interpolation between closest ranks + // Definition as described in Matlab documentation + // and at http://en.wikipedia.org/wiki/Percentile + // Assumes that input vector v is sorted in ascending order. + // Duplicate values are allowed. + double percentile(double x, const vector& v); + double percentile(double x, const Gda::dbl_int_pair_vec_type& v); + double percentile(double x, const Gda::dbl_int_pair_vec_type& v, + const vector& undefs); } // Note: In "Exploratory Data Analysis", pp 32-34, 1977, Tukey only defines @@ -137,9 +214,9 @@ struct HingeStats { max_val(0), is_even_num_obs(false), Q2(0), Q2_ind(0), Q1(0), Q1_ind(0), Q3(0), Q3_ind(0), min_IQR_ind(0), max_IQR_ind(0) {} - void CalculateHingeStats(const std::vector& data); - void CalculateHingeStats(const std::vector& data, - const std::vector& data_undef); + void CalculateHingeStats(const vector& data); + void CalculateHingeStats(const vector& data, + const vector& data_undef); int num_obs; double min_val; double max_val; @@ -163,35 +240,21 @@ struct HingeStats { double extreme_upper_val_30; }; -namespace Gda { - // Percentile using Linear interpolation between closest ranks - // Definition as described in Matlab documentation - // and at http://en.wikipedia.org/wiki/Percentile - // Assumes that input vector v is sorted in ascending order. - // Duplicate values are allowed. - double percentile(double x, const std::vector& v); - double percentile(double x, const Gda::dbl_int_pair_vec_type& v); - double percentile(double x, const Gda::dbl_int_pair_vec_type& v, - const std::vector& undefs); -} - struct SampleStatistics { - SampleStatistics() : sample_size(0), min(0), max(0), mean(0), - var_with_bessel(0), var_without_bessel(0), - sd_with_bessel(0), sd_without_bessel(0) {} - SampleStatistics(const std::vector& data); - SampleStatistics(const std::vector& data, - const std::vector& undefs); - SampleStatistics(const std::vector& data, - const std::vector& undefs1, - const std::vector& undefs2); - void CalculateFromSample(const std::vector& data); - void CalculateFromSample(const std::vector& data, - const std::vector& undefs); - void CalculateFromSample(const std::vector& data, - const std::vector& undefs); + SampleStatistics(); + SampleStatistics(const vector& data); + SampleStatistics(const vector& data, + const vector& undefs); + SampleStatistics(const vector& data, + const vector& undefs1, + const vector& undefs2); + void CalculateFromSample(const vector& data); + void CalculateFromSample(const vector& data, + const vector& undefs); + void CalculateFromSample(const vector& data, + const vector& undefs); - std::string ToString(); + string ToString(); int sample_size; double min; @@ -202,12 +265,13 @@ struct SampleStatistics { double sd_with_bessel; double sd_without_bessel; - static double CalcMin(const std::vector& data); - static double CalcMax(const std::vector& data); - static void CalcMinMax(const std::vector& data, double& min, - double& max); - static double CalcMean(const std::vector& data); - static double CalcMean(const std::vector& data); + static double CalcMin(const vector& data); + static double CalcMax(const vector& data); + static void CalcMinMax(const vector& data, double& min, + double& max); + static double CalcMean(const vector& data); + static double CalcMean(const vector& data); + }; struct SimpleLinearRegression { @@ -218,26 +282,26 @@ struct SimpleLinearRegression { valid(false), valid_correlation(false), valid_std_err(false) {} - SimpleLinearRegression(const std::vector& X, - const std::vector& Y, + SimpleLinearRegression(const vector& X, + const vector& Y, double meanX, double meanY, double varX, double varY); - SimpleLinearRegression(const std::vector& X, - const std::vector& Y, - const std::vector& X_undef, - const std::vector& Y_undef, + SimpleLinearRegression(const vector& X, + const vector& Y, + const vector& X_undef, + const vector& Y_undef, double meanX, double meanY, double varX, double varY); - void CalculateRegression(const std::vector& X, - const std::vector& Y, + void CalculateRegression(const vector& X, + const vector& Y, double meanX, double meanY, double varX, double varY); static double TScoreTo2SidedPValue(double tscore, int df); - std::string ToString(); + string ToString(); int n; double covariance; @@ -259,31 +323,28 @@ struct SimpleLinearRegression { }; struct AxisScale { - AxisScale() : data_min(0), data_max(0), - scale_min(0), scale_max(0), scale_range(0), tic_inc(0), p(0), - ticks(5) {} + AxisScale(); AxisScale(double data_min_s, double data_max_s, int ticks_s = 5, int lbl_precision=2); AxisScale(const AxisScale& s); - virtual AxisScale& operator=(const AxisScale& s); - virtual ~AxisScale() {} + AxisScale& operator=(const AxisScale& s); void CalculateScale(double data_min_s, double data_max_s, const int ticks = 5); void SkipEvenTics(); // only display every other tic value void ShowAllTics(); - std::string ToString(); + string ToString(); double data_min; double data_max; double scale_min; double scale_max; double scale_range; - double tic_inc; + double tic_inc; int lbl_precision; int ticks; int p; // power of ten to scale significant digit - std::vectortics; // numerical tic values - std::vectortics_str; // tics in formated string representation - std::vectortics_str_show; // if false, then don't draw tic string + vectortics; // numerical tic values + vectortics_str; // tics in formated string representation + vectortics_str_show; // if false, then don't draw tic string }; @@ -294,19 +355,23 @@ namespace GenUtils { wxString Pad(const wxString& s, int width, bool pad_left=true); wxString PadTrim(const wxString& s, int width, bool pad_left=true); wxString DblToStr(double x, int precision = 3); + wxString IntToStr(int x, int precision = 0); wxString PtToStr(const wxPoint& p); wxString PtToStr(const wxRealPoint& p); + void MeanAbsoluteDeviation(int nObs, double* data); + void MeanAbsoluteDeviation(int nObs, double* data, vector& undef); + void MeanAbsoluteDeviation(vector& data); + void MeanAbsoluteDeviation(vector& data, vector& undef); void DeviationFromMean(int nObs, double* data); - void DeviationFromMean(int nObs, double* data, std::vector& undef); - void DeviationFromMean(std::vector& data); + void DeviationFromMean(int nObs, double* data, vector& undef); + void DeviationFromMean(vector& data); + double Sum(vector& data); + double SumOfSquares(vector& data); bool StandardizeData(int nObs, double* data); - bool StandardizeData(int nObs, double* data, std::vector& undef); - bool StandardizeData(std::vector& data); - template T abs(const T& x); - template const T& max(const T& x, const T& y); - template const T& min(const T& x, const T& y); - template const T& max(const T& x, const T& y, const T& z); - template const T& min(const T& x, const T& y, const T& z); + bool StandardizeData(int nObs, double* data, vector& undef); + bool StandardizeData(vector& data); + double Correlation(vector& x, vector& y); + double GetVariance(vector& data); wxString swapExtension(const wxString& fname, const wxString& ext); wxString GetFileDirectory(const wxString& path); wxString GetFileName(const wxString& path); @@ -329,12 +394,12 @@ namespace GenUtils { by SimplfyPath to see if they can be converted into a relative path with respect to the current Working Directory (project file location). */ wxString SimplifyPath(const wxFileName& wd, const wxString& path); - void SplitLongPath(const wxString& path, std::vector& parts, + void SplitLongPath(const wxString& path, vector& parts, wxString& html_formatted, int max_chars_per_part = 30); wxInt32 Reverse(const wxInt32 &val); long ReverseInt(const int &val); - void SkipTillNumber(std::istream &s); + void SkipTillNumber(istream &s); void longToString(const long d, char* Id, const int base); double distance(const wxRealPoint& p1, const wxRealPoint& p2); double distance(const wxRealPoint& p1, const wxPoint& p2); @@ -354,17 +419,86 @@ namespace GenUtils { bool isEmptyOrSpaces(const wxString& str); bool ExistsShpShxDbf(const wxFileName& fname, bool* shp_found, bool* shx_found, bool* dbf_found); - wxString FindLongestSubString(const std::vector strings, + wxString FindLongestSubString(const vector strings, bool case_sensitive=false); - wxString WrapText(wxWindow *win, const wxString& text, int widthMax); - wxString GetBasemapCacheDir(); wxString GetWebPluginsDir(); wxString GetResourceDir(); wxString GetSamplesDir(); + bool less_vectors(const vector& a,const vector& b); + + // Act like matlab's [Y,I] = SORT(X) + // Input: + // unsorted unsorted vector + // Output: + // sorted sorted vector, allowed to be same as unsorted + // index_map an index map such that sorted[i] = unsorted[index_map[i]] + template + void sort( + vector &unsorted, + vector &sorted, + vector &index_map); + // Act like matlab's Y = X[I] + // where I contains a vector of indices so that after, + // Y[j] = X[I[j]] for index j + // this implies that Y.size() == I.size() + // X and Y are allowed to be the same reference + template< class T > + void reorder( + vector & unordered, + vector const & index_map, + vector & ordered); + + // Comparison struct used by sort + // http://bytes.com/topic/c/answers/132045-sort-get-index + template struct index_cmp + { + index_cmp(const T arr) : arr(arr) {} + bool operator()(const size_t a, const size_t b) const + { + return arr[a] < arr[b]; + } + const T arr; + }; - bool less_vectors(const std::vector& a,const std::vector& b); + template + void sort( + vector & unsorted, + vector & sorted, + vector & index_map) + { + // Original unsorted index map + index_map.resize(unsorted.size()); + for(size_t i=0;i& >(unsorted)); + + sorted.resize(unsorted.size()); + reorder(unsorted,index_map,sorted); + } + // This implementation is O(n), but also uses O(n) extra memory + template< class T > + void reorder( + vector & unordered, + vector const & index_map, + vector & ordered) + { + // copy for the reorder according to index_map, because unsorted may also be + // sorted + vector copy = unordered; + ordered.resize(index_map.size()); + for(int i = 0; i T GenUtils::abs(const T& x) -{ - if (x >= 0) return x; - return -x; -} - -template const T& GenUtils::max(const T& x, const T& y) -{ - return x < y ? y : x; -} - -template const T& GenUtils::min(const T& x, const T& y) -{ - return x < y ? x : y; -} - -template const T& GenUtils::max(const T& x, const T& y, const T& z) -{ - if (x > y) { - return x > z ? x : z; - } else { - return y > z ? y : z; - } -} - -template const T& GenUtils::min(const T& x, const T& y, const T& z) -{ - if (x < y) { - return x < z ? x : z; - } else { - return y < z ? y : z; - } -} - #endif diff --git a/GeneralWxUtils.cpp b/GeneralWxUtils.cpp index dce6d5c00..67eae8122 100644 --- a/GeneralWxUtils.cpp +++ b/GeneralWxUtils.cpp @@ -17,13 +17,137 @@ * along with this program. If not, see . */ -#include "GeneralWxUtils.h" #include #include #include #include #include +#include +#include +#include +#include + + +#include "GeneralWxUtils.h" +//////////////////////////////////////////////////////////////////////// +// +// +//////////////////////////////////////////////////////////////////////// +BEGIN_EVENT_TABLE(SimpleReportTextCtrl, wxTextCtrl) +EVT_CONTEXT_MENU(SimpleReportTextCtrl::OnContextMenu) +END_EVENT_TABLE() + +void SimpleReportTextCtrl::OnContextMenu(wxContextMenuEvent& event) +{ + wxMenu* menu = new wxMenu; + // Some standard items + menu->Append(XRCID("SAVE_SIMPLE_REPORT"), _("&Save")); + menu->AppendSeparator(); + menu->Append(wxID_UNDO, _("&Undo")); + menu->Append(wxID_REDO, _("&Redo")); + menu->AppendSeparator(); + menu->Append(wxID_CUT, _("Cu&t")); + menu->Append(wxID_COPY, _("&Copy")); + menu->Append(wxID_PASTE, _("&Paste")); + menu->Append(wxID_CLEAR, _("&Delete")); + menu->AppendSeparator(); + menu->Append(wxID_SELECTALL, _("Select &All")); + + // Add any custom items here + Connect(XRCID("SAVE_SIMPLE_REPORT"), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(SimpleReportTextCtrl::OnSaveClick)); + + PopupMenu(menu); +} + +void SimpleReportTextCtrl::OnSaveClick( wxCommandEvent& event ) +{ + wxLogMessage("In SimpleReportTextCtrl::OnSaveClick()"); + wxFileDialog dlg( this, "Save PCA results", wxEmptyString, + wxEmptyString, + "TXT files (*.txt)|*.txt", + wxFD_SAVE ); + if (dlg.ShowModal() != wxID_OK) return; + + wxFileName new_txt_fname(dlg.GetPath()); + wxString new_txt = new_txt_fname.GetFullPath(); + wxFFileOutputStream output(new_txt); + if (output.IsOk()) { + wxTextOutputStream txt_out( output ); + txt_out << this->GetValue(); + txt_out.Flush(); + output.Close(); + } +} +//////////////////////////////////////////////////////////////////////// +// +// +//////////////////////////////////////////////////////////////////////// + +ScrolledDetailMsgDialog::ScrolledDetailMsgDialog(const wxString & title, const wxString & msg, const wxString & details, const wxSize &size, const wxArtID & art_id) +: wxDialog(NULL, -1, title, wxDefaultPosition, size, wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER) +{ + + wxPanel *panel = new wxPanel(this, -1); + + wxBoxSizer *vbox0 = new wxBoxSizer(wxVERTICAL); + wxStaticText *st = new wxStaticText(panel, -1, msg, wxDefaultPosition, wxDefaultSize, wxTE_WORDWRAP); + tc = new SimpleReportTextCtrl(panel, XRCID("ID_TEXTCTRL_1"), details, wxDefaultPosition, wxSize(-1, 300)); + vbox0->Add(st, 0, wxBOTTOM, 10); + vbox0->Add(tc, 1, wxEXPAND); + + wxBoxSizer *hbox0 = new wxBoxSizer(wxHORIZONTAL); + wxBitmap save = wxArtProvider::GetBitmap(wxART_WARNING); + wxStaticBitmap *warn = new wxStaticBitmap(panel, -1, save); + hbox0->Add(warn, 0, wxRIGHT, 5); + hbox0->Add(vbox0, 1); + + panel->SetSizer(hbox0); + + wxBoxSizer *hbox1 = new wxBoxSizer(wxHORIZONTAL); + wxButton *saveButton = new wxButton(this, XRCID("SAVE_DETAILS"), _("Save Details"), wxDefaultPosition, wxSize(130, -1)); + wxButton *okButton = new wxButton(this, wxID_OK, _("Ok"), wxDefaultPosition, wxSize(110, -1)); + hbox1->Add(saveButton, 1, wxRIGHT, 30); + hbox1->Add(okButton, 1); + + Connect(XRCID("SAVE_DETAILS"), wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(ScrolledDetailMsgDialog::OnSaveClick)); + + wxBoxSizer *vbox = new wxBoxSizer(wxVERTICAL); + vbox->Add(panel, 1, wxEXPAND | wxALL, 20); + vbox->Add(hbox1, 0, wxALIGN_CENTER | wxTOP | wxBOTTOM, 10); + + SetSizer(vbox); + + Centre(); + ShowModal(); + + Destroy(); +} + +void ScrolledDetailMsgDialog::OnSaveClick( wxCommandEvent& event ) +{ + wxLogMessage("In ScrolledDetailMsgDialog::OnSaveClick()"); + wxFileDialog dlg( this, "Save results", wxEmptyString, + wxEmptyString, + "TXT files (*.txt)|*.txt", + wxFD_SAVE ); + if (dlg.ShowModal() != wxID_OK) return; + + wxFileName new_txt_fname(dlg.GetPath()); + wxString new_txt = new_txt_fname.GetFullPath(); + wxFFileOutputStream output(new_txt); + if (output.IsOk()) { + wxTextOutputStream txt_out( output ); + txt_out << tc->GetValue(); + txt_out.Flush(); + output.Close(); + } +} + +//////////////////////////////////////////////////////////////////////// +// +// +//////////////////////////////////////////////////////////////////////// wxOperatingSystemId GeneralWxUtils::GetOsId() { static wxOperatingSystemId osId = @@ -170,6 +294,7 @@ bool GeneralWxUtils::ReplaceMenu(wxMenuBar* mb, const wxString& title, //mb->Replace(m_ind, newMenu, title); wxMenu* prev_opt_menu = mb->Remove(m_ind); mb->Insert(m_ind, newMenu, title); + // The following line shouldn't be needed, but on wxWidgets 2.9.2, the // menu label is set to empty after Replace is called. //mb->SetMenuLabel(m_ind, title); @@ -326,5 +451,76 @@ wxMenu* GeneralWxUtils::FindMenu(wxMenuBar* mb, const wxString& menuTitle) return mb->GetMenu(menu); } +wxColour GeneralWxUtils::PickColor(wxWindow *parent, wxColour& col) +{ + wxColourData data; + data.SetColour(col); + data.SetChooseFull(true); + int ki; + for (ki = 0; ki < 16; ki++) { + wxColour colour(ki * 16, ki * 16, ki * 16); + data.SetCustomColour(ki, colour); + } + + wxColourDialog dialog(parent, &data); + dialog.SetTitle(_("Choose Cateogry Color")); + if (dialog.ShowModal() == wxID_OK) { + wxColourData retData = dialog.GetColourData(); + return retData.GetColour(); + } + return col; +} + +void GeneralWxUtils::SaveWindowAsImage(wxWindow *win, wxString title) +{ + //Create a DC for the whole screen area + wxWindowDC dcScreen(win); + + //Get the size of the screen/DC + wxCoord screenWidth, screenHeight; + dcScreen.GetSize(&screenWidth, &screenHeight); + + //Create a Bitmap that will later on hold the screenshot image + //Note that the Bitmap must have a size big enough to hold the screenshot + //-1 means using the current default colour depth + wxSize new_sz = win->FromDIP(wxSize(screenWidth, screenHeight)); + wxBitmap screenshot(new_sz); + + //Create a memory DC that will be used for actually taking the screenshot + wxMemoryDC memDC; + //Tell the memory DC to use our Bitmap + //all drawing action on the memory DC will go to the Bitmap now + memDC.SelectObject(screenshot); + //Blit (in this case copy) the actual screen on the memory DC + //and thus the Bitmap + + memDC.Blit( 0, //Copy to this X coordinate + 0, //Copy to this Y coordinate + screenWidth, //Copy this width + screenHeight, //Copy this height + &dcScreen, //From where do we copy? + 0, //What's the X offset in the original DC? + 0 //What's the Y offset in the original DC? + ); + //Select the Bitmap out of the memory DC by selecting a new + //uninitialized Bitmap + memDC.SelectObject(wxNullBitmap); + + //Our Bitmap now has the screenshot, so let's save it :-) + wxString default_fname(title); + wxString filter = "BMP|*.bmp|PNG|*.png"; + wxFileDialog dialog(NULL, _("Save Image to File"), wxEmptyString, + default_fname, filter, + wxFD_SAVE | wxFD_OVERWRITE_PROMPT); + if (dialog.ShowModal() != wxID_OK) return; + wxFileName fname = wxFileName(dialog.GetPath()); + wxString str_fname = fname.GetPathWithSep() + fname.GetName(); + + if (dialog.GetFilterIndex() == 0) { + screenshot.SaveFile(str_fname + ".bmp", wxBITMAP_TYPE_BMP); + } else if (dialog.GetFilterIndex() == 1) { + screenshot.SaveFile(str_fname + ".png", wxBITMAP_TYPE_PNG); + } +} diff --git a/GeneralWxUtils.h b/GeneralWxUtils.h index 30b52f46c..bdbd3f004 100644 --- a/GeneralWxUtils.h +++ b/GeneralWxUtils.h @@ -22,6 +22,11 @@ #include #include +#include +#include +#include + +#include "DialogTools/VariableSettingsDlg.h" class GeneralWxUtils { public: @@ -51,6 +56,42 @@ class GeneralWxUtils { static bool CheckMenuItem(wxMenu* menu, int id, bool check); static bool SetMenuItemText(wxMenu* menu, int id, const wxString& text); static wxMenu* FindMenu(wxMenuBar* mb, const wxString& menuTitle); + static wxColour PickColor(wxWindow* parent, wxColour& col); + static void SaveWindowAsImage(wxWindow* win, wxString title); + //static std::set GetFieldNamesFromTable(TableInterface* table); +}; + +class SimpleReportTextCtrl : public wxTextCtrl +{ +public: + SimpleReportTextCtrl(wxWindow* parent, wxWindowID id, const wxString& value = "", + const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, + long style = wxTE_MULTILINE | wxTE_READONLY | wxTE_RICH | wxTE_RICH2, const wxValidator& validator = wxDefaultValidator, + const wxString& name = wxTextCtrlNameStr) + : wxTextCtrl(parent, id, value, pos, size, style, validator, name) + { + if (GeneralWxUtils::isWindows()) { + wxFont font(8,wxFONTFAMILY_TELETYPE,wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL); + SetFont(font); + } else { + wxFont font(12,wxFONTFAMILY_TELETYPE,wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL); + SetFont(font); + } + } +protected: + void OnContextMenu(wxContextMenuEvent& event); + void OnSaveClick( wxCommandEvent& event ); + DECLARE_EVENT_TABLE() +}; + +class ScrolledDetailMsgDialog : public wxDialog +{ +public: + ScrolledDetailMsgDialog(const wxString & title, const wxString & msg, const wxString & details, const wxSize &size = wxSize(540, 280), const wxArtID & art_id = wxART_WARNING); + + SimpleReportTextCtrl *tc; + + void OnSaveClick( wxCommandEvent& event ); }; #endif diff --git a/GeoDa.cpp b/GeoDa.cpp index cce487bd2..4b6ef4ebb 100644 --- a/GeoDa.cpp +++ b/GeoDa.cpp @@ -71,8 +71,6 @@ #include #include -#include "DataViewer/DataChangeType.h" -#include "DataViewer/DbfTable.h" #include "DataViewer/DataViewerAddColDlg.h" #include "DataViewer/DataViewerDeleteColDlg.h" #include "DataViewer/DataViewerEditFieldPropertiesDlg.h" @@ -116,8 +114,19 @@ #include "DialogTools/ReportBugDlg.h" #include "DialogTools/SaveToTableDlg.h" #include "DialogTools/KMeansDlg.h" +#include "DialogTools/MaxpDlg.h" +#include "DialogTools/SpectralClusteringDlg.h" #include "DialogTools/HClusterDlg.h" - +#include "DialogTools/HDBScanDlg.h" +#include "DialogTools/CreateGridDlg.h" +#include "DialogTools/RedcapDlg.h" +#include "DialogTools/MDSDlg.h" +#include "DialogTools/AggregateDlg.h" +#include "DialogTools/GeocodingDlg.h" +#include "DialogTools/PCASettingsDlg.h" +#include "DialogTools/SkaterDlg.h" +#include "DialogTools/PreferenceDlg.h" +#include "DialogTools/SpatialJoinDlg.h" #include "Explore/CatClassification.h" #include "Explore/CovSpView.h" @@ -138,6 +147,8 @@ #include "Explore/ConditionalHistogramView.h" #include "Explore/CartogramNewView.h" #include "Explore/GStatCoordinator.h" +#include "Explore/MLJCMapNewView.h" +#include "Explore/MLJCCoordinator.h" #include "Explore/ScatterNewPlotView.h" #include "Explore/ScatterPlotMatView.h" #include "Explore/MapNewView.h" @@ -147,18 +158,21 @@ #include "Explore/3DPlotView.h" #include "Explore/WebViewExampleWin.h" #include "Explore/Basemap.h" +#include "Explore/ColocationMapView.h" #include "Regression/DiagnosticReport.h" #include "ShapeOperations/CsvFileUtils.h" -#include "ShapeOperations/ShapeUtils.h" #include "ShapeOperations/WeightsManager.h" #include "ShapeOperations/WeightsManState.h" #include "ShapeOperations/OGRDataAdapter.h" #include "VarCalc/CalcHelp.h" +#include "Algorithms/redcap.h" +#include "Algorithms/geocoding.h" +#include "Algorithms/fastcluster.h" -#include "ShpFile.h" +#include "wxTranslationHelper.h" #include "GdaException.h" #include "FramesManager.h" #include "GdaConst.h" @@ -169,20 +183,16 @@ #include "TemplateFrame.h" #include "SaveButtonManager.h" #include "GeoDa.h" - #include "version.h" - +#include "arizona/viz3/plots/scatterplot.h" +#include "rc/GeoDaIcon-16x16.xpm" //The XML Handler should be explicitly registered: #include - // The following is defined in rc/GdaAppResouces.cpp. This file was -// compiled with: -/* - wxrc dialogs.xrc menus.xrc toolbar.xrc \ - --cpp-code --output=GdaAppResources.cpp --function=GdaInitXmlResource -*/ +// compiled with: wxrc dialogs.xrc menus.xrc toolbar.xrc +// --cpp-code --output=GdaAppResources.cpp --function=GdaInitXmlResource // and combines all resouces file into single source file that is linked into // the application binary. extern void GdaInitXmlResource(); @@ -191,7 +201,7 @@ const int ID_TEST_MAP_FRAME = wxID_HIGHEST + 10; IMPLEMENT_APP(GdaApp) -GdaApp::GdaApp() : checker(0), server(0), m_pLogFile(0) +GdaApp::GdaApp() : m_pLogFile(0) { //Don't call wxHandleFatalExceptions so that a core dump file will be //produced for debugging. @@ -200,15 +210,12 @@ GdaApp::GdaApp() : checker(0), server(0), m_pLogFile(0) GdaApp::~GdaApp() { - if (server) delete server; server = 0; - wxLog::SetActiveTarget(NULL); if (m_pLogFile != NULL){ fclose(m_pLogFile); } } -#include "rc/GeoDaIcon-16x16.xpm" bool GdaApp::OnInit(void) { @@ -217,53 +224,7 @@ bool GdaApp::OnInit(void) // initialize OGR connection OGRDataAdapter::GetInstance(); - - if (!GeneralWxUtils::isMac()) { - // GeoDa operates in single-instance mode. This means that for - // a given user, only one instance of GeoDa will remain open - // at a time. This is not needed on Mac OSX since by default - // programs are only launched in single instance mode. This might - // not be true for launching directly from the command line, so - // this might need to change in the future. - checker = new wxSingleInstanceChecker("GdaApp"); - - if (!checker->IsAnotherRunning()) { - // This is the first instance of GeoDa running for this - // user, so this instance becomes the "server." - ///LOG_MSG("First instance of GeoDa: creating server for future program instances."); - server = new GdaServer; - if (!server->Create("GdaApp")) { - //LOG_MSG("Error: Failed to create in IPC service."); - } - } else { - // Another instance of GeoDa is already running. This other - // instance is acting as the "server" so this instance - // becomes the "client" and requests that the server open - // the requested project before this instance exits. - GdaClient* client = new GdaClient; - - // host_name will be ignored under DDE (Windows and - // possibly Linux), but will be used on platforms - // implementing wxClient/wxServer using TCP/IP. - wxString host_name("localhost"); - - wxConnectionBase* connection = - client->MakeConnection(host_name, "GdaApp", "GdaApp"); - - if (connection) { - connection->Execute(cmd_line_proj_file_name); - connection->Disconnect(); - delete connection; - } else { - wxString msg = _("The existing GeoDa instance may be too busy to respond.\nPlease close any open dialogs and try again."); - } - delete client; - delete checker; // OnExit() won't be called if we return false - checker = 0; - return false; - } - } - + // By defaut, GDAL will use user's system locale to read any input datasource // However, user can change the Separators in GeoDa, after re-open the // datasource, CSV reader will use the Separators @@ -276,7 +237,20 @@ bool GdaApp::OnInit(void) // load preferences PreferenceDlg::ReadFromCache(); - + + // load language here: GdaConst::gda_ui_language + // search_path is the ./lang directory + // config_path it the exe directory (every user will have a different config file?) + wxFileName appFileName(argv[0]); + appFileName.Normalize(wxPATH_NORM_DOTS|wxPATH_NORM_ABSOLUTE| wxPATH_NORM_TILDE); + wxString search_path = appFileName.GetPath() + wxFileName::GetPathSeparator() + "lang"; + // load language from lang/config.ini if user specified any + wxString config_path = search_path + wxFileName::GetPathSeparator()+ "config.ini"; + bool use_native_config = false; + m_TranslationHelper = new wxTranslationHelper(*this, search_path, use_native_config); + m_TranslationHelper->SetConfigPath(config_path); + m_TranslationHelper->Load(); + // Other GDAL configurations if (GdaConst::hide_sys_table_postgres == false) { CPLSetConfigOption("PG_LIST_ALL_TABLES", "YES"); @@ -287,6 +261,8 @@ bool GdaApp::OnInit(void) if (GdaConst::gdal_http_timeout >= 0 ) { CPLSetConfigOption("GDAL_HTTP_TIMEOUT", wxString::Format("%d", GdaConst::gdal_http_timeout)); } + CPLSetConfigOption("OGR_XLS_HEADERS", "FORCE"); + CPLSetConfigOption("OGR_XLSX_HEADERS", "FORCE"); // will suppress "iCCP: known incorrect sRGB profile" warning message // in wxWidgets 2.9.5. This is a bug in libpng. See wxWidgets trac @@ -307,37 +283,60 @@ bool GdaApp::OnInit(void) GdaInitXmlResource(); // call the init function in GdaAppResources.cpp + // check crash + if (GdaConst::disable_crash_detect == false) { + std::vector items = OGRDataAdapter::GetInstance().GetHistory("NoCrash"); + if (items.size() > 0) { + wxString no_crash = items[0]; + if (no_crash == "false") { + // ask user to send crash data + wxString msg = _("It looks like GeoDa has been terminated abnormally. \nDo you want to send a crash report to GeoDa team? \n\n(Optional) Please leave your email address,\nso we can send a follow-up email once we have a fix."); + wxString ttl = _("Send Crash Report"); + wxString user_email = GdaConst::gda_user_email; + wxTextEntryDialog msgDlg(GdaFrame::GetGdaFrame(), msg, ttl, user_email, + wxOK | wxCANCEL | wxCENTRE ); + if (msgDlg.ShowModal() == wxID_OK) { + user_email = msgDlg.GetValue(); + if (user_email != GdaConst::gda_user_email) { + OGRDataAdapter::GetInstance().AddEntry("gda_user_email", user_email); + GdaConst::gda_user_email = user_email; + } + wxString ttl = "Crash Report"; + wxString body; + body << "From: " << user_email << "\n Details:"; + ReportBugDlg::CreateIssue(ttl, body); + } + } + } + OGRDataAdapter::GetInstance().AddEntry("NoCrash", "false"); + } + int frameWidth = 980; int frameHeight = 80; if (GeneralWxUtils::isMac()) { frameWidth = 1052; frameHeight = 80; - } - if (GeneralWxUtils::isWindows()) { + } else if (GeneralWxUtils::isWindows()) { frameWidth = 1160; frameHeight = 120; - } - if (GeneralWxUtils::isUnix()) { // assumes GTK + } else if (GeneralWxUtils::isUnix()) { // assumes GTK frameWidth = 1060; frameHeight = 120; #ifdef __linux__ wxLinuxDistributionInfo linux_info = wxGetLinuxDistributionInfo(); - if (linux_info.Description.Lower().Contains("centos")) + if (linux_info.Description.Lower().Contains("centos")) { frameHeight = 180; + } #endif - } - wxPoint appFramePos = wxDefaultPosition; - if (GeneralWxUtils::isUnix() || GeneralWxUtils::isMac()) { - appFramePos = wxPoint(80,60); - } + wxPoint appFramePos = wxPoint(80,60); int screenX = wxSystemSettings::GetMetric ( wxSYS_SCREEN_X ); if (screenX < frameWidth) { frameWidth = screenX; - appFramePos = wxPoint(0, 50); + appFramePos = wxPoint(0, 0); } wxFrame* frame = new GdaFrame("GeoDa", appFramePos, @@ -346,7 +345,6 @@ bool GdaApp::OnInit(void) frame->Show(true); frame->SetMinSize(wxSize(640, frameHeight)); - //GdaFrame::GetGdaFrame()->Show(true); SetTopWindow(GdaFrame::GetGdaFrame()); if (GeneralWxUtils::isWindows()) { @@ -363,36 +361,10 @@ bool GdaApp::OnInit(void) } } - if (!cmd_line_proj_file_name.IsEmpty()) { - wxString proj_fname(cmd_line_proj_file_name); - GdaFrame::GetGdaFrame()->OpenProject(proj_fname); - } - wxPoint welcome_pos = appFramePos; welcome_pos.y += 150; - - // check crash - if (GdaConst::disable_crash_detect == false) { - std::vector items = OGRDataAdapter::GetInstance().GetHistory("NoCrash"); - if (items.size() > 0) { - std::string no_crash = items[0]; - if (no_crash == "false") { - // ask user to send crash data - wxString msg = _("It looks like GeoDa has been terminated abnormally. \nDo you want to send a crash report to GeoDa team?"); - wxString ttl = _("Send Crash Report"); - wxMessageDialog msgDlg(GdaFrame::GetGdaFrame(), msg, ttl, - wxYES_NO | wxNO_DEFAULT | wxICON_QUESTION ); - if (msgDlg.ShowModal() == wxID_YES) { - //wxCommandEvent ev; - //GdaFrame::GetGdaFrame()->OnReportBug(ev); - wxString ttl = "Crash Report"; - ReportBugDlg::CreateIssue(ttl, "Details:"); - } - } - } - OGRDataAdapter::GetInstance().AddEntry("NoCrash", "false"); - } + // setup gdaldata directory for libprj wxString exePath = wxStandardPaths::Get().GetExecutablePath(); wxFileName exeFile(exePath); wxString exeDir = exeFile.GetPathWithSep(); @@ -400,6 +372,10 @@ bool GdaApp::OnInit(void) #ifdef __WIN32__ wxString gal_data_dir = exeDir + "data"; wxSetEnv("GEODA_GDAL_DATA", gal_data_dir); + //CPLSetConfigOption("GEODA_GDAL_DATA", GET_ENCODED_FILENAME(gal_data_dir)); +#elif defined __linux__ + wxString gal_data_dir = exeDir + "gdaldata"; + wxSetEnv("GEODA_GDAL_DATA", gal_data_dir); CPLSetConfigOption("GEODA_GDAL_DATA", GET_ENCODED_FILENAME(gal_data_dir)); #else wxString gal_data_dir = exeDir + "../Resources/gdaldata"; @@ -432,78 +408,71 @@ bool GdaApp::OnInit(void) Gda::version_build, Gda::version_subbuild); wxLogMessage(versionlog); + wxLogMessage(loggerFile); - // check update in a new thread - if (GdaConst::disable_auto_upgrade == false) { - CallAfter(&GdaFrame::CheckUpdate); + + if (!cmd_line_proj_file_name.IsEmpty()) { + wxString proj_fname(cmd_line_proj_file_name); + wxArrayString fnames; + fnames.Add(proj_fname); + MacOpenFiles(fnames); } - - // show open file dialog - GdaFrame::GetGdaFrame()->ShowOpenDatasourceDlg(welcome_pos); return true; } -int GdaApp::OnExit(void) -{ - if (checker) delete checker; - return 0; -} - -void GdaApp::OnFatalException() +bool GdaApp::OnCmdLineParsed(wxCmdLineParser& parser) { - wxMessageBox(_("GeoDa has run into a problem and will close.")); + if ( parser.GetParamCount() > 0) { + cmd_line_proj_file_name = parser.GetParam(0); + } + return true; } - -const wxCmdLineEntryDesc GdaApp::globalCmdLineDesc [] = +void GdaApp::MacOpenFiles(const wxArrayString& fileNames) { - { wxCMD_LINE_SWITCH, "h", "help", - "displays help on the command line parameters", - wxCMD_LINE_VAL_NONE, wxCMD_LINE_OPTION_HELP }, - { wxCMD_LINE_PARAM, NULL, NULL, "project file", - wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL }, - { wxCMD_LINE_NONE } -}; + wxLogMessage("MacOpenFiles"); + wxLogMessage(fileNames[0]); + int sz=fileNames.GetCount(); -void GdaApp::OnInitCmdLine(wxCmdLineParser& parser) -{ - parser.SetDesc (GdaApp::globalCmdLineDesc); - parser.SetSwitchChars (wxT("-")); + if (sz > 0) { + wxWindowList::compatibility_iterator node = wxTopLevelWindows.GetFirst(); + while (node) { + wxWindow* win = node->GetData(); + if (ConnectDatasourceDlg* w = dynamic_cast(win)) { + w->EndModal(wxID_CANCEL); + } + node = node->GetNext(); + } + + GdaFrame::GetGdaFrame()->OpenProject(fileNames[0]); + } } -bool GdaApp::OnCmdLineParsed(wxCmdLineParser& parser) +int GdaApp::OnExit(void) { - for (int i=0; i 0) { - cmd_line_proj_file_name = parser.GetParam(0); - } - return true; + return 0; } -void GdaApp::MacOpenFiles(const wxArrayString& fileNames) +void GdaApp::OnFatalException() { - wxString msg; - int sz=fileNames.GetCount(); - msg << "Request to open " << sz << " file(s):"; - for (int i=0; i 0) - GdaFrame::GetGdaFrame()->OpenProject(fileNames[0]); + wxMessageBox(_("GeoDa has run into a problem and will close.")); } std::vector GdaFrame::htmlMenuItems; +GdaFrame* GdaFrame::gda_frame = 0; +bool GdaFrame::projectOpen = false; +Project* GdaFrame::project_p = 0; +std::list GdaFrame::toolbar_list(0); void GdaFrame::UpdateToolbarAndMenus() { // This method is called when no particular window is currently active. // In this case, the close menu item should be disabled. - - GeneralWxUtils::EnableMenuItem(GetMenuBar(), "File", wxID_CLOSE, false); - - Project* p = GetProject(); + // some change + + GeneralWxUtils::EnableMenuItem(GetMenuBar(), _("File"), wxID_CLOSE, false); + Project* p = GetProject(); bool proj_open = (p != 0); bool shp_proj = proj_open && !p->IsTableOnlyProject(); bool table_proj = proj_open && p->IsTableOnlyProject(); @@ -518,9 +487,10 @@ void GdaFrame::UpdateToolbarAndMenus() EnableTool(XRCID("ID_NEW_PROJECT"), !proj_open); EnableTool(XRCID("ID_OPEN_PROJECT"), !proj_open); EnableTool(XRCID("ID_CLOSE_PROJECT"), proj_open); - GeneralWxUtils::EnableMenuItem(mb, "File", XRCID("ID_NEW_PROJECT"), !proj_open); - GeneralWxUtils::EnableMenuItem(mb, "File", XRCID("ID_OPEN_PROJECT"), !proj_open); - GeneralWxUtils::EnableMenuItem(mb, "File", XRCID("ID_CLOSE_PROJECT"), proj_open); + + GeneralWxUtils::EnableMenuItem(mb, _("File"), XRCID("ID_NEW_PROJECT"), !proj_open); + GeneralWxUtils::EnableMenuItem(mb, _("File"), XRCID("ID_OPEN_PROJECT"), !proj_open); + GeneralWxUtils::EnableMenuItem(mb, _("File"), XRCID("ID_CLOSE_PROJECT"), proj_open); if (!proj_open) { // Disable only if project not open. Otherwise, leave changing @@ -544,13 +514,12 @@ void GdaFrame::UpdateToolbarAndMenus() EnableTool(XRCID("ID_TOOLS_WEIGHTS_CREATE"), proj_open); EnableTool(XRCID("ID_CONNECTIVITY_HIST_VIEW"), proj_open); EnableTool(XRCID("ID_CONNECTIVITY_MAP_VIEW"), proj_open); - - GeneralWxUtils::EnableMenuItem(mb, "Tools", XRCID("ID_TOOLS_WEIGHTS_MANAGER"), proj_open); - GeneralWxUtils::EnableMenuItem(mb, "Tools", XRCID("ID_TOOLS_WEIGHTS_CREATE"), proj_open); - GeneralWxUtils::EnableMenuItem(mb, "Tools", XRCID("ID_CONNECTIVITY_HIST_VIEW"), proj_open); - GeneralWxUtils::EnableMenuItem(mb, "Tools", XRCID("ID_CONNECTIVITY_MAP_VIEW"), proj_open); - GeneralWxUtils::EnableMenuItem(mb, "Tools", XRCID("ID_POINTS_FROM_TABLE"), table_proj); - + + GeneralWxUtils::EnableMenuItem(mb, _("Tools"), XRCID("ID_TOOLS_WEIGHTS_MANAGER"), proj_open); + GeneralWxUtils::EnableMenuItem(mb, _("Tools"), XRCID("ID_TOOLS_WEIGHTS_CREATE"), proj_open); + GeneralWxUtils::EnableMenuItem(mb, _("Tools"), XRCID("ID_CONNECTIVITY_HIST_VIEW"), proj_open); + GeneralWxUtils::EnableMenuItem(mb, _("Tools"), XRCID("ID_CONNECTIVITY_MAP_VIEW"), proj_open); + GeneralWxUtils::EnableMenuItem(mb, _("Tools"), XRCID("ID_POINTS_FROM_TABLE"), proj_open); GeneralWxUtils::EnableMenuItem(mb, XRCID("ID_COPY_IMAGE_TO_CLIPBOARD"), false); GeneralWxUtils::EnableMenuItem(mb, XRCID("ID_SELECTION_MODE"), proj_open); @@ -562,9 +531,9 @@ void GdaFrame::UpdateToolbarAndMenus() GeneralWxUtils::EnableMenuItem(mb, XRCID("ID_FIXED_ASPECT_RATIO_MODE"), proj_open); GeneralWxUtils::EnableMenuItem(mb, XRCID("ID_ADJUST_AXIS_PRECISION"), proj_open); GeneralWxUtils::EnableMenuItem(mb, XRCID("ID_ZOOM_MODE"), proj_open); - GeneralWxUtils::EnableMenuItem(mb, XRCID("ID_PAN_MODE"), proj_open); - - GeneralWxUtils::EnableMenuAll(mb, "Explore", proj_open); + GeneralWxUtils::EnableMenuItem(mb, XRCID("ID_PAN_MODE"), proj_open); + GeneralWxUtils::EnableMenuAll(mb, _("Explore"), proj_open); + EnableTool(XRCID("IDM_BOX"), proj_open); GeneralWxUtils::EnableMenuItem(mb, XRCID("IDM_BOX"), proj_open); @@ -593,8 +562,15 @@ void GdaFrame::UpdateToolbarAndMenus() GeneralWxUtils::EnableMenuItem(mb, XRCID("ID_CLUSTERING_MENU"), proj_open); GeneralWxUtils::EnableMenuItem(mb, XRCID("ID_TOOLS_DATA_PCA"), shp_proj); GeneralWxUtils::EnableMenuItem(mb, XRCID("ID_TOOLS_DATA_KMEANS"), proj_open); + GeneralWxUtils::EnableMenuItem(mb, XRCID("ID_TOOLS_DATA_KMEDIANS"), proj_open); + GeneralWxUtils::EnableMenuItem(mb, XRCID("ID_TOOLS_DATA_KMEDOIDS"), proj_open); GeneralWxUtils::EnableMenuItem(mb,XRCID("ID_TOOLS_DATA_HCLUSTER"), proj_open); - + GeneralWxUtils::EnableMenuItem(mb,XRCID("ID_TOOLS_DATA_HDBSCAN"), proj_open); + GeneralWxUtils::EnableMenuItem(mb, XRCID("ID_TOOLS_DATA_MAXP"), proj_open); + GeneralWxUtils::EnableMenuItem(mb, XRCID("ID_TOOLS_DATA_SKATER"), proj_open); + GeneralWxUtils::EnableMenuItem(mb, XRCID("ID_TOOLS_DATA_SPECTRAL"), proj_open); + GeneralWxUtils::EnableMenuItem(mb, XRCID("ID_TOOLS_DATA_REDCAP"), proj_open); + GeneralWxUtils::EnableMenuItem(mb, XRCID("ID_TOOLS_DATA_MDS"), proj_open); EnableTool(XRCID("IDM_3DP"), proj_open); GeneralWxUtils::EnableMenuItem(mb, XRCID("IDM_3DP"), proj_open); @@ -603,13 +579,9 @@ void GdaFrame::UpdateToolbarAndMenus() GeneralWxUtils::EnableMenuItem(mb, XRCID("IDM_LINE_CHART"), proj_open); EnableTool(XRCID("IDM_NEW_TABLE"), proj_open); - GeneralWxUtils::EnableMenuAll(mb, "Table", proj_open); + GeneralWxUtils::EnableMenuAll(mb, _("Table"), proj_open); GeneralWxUtils::EnableMenuItem(mb, XRCID("ID_SHOW_TIME_CHOOSER"),time_variant); - // Temporarily removed for 1.6 release work - // - // - // GeneralWxUtils::EnableMenuItem(mb, XRCID("ID_CALCULATOR"), true); EnableTool(XRCID("ID_SHOW_TIME_CHOOSER"), time_variant); GeneralWxUtils::EnableMenuItem(mb, XRCID("ID_SHOW_DATA_MOVIE"), proj_open); @@ -637,12 +609,20 @@ void GdaFrame::UpdateToolbarAndMenus() GeneralWxUtils::EnableMenuItem(mb, XRCID("IDM_UNI_LISA"), shp_proj); EnableTool(XRCID("IDM_MULTI_LISA"), shp_proj); GeneralWxUtils::EnableMenuItem(mb, XRCID("IDM_MULTI_LISA"), shp_proj); + EnableTool(XRCID("IDM_DIFF_LISA"), shp_proj); + GeneralWxUtils::EnableMenuItem(mb, XRCID("IDM_DIFF_LISA"), shp_proj); EnableTool(XRCID("IDM_LISA_EBRATE"), shp_proj); GeneralWxUtils::EnableMenuItem(mb, XRCID("IDM_LISA_EBRATE"), shp_proj); EnableTool(XRCID("IDM_LOCAL_G"), shp_proj); GeneralWxUtils::EnableMenuItem(mb, XRCID("IDM_LOCAL_G"), shp_proj); EnableTool(XRCID("IDM_LOCAL_G_STAR"), shp_proj); GeneralWxUtils::EnableMenuItem(mb, XRCID("IDM_LOCAL_G_STAR"), shp_proj); + EnableTool(XRCID("IDM_LOCAL_JOINT_COUNT"), shp_proj); + GeneralWxUtils::EnableMenuItem(mb, XRCID("IDM_LOCAL_JOINT_COUNT"), shp_proj); + EnableTool(XRCID("IDM_BIV_LJC"), shp_proj); + GeneralWxUtils::EnableMenuItem(mb, XRCID("IDM_BIV_LJC"), shp_proj); + EnableTool(XRCID("IDM_MUL_LJC"), shp_proj); + GeneralWxUtils::EnableMenuItem(mb, XRCID("IDM_MUL_LJC"), shp_proj); EnableTool(XRCID("IDM_UNI_LOCAL_GEARY"), shp_proj); @@ -653,7 +633,7 @@ void GdaFrame::UpdateToolbarAndMenus() EnableTool(XRCID("IDM_CORRELOGRAM"), shp_proj); GeneralWxUtils::EnableMenuItem(mb, XRCID("IDM_CORRELOGRAM"), shp_proj); - GeneralWxUtils::EnableMenuAll(mb, "Map", shp_proj); + GeneralWxUtils::EnableMenuAll(mb, _("Map"), shp_proj); EnableTool(XRCID("ID_MAP_CHOICES"), shp_proj); EnableTool(XRCID("ID_DATA_MOVIE"), shp_proj); EnableTool(XRCID("ID_SHOW_CONDITIONAL_MAP_VIEW"), shp_proj); @@ -665,8 +645,31 @@ void GdaFrame::UpdateToolbarAndMenus() //Empty out the Options menu: wxMenu* optMenu=wxXmlResource::Get()->LoadMenu("ID_DEFAULT_MENU_OPTIONS"); - GeneralWxUtils::ReplaceMenu(mb, "Options", optMenu); - + GeneralWxUtils::ReplaceMenu(mb, _("Options"), optMenu); + + //Empty Custom category menu: + wxMenuItem* mi = mb->FindItem(XRCID("ID_OPEN_CUSTOM_BREAKS_SUBMENU")); + wxMenu* sm = mi->GetSubMenu(); + if (sm) { + // clean + wxMenuItemList items = sm->GetMenuItems(); + for (int i=0; iDelete(items[i]); + } + if (project_p) { + vector titles; + CatClassifManager* ccm = project_p->GetCatClassifManager(); + ccm->GetTitles(titles); + + sm->Append(XRCID("ID_NEW_CUSTOM_CAT_CLASSIF_A"), _("Create New Custom"), _("Create new custom categories classification.")); + sm->AppendSeparator(); + + for (size_t j=0; jAppend(GdaConst::ID_CUSTOM_CAT_CLASSIF_CHOICE_A0+j, titles[j]); + } + GdaFrame::GetGdaFrame()->Bind(wxEVT_COMMAND_MENU_SELECTED, &GdaFrame::OnCustomCategoryClick, GdaFrame::GetGdaFrame(), GdaConst::ID_CUSTOM_CAT_CLASSIF_CHOICE_A0, GdaConst::ID_CUSTOM_CAT_CLASSIF_CHOICE_A0 + titles.size()); + } + } } void GdaFrame::SetMenusToDefault() @@ -675,26 +678,20 @@ void GdaFrame::SetMenusToDefault() // in one of File, Tools, Methods, or Help menus. wxMenuBar* mb = GetMenuBar(); if (!mb) return; - //wxMenu* menu = NULL; wxString menuText = wxEmptyString; int menuCnt = mb->GetMenuCount(); for (int i=0; iGetMenu(i); menuText = mb->GetMenuLabelText(i); - if ( (menuText != "File") && - (menuText != "Tools") && - (menuText != "Table") && - (menuText != "Help") ) { + if ( (menuText != _("File")) && + (menuText != _("Tools")) && + (menuText != _("Table")) && + (menuText != _("Help")) ) { GeneralWxUtils::EnableMenuAll(mb, menuText, false); } } } -GdaFrame* GdaFrame::gda_frame = 0; -bool GdaFrame::projectOpen = false; -Project* GdaFrame::project_p = 0; -std::list GdaFrame::toolbar_list(0); - GdaFrame::GdaFrame(const wxString& title, const wxPoint& pos, const wxSize& size, long style) : wxFrame(NULL, -1, title, pos, size, style) @@ -706,7 +703,7 @@ GdaFrame::GdaFrame(const wxString& title, const wxPoint& pos, if (!GetHtmlMenuItems() || htmlMenuItems.size() == 0) { } else { wxMenuBar* mb = GetMenuBar(); - int exp_menu_ind = mb->FindMenu("Explore"); + int exp_menu_ind = mb->FindMenu(_("Explore")); wxMenu* exp_menu = mb->GetMenu(exp_menu_ind); wxMenu* html_menu = new wxMenu(); int base_id = GdaConst::ID_HTML_MENU_ENTRY_CHOICE_0; @@ -729,6 +726,13 @@ GdaFrame::GdaFrame(const wxString& title, const wxPoint& pos, SetMenusToDefault(); UpdateToolbarAndMenus(); SetEncodingCheckmarks(wxFONTENCODING_UTF8); + + CallAfter(&GdaFrame::ShowOpenDatasourceDlg,wxPoint(80, 220),true); + + // check update in a new thread + if (GdaConst::disable_auto_upgrade == false) { + CallAfter(&GdaFrame::CheckUpdate); + } } GdaFrame::~GdaFrame() @@ -746,7 +750,7 @@ void GdaFrame::CheckUpdate() wxLogMessage(version); wxString skip_version; - std::vector items = OGRDataAdapter::GetInstance().GetHistory("no_update_version"); + std::vector items = OGRDataAdapter::GetInstance().GetHistory("no_update_version"); if (items.size()>0) skip_version = items[0]; @@ -756,8 +760,7 @@ void GdaFrame::CheckUpdate() bool showSkip = true; AutoUpdateDlg updateDlg(NULL, showSkip); if (updateDlg.ShowModal() == wxID_NO) { - OGRDataAdapter::GetInstance().AddEntry("no_update_version", - std::string(version.mb_str())); + OGRDataAdapter::GetInstance().AddEntry("no_update_version", version); } } } @@ -816,7 +819,7 @@ void GdaFrame::OnOpenNewTable() if (g) tf = (TableFrame*) g->GetParent()->GetParent(); // wxPanel"); - for(i=0; iout,"\n"); - } - fprintf(p->out,"\n"); - } - if( azArg==0 ) break; - fprintf(p->out,""); - for(i=0; iout,"\n"); - } - fprintf(p->out,"\n"); - break; - } - case MODE_Tcl: { - if( p->cnt++==0 && p->showHeader ){ - for(i=0; iout,azCol[i] ? azCol[i] : ""); - if(iout, "%s", p->separator); - } - fprintf(p->out,"\n"); - } - if( azArg==0 ) break; - for(i=0; iout, azArg[i] ? azArg[i] : p->nullvalue); - if(iout, "%s", p->separator); - } - fprintf(p->out,"\n"); - break; - } - case MODE_Csv: { - if( p->cnt++==0 && p->showHeader ){ - for(i=0; iout,"\n"); - } - if( azArg==0 ) break; - for(i=0; iout,"\n"); - break; - } - case MODE_Insert: { - p->cnt++; - if( azArg==0 ) break; - fprintf(p->out,"INSERT INTO %s VALUES(",p->zDestTable); - for(i=0; i0 ? ",": ""; - if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){ - fprintf(p->out,"%sNULL",zSep); - }else if( aiType && aiType[i]==SQLITE_TEXT ){ - if( zSep[0] ) fprintf(p->out,"%s",zSep); - output_quoted_string(p->out, azArg[i]); - }else if( aiType && (aiType[i]==SQLITE_INTEGER || aiType[i]==SQLITE_FLOAT) ){ - fprintf(p->out,"%s%s",zSep, azArg[i]); - }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){ - const void *pBlob = sqlite3_column_blob(p->pStmt, i); - int nBlob = sqlite3_column_bytes(p->pStmt, i); - if( zSep[0] ) fprintf(p->out,"%s",zSep); - output_hex_blob(p->out, pBlob, nBlob); - }else if( isNumber(azArg[i], 0) ){ - fprintf(p->out,"%s%s",zSep, azArg[i]); - }else{ - if( zSep[0] ) fprintf(p->out,"%s",zSep); - output_quoted_string(p->out, azArg[i]); - } - } - fprintf(p->out,");\n"); - break; - } - } - return 0; -} - -/* -** This is the callback routine that the SQLite library -** invokes for each row of a query result. -*/ -static int callback(void *pArg, int nArg, char **azArg, char **azCol){ - /* since we don't have type info, call the shell_callback with a NULL value */ - return shell_callback(pArg, nArg, azArg, azCol, NULL); -} - -/* -** Set the destination table field of the callback_data structure to -** the name of the table given. Escape any quote characters in the -** table name. -*/ -static void set_table_name(struct callback_data *p, const char *zName){ - int i, n; - int needQuote; - char *z; - - if( p->zDestTable ){ - free(p->zDestTable); - p->zDestTable = 0; - } - if( zName==0 ) return; - needQuote = !isalpha((unsigned char)*zName) && *zName!='_'; - for(i=n=0; zName[i]; i++, n++){ - if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ){ - needQuote = 1; - if( zName[i]=='\'' ) n++; - } - } - if( needQuote ) n += 2; - z = p->zDestTable = malloc( n+1 ); - if( z==0 ){ - fprintf(stderr,"Error: out of memory\n"); - exit(1); - } - n = 0; - if( needQuote ) z[n++] = '\''; - for(i=0; zName[i]; i++){ - z[n++] = zName[i]; - if( zName[i]=='\'' ) z[n++] = '\''; - } - if( needQuote ) z[n++] = '\''; - z[n] = 0; -} - -/* zIn is either a pointer to a NULL-terminated string in memory obtained -** from malloc(), or a NULL pointer. The string pointed to by zAppend is -** added to zIn, and the result returned in memory obtained from malloc(). -** zIn, if it was not NULL, is freed. -** -** If the third argument, quote, is not '\0', then it is used as a -** quote character for zAppend. -*/ -static char *appendText(char *zIn, char const *zAppend, char quote){ - int len; - int i; - int nAppend = strlen30(zAppend); - int nIn = (zIn?strlen30(zIn):0); - - len = nAppend+nIn+1; - if( quote ){ - len += 2; - for(i=0; idb, zSelect, -1, &pSelect, 0); - if( rc!=SQLITE_OK || !pSelect ){ - fprintf(p->out, "/**** ERROR: (%d) %s *****/\n", rc, sqlite3_errmsg(p->db)); - p->nErr++; - return rc; - } - rc = sqlite3_step(pSelect); - nResult = sqlite3_column_count(pSelect); - while( rc==SQLITE_ROW ){ - if( zFirstRow ){ - fprintf(p->out, "%s", zFirstRow); - zFirstRow = 0; - } - z = (const char*)sqlite3_column_text(pSelect, 0); - fprintf(p->out, "%s", z); - for(i=1; iout, ",%s", sqlite3_column_text(pSelect, i)); - } - if( z==0 ) z = ""; - while( z[0] && (z[0]!='-' || z[1]!='-') ) z++; - if( z[0] ){ - fprintf(p->out, "\n;\n"); - }else{ - fprintf(p->out, ";\n"); - } - rc = sqlite3_step(pSelect); - } - rc = sqlite3_finalize(pSelect); - if( rc!=SQLITE_OK ){ - fprintf(p->out, "/**** ERROR: (%d) %s *****/\n", rc, sqlite3_errmsg(p->db)); - p->nErr++; - } - return rc; -} - -/* -** Allocate space and save off current error string. -*/ -static char *save_err_msg( - sqlite3 *db /* Database to query */ -){ - int nErrMsg = 1+strlen30(sqlite3_errmsg(db)); - char *zErrMsg = sqlite3_malloc(nErrMsg); - if( zErrMsg ){ - memcpy(zErrMsg, sqlite3_errmsg(db), nErrMsg); - } - return zErrMsg; -} - -/* -** Display memory stats. -*/ -static int display_stats( - sqlite3 *db, /* Database to query */ - struct callback_data *pArg, /* Pointer to struct callback_data */ - int bReset /* True to reset the stats */ -){ - int iCur; - int iHiwtr; - - if( pArg && pArg->out ){ - - iHiwtr = iCur = -1; - sqlite3_status(SQLITE_STATUS_MEMORY_USED, &iCur, &iHiwtr, bReset); - fprintf(pArg->out, "Memory Used: %d (max %d) bytes\n", iCur, iHiwtr); - iHiwtr = iCur = -1; - sqlite3_status(SQLITE_STATUS_MALLOC_COUNT, &iCur, &iHiwtr, bReset); - fprintf(pArg->out, "Number of Outstanding Allocations: %d (max %d)\n", iCur, iHiwtr); -/* -** Not currently used by the CLI. -** iHiwtr = iCur = -1; -** sqlite3_status(SQLITE_STATUS_PAGECACHE_USED, &iCur, &iHiwtr, bReset); -** fprintf(pArg->out, "Number of Pcache Pages Used: %d (max %d) pages\n", iCur, iHiwtr); -*/ - iHiwtr = iCur = -1; - sqlite3_status(SQLITE_STATUS_PAGECACHE_OVERFLOW, &iCur, &iHiwtr, bReset); - fprintf(pArg->out, "Number of Pcache Overflow Bytes: %d (max %d) bytes\n", iCur, iHiwtr); -/* -** Not currently used by the CLI. -** iHiwtr = iCur = -1; -** sqlite3_status(SQLITE_STATUS_SCRATCH_USED, &iCur, &iHiwtr, bReset); -** fprintf(pArg->out, "Number of Scratch Allocations Used: %d (max %d)\n", iCur, iHiwtr); -*/ - iHiwtr = iCur = -1; - sqlite3_status(SQLITE_STATUS_SCRATCH_OVERFLOW, &iCur, &iHiwtr, bReset); - fprintf(pArg->out, "Number of Scratch Overflow Bytes: %d (max %d) bytes\n", iCur, iHiwtr); - iHiwtr = iCur = -1; - sqlite3_status(SQLITE_STATUS_MALLOC_SIZE, &iCur, &iHiwtr, bReset); - fprintf(pArg->out, "Largest Allocation: %d bytes\n", iHiwtr); - iHiwtr = iCur = -1; - sqlite3_status(SQLITE_STATUS_PAGECACHE_SIZE, &iCur, &iHiwtr, bReset); - fprintf(pArg->out, "Largest Pcache Allocation: %d bytes\n", iHiwtr); - iHiwtr = iCur = -1; - sqlite3_status(SQLITE_STATUS_SCRATCH_SIZE, &iCur, &iHiwtr, bReset); - fprintf(pArg->out, "Largest Scratch Allocation: %d bytes\n", iHiwtr); -#ifdef YYTRACKMAXSTACKDEPTH - iHiwtr = iCur = -1; - sqlite3_status(SQLITE_STATUS_PARSER_STACK, &iCur, &iHiwtr, bReset); - fprintf(pArg->out, "Deepest Parser Stack: %d (max %d)\n", iCur, iHiwtr); -#endif - } - - if( pArg && pArg->out && db ){ - iHiwtr = iCur = -1; - sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED, &iCur, &iHiwtr, bReset); - fprintf(pArg->out, "Lookaside Slots Used: %d (max %d)\n", iCur, iHiwtr); - sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT, &iCur, &iHiwtr, bReset); - fprintf(pArg->out, "Successful lookaside attempts: %d\n", iHiwtr); - sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE, &iCur, &iHiwtr, bReset); - fprintf(pArg->out, "Lookaside failures due to size: %d\n", iHiwtr); - sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL, &iCur, &iHiwtr, bReset); - fprintf(pArg->out, "Lookaside failures due to OOM: %d\n", iHiwtr); - iHiwtr = iCur = -1; - sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset); - fprintf(pArg->out, "Pager Heap Usage: %d bytes\n", iCur); iHiwtr = iCur = -1; - sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1); - fprintf(pArg->out, "Page cache hits: %d\n", iCur); - iHiwtr = iCur = -1; - sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1); - fprintf(pArg->out, "Page cache misses: %d\n", iCur); - iHiwtr = iCur = -1; - sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1); - fprintf(pArg->out, "Page cache writes: %d\n", iCur); - iHiwtr = iCur = -1; - sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset); - fprintf(pArg->out, "Schema Heap Usage: %d bytes\n", iCur); - iHiwtr = iCur = -1; - sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset); - fprintf(pArg->out, "Statement Heap/Lookaside Usage: %d bytes\n", iCur); - } - - if( pArg && pArg->out && db && pArg->pStmt ){ - iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP, bReset); - fprintf(pArg->out, "Fullscan Steps: %d\n", iCur); - iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset); - fprintf(pArg->out, "Sort Operations: %d\n", iCur); - iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX, bReset); - fprintf(pArg->out, "Autoindex Inserts: %d\n", iCur); - } - - return 0; -} - -/* -** Execute a statement or set of statements. Print -** any result rows/columns depending on the current mode -** set via the supplied callback. -** -** This is very similar to SQLite's built-in sqlite3_exec() -** function except it takes a slightly different callback -** and callback data argument. -*/ -static int shell_exec( - sqlite3 *db, /* An open database */ - const char *zSql, /* SQL to be evaluated */ - int (*xCallback)(void*,int,char**,char**,int*), /* Callback function */ - /* (not the same as sqlite3_exec) */ - struct callback_data *pArg, /* Pointer to struct callback_data */ - char **pzErrMsg /* Error msg written here */ -){ - sqlite3_stmt *pStmt = NULL; /* Statement to execute. */ - int rc = SQLITE_OK; /* Return Code */ - int rc2; - const char *zLeftover; /* Tail of unprocessed SQL */ - - if( pzErrMsg ){ - *pzErrMsg = NULL; - } - - while( zSql[0] && (SQLITE_OK == rc) ){ - rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover); - if( SQLITE_OK != rc ){ - if( pzErrMsg ){ - *pzErrMsg = save_err_msg(db); - } - }else{ - if( !pStmt ){ - /* this happens for a comment or white-space */ - zSql = zLeftover; - while( IsSpace(zSql[0]) ) zSql++; - continue; - } - - /* save off the prepared statment handle and reset row count */ - if( pArg ){ - pArg->pStmt = pStmt; - pArg->cnt = 0; - } - - /* echo the sql statement if echo on */ - if( pArg && pArg->echoOn ){ - const char *zStmtSql = sqlite3_sql(pStmt); - fprintf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql); - } - - /* Output TESTCTRL_EXPLAIN text of requested */ - if( pArg && pArg->mode==MODE_Explain ){ - const char *zExplain = 0; - sqlite3_test_control(SQLITE_TESTCTRL_EXPLAIN_STMT, pStmt, &zExplain); - if( zExplain && zExplain[0] ){ - fprintf(pArg->out, "%s", zExplain); - } - } - - /* perform the first step. this will tell us if we - ** have a result set or not and how wide it is. - */ - rc = sqlite3_step(pStmt); - /* if we have a result set... */ - if( SQLITE_ROW == rc ){ - /* if we have a callback... */ - if( xCallback ){ - /* allocate space for col name ptr, value ptr, and type */ - int nCol = sqlite3_column_count(pStmt); - void *pData = sqlite3_malloc(3*nCol*sizeof(const char*) + 1); - if( !pData ){ - rc = SQLITE_NOMEM; - }else{ - char **azCols = (char **)pData; /* Names of result columns */ - char **azVals = &azCols[nCol]; /* Results */ - int *aiTypes = (int *)&azVals[nCol]; /* Result types */ - int i; - assert(sizeof(int) <= sizeof(char *)); - /* save off ptrs to column names */ - for(i=0; istatsOn ){ - display_stats(db, pArg, 0); - } - - /* Finalize the statement just executed. If this fails, save a - ** copy of the error message. Otherwise, set zSql to point to the - ** next statement to execute. */ - rc2 = sqlite3_finalize(pStmt); - if( rc!=SQLITE_NOMEM ) rc = rc2; - if( rc==SQLITE_OK ){ - zSql = zLeftover; - while( IsSpace(zSql[0]) ) zSql++; - }else if( pzErrMsg ){ - *pzErrMsg = save_err_msg(db); - } - - /* clear saved stmt handle */ - if( pArg ){ - pArg->pStmt = NULL; - } - } - } /* end while */ - - return rc; -} - - -/* -** This is a different callback routine used for dumping the database. -** Each row received by this callback consists of a table name, -** the table type ("index" or "table") and SQL to create the table. -** This routine should print text sufficient to recreate the table. -*/ -static int dump_callback(void *pArg, int nArg, char **azArg, char **azCol){ - int rc; - const char *zTable; - const char *zType; - const char *zSql; - const char *zPrepStmt = 0; - struct callback_data *p = (struct callback_data *)pArg; - - UNUSED_PARAMETER(azCol); - if( nArg!=3 ) return 1; - zTable = azArg[0]; - zType = azArg[1]; - zSql = azArg[2]; - - if( strcmp(zTable, "sqlite_sequence")==0 ){ - zPrepStmt = "DELETE FROM sqlite_sequence;\n"; - }else if( strcmp(zTable, "sqlite_stat1")==0 ){ - fprintf(p->out, "ANALYZE sqlite_master;\n"); - }else if( strncmp(zTable, "sqlite_", 7)==0 ){ - return 0; - }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){ - char *zIns; - if( !p->writableSchema ){ - fprintf(p->out, "PRAGMA writable_schema=ON;\n"); - p->writableSchema = 1; - } - zIns = sqlite3_mprintf( - "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)" - "VALUES('table','%q','%q',0,'%q');", - zTable, zTable, zSql); - fprintf(p->out, "%s\n", zIns); - sqlite3_free(zIns); - return 0; - }else{ - fprintf(p->out, "%s;\n", zSql); - } - - if( strcmp(zType, "table")==0 ){ - sqlite3_stmt *pTableInfo = 0; - char *zSelect = 0; - char *zTableInfo = 0; - char *zTmp = 0; - int nRow = 0; - - zTableInfo = appendText(zTableInfo, "PRAGMA table_info(", 0); - zTableInfo = appendText(zTableInfo, zTable, '"'); - zTableInfo = appendText(zTableInfo, ");", 0); - - rc = sqlite3_prepare(p->db, zTableInfo, -1, &pTableInfo, 0); - free(zTableInfo); - if( rc!=SQLITE_OK || !pTableInfo ){ - return 1; - } - - zSelect = appendText(zSelect, "SELECT 'INSERT INTO ' || ", 0); - /* Always quote the table name, even if it appears to be pure ascii, - ** in case it is a keyword. Ex: INSERT INTO "table" ... */ - zTmp = appendText(zTmp, zTable, '"'); - if( zTmp ){ - zSelect = appendText(zSelect, zTmp, '\''); - free(zTmp); - } - zSelect = appendText(zSelect, " || ' VALUES(' || ", 0); - rc = sqlite3_step(pTableInfo); - while( rc==SQLITE_ROW ){ - const char *zText = (const char *)sqlite3_column_text(pTableInfo, 1); - zSelect = appendText(zSelect, "quote(", 0); - zSelect = appendText(zSelect, zText, '"'); - rc = sqlite3_step(pTableInfo); - if( rc==SQLITE_ROW ){ - zSelect = appendText(zSelect, "), ", 0); - }else{ - zSelect = appendText(zSelect, ") ", 0); - } - nRow++; - } - rc = sqlite3_finalize(pTableInfo); - if( rc!=SQLITE_OK || nRow==0 ){ - free(zSelect); - return 1; - } - zSelect = appendText(zSelect, "|| ')' FROM ", 0); - zSelect = appendText(zSelect, zTable, '"'); - - rc = run_table_dump_query(p, zSelect, zPrepStmt); - if( rc==SQLITE_CORRUPT ){ - zSelect = appendText(zSelect, " ORDER BY rowid DESC", 0); - run_table_dump_query(p, zSelect, 0); - } - free(zSelect); - } - return 0; -} - -/* -** Run zQuery. Use dump_callback() as the callback routine so that -** the contents of the query are output as SQL statements. -** -** If we get a SQLITE_CORRUPT error, rerun the query after appending -** "ORDER BY rowid DESC" to the end. -*/ -static int run_schema_dump_query( - struct callback_data *p, - const char *zQuery -){ - int rc; - char *zErr = 0; - rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr); - if( rc==SQLITE_CORRUPT ){ - char *zQ2; - int len = strlen30(zQuery); - fprintf(p->out, "/****** CORRUPTION ERROR *******/\n"); - if( zErr ){ - fprintf(p->out, "/****** %s ******/\n", zErr); - sqlite3_free(zErr); - zErr = 0; - } - zQ2 = malloc( len+100 ); - if( zQ2==0 ) return rc; - sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery); - rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr); - if( rc ){ - fprintf(p->out, "/****** ERROR: %s ******/\n", zErr); - }else{ - rc = SQLITE_CORRUPT; - } - sqlite3_free(zErr); - free(zQ2); - } - return rc; -} - -/* -** Text of a help message -*/ -static char zHelp[] = - ".backup ?DB? FILE Backup DB (default \"main\") to FILE\n" - ".bail ON|OFF Stop after hitting an error. Default OFF\n" - ".databases List names and files of attached databases\n" - ".dump ?TABLE? ... Dump the database in an SQL text format\n" - " If TABLE specified, only dump tables matching\n" - " LIKE pattern TABLE.\n" - ".echo ON|OFF Turn command echo on or off\n" - ".exit Exit this program\n" - ".explain ?ON|OFF? Turn output mode suitable for EXPLAIN on or off.\n" - " With no args, it turns EXPLAIN on.\n" - ".header(s) ON|OFF Turn display of headers on or off\n" - ".help Show this message\n" - ".import FILE TABLE Import data from FILE into TABLE\n" - ".indices ?TABLE? Show names of all indices\n" - " If TABLE specified, only show indices for tables\n" - " matching LIKE pattern TABLE.\n" -#ifdef SQLITE_ENABLE_IOTRACE - ".iotrace FILE Enable I/O diagnostic logging to FILE\n" -#endif -#ifndef SQLITE_OMIT_LOAD_EXTENSION - ".load FILE ?ENTRY? Load an extension library\n" -#endif - ".log FILE|off Turn logging on or off. FILE can be stderr/stdout\n" - ".mode MODE ?TABLE? Set output mode where MODE is one of:\n" - " csv Comma-separated values\n" - " column Left-aligned columns. (See .width)\n" - " html HTML
    D.F. 
    "); - output_html_string(p->out, azCol[i]); - fprintf(p->out,"
    "); - output_html_string(p->out, azArg[i] ? azArg[i] : p->nullvalue); - fprintf(p->out,"
    code\n" - " insert SQL insert statements for TABLE\n" - " line One value per line\n" - " list Values delimited by .separator string\n" - " tabs Tab-separated values\n" - " tcl TCL list elements\n" - ".nullvalue STRING Use STRING in place of NULL values\n" - ".output FILENAME Send output to FILENAME\n" - ".output stdout Send output to the screen\n" - ".print STRING... Print literal STRING\n" - ".prompt MAIN CONTINUE Replace the standard prompts\n" - ".quit Exit this program\n" - ".read FILENAME Execute SQL in FILENAME\n" - ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE\n" - ".schema ?TABLE? Show the CREATE statements\n" - " If TABLE specified, only show tables matching\n" - " LIKE pattern TABLE.\n" - ".separator STRING Change separator used by output mode and .import\n" - ".show Show the current values for various settings\n" - ".stats ON|OFF Turn stats on or off\n" - ".tables ?TABLE? List names of tables\n" - " If TABLE specified, only list tables matching\n" - " LIKE pattern TABLE.\n" - ".timeout MS Try opening locked tables for MS milliseconds\n" - ".trace FILE|off Output each SQL statement as it is run\n" - ".vfsname ?AUX? Print the name of the VFS stack\n" - ".width NUM1 NUM2 ... Set column widths for \"column\" mode\n" -; - -static char zTimerHelp[] = - ".timer ON|OFF Turn the CPU timer measurement on or off\n" -; - -/* Forward reference */ -static int process_input(struct callback_data *p, FILE *in); - -/* -** Make sure the database is open. If it is not, then open it. If -** the database fails to open, print an error message and exit. -*/ -static void open_db(struct callback_data *p){ - if( p->db==0 ){ - sqlite3_initialize(); - sqlite3_open(p->zDbFilename, &p->db); - db = p->db; - if( db && sqlite3_errcode(db)==SQLITE_OK ){ - sqlite3_create_function(db, "shellstatic", 0, SQLITE_UTF8, 0, - shellstaticFunc, 0, 0); - } - if( db==0 || SQLITE_OK!=sqlite3_errcode(db) ){ - fprintf(stderr,"Error: unable to open database \"%s\": %s\n", - p->zDbFilename, sqlite3_errmsg(db)); - exit(1); - } -#ifndef SQLITE_OMIT_LOAD_EXTENSION - sqlite3_enable_load_extension(p->db, 1); -#endif -#ifdef SQLITE_ENABLE_REGEXP - { - extern int sqlite3_add_regexp_func(sqlite3*); - sqlite3_add_regexp_func(db); - } -#endif -#ifdef SQLITE_ENABLE_SPELLFIX - { - extern int sqlite3_spellfix1_register(sqlite3*); - sqlite3_spellfix1_register(db); - } -#endif - } -} - -/* -** Do C-language style dequoting. -** -** \t -> tab -** \n -> newline -** \r -> carriage return -** \NNN -> ascii character NNN in octal -** \\ -> backslash -*/ -static void resolve_backslashes(char *z){ - int i, j; - char c; - for(i=j=0; (c = z[i])!=0; i++, j++){ - if( c=='\\' ){ - c = z[++i]; - if( c=='n' ){ - c = '\n'; - }else if( c=='t' ){ - c = '\t'; - }else if( c=='r' ){ - c = '\r'; - }else if( c>='0' && c<='7' ){ - c -= '0'; - if( z[i+1]>='0' && z[i+1]<='7' ){ - i++; - c = (c<<3) + z[i] - '0'; - if( z[i+1]>='0' && z[i+1]<='7' ){ - i++; - c = (c<<3) + z[i] - '0'; - } - } - } - } - z[j] = c; - } - z[j] = 0; -} - -/* -** Interpret zArg as a boolean value. Return either 0 or 1. -*/ -static int booleanValue(char *zArg){ - int i; - for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){} - if( i>0 && zArg[i]==0 ) return atoi(zArg); - if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){ - return 1; - } - if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){ - return 0; - } - fprintf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n", - zArg); - return 0; -} - -/* -** Close an output file, assuming it is not stderr or stdout -*/ -static void output_file_close(FILE *f){ - if( f && f!=stdout && f!=stderr ) fclose(f); -} - -/* -** Try to open an output file. The names "stdout" and "stderr" are -** recognized and do the right thing. NULL is returned if the output -** filename is "off". -*/ -static FILE *output_file_open(const char *zFile){ - FILE *f; - if( strcmp(zFile,"stdout")==0 ){ - f = stdout; - }else if( strcmp(zFile, "stderr")==0 ){ - f = stderr; - }else if( strcmp(zFile, "off")==0 ){ - f = 0; - }else{ - f = fopen(zFile, "wb"); - if( f==0 ){ - fprintf(stderr, "Error: cannot open \"%s\"\n", zFile); - } - } - return f; -} - -/* -** A routine for handling output from sqlite3_trace(). -*/ -static void sql_trace_callback(void *pArg, const char *z){ - FILE *f = (FILE*)pArg; - if( f ) fprintf(f, "%s\n", z); -} - -/* -** A no-op routine that runs with the ".breakpoint" doc-command. This is -** a useful spot to set a debugger breakpoint. -*/ -static void test_breakpoint(void){ - static int nCall = 0; - nCall++; -} - -/* -** If an input line begins with "." then invoke this routine to -** process that line. -** -** Return 1 on error, 2 to exit, and 0 otherwise. -*/ -static int do_meta_command(char *zLine, struct callback_data *p){ - int i = 1; - int nArg = 0; - int n, c; - int rc = 0; - char *azArg[50]; - - /* Parse the input line into tokens. - */ - while( zLine[i] && nArg=3 && strncmp(azArg[0], "backup", n)==0 ){ - const char *zDestFile = 0; - const char *zDb = 0; - const char *zKey = 0; - sqlite3 *pDest; - sqlite3_backup *pBackup; - int j; - for(j=1; jdb, zDb); - if( pBackup==0 ){ - fprintf(stderr, "Error: %s\n", sqlite3_errmsg(pDest)); - sqlite3_close(pDest); - return 1; - } - while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){} - sqlite3_backup_finish(pBackup); - if( rc==SQLITE_DONE ){ - rc = 0; - }else{ - fprintf(stderr, "Error: %s\n", sqlite3_errmsg(pDest)); - rc = 1; - } - sqlite3_close(pDest); - }else - - if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 && nArg>1 && nArg<3 ){ - bail_on_error = booleanValue(azArg[1]); - }else - - /* The undocumented ".breakpoint" command causes a call to the no-op - ** routine named test_breakpoint(). - */ - if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){ - test_breakpoint(); - }else - - if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 && nArg==1 ){ - struct callback_data data; - char *zErrMsg = 0; - open_db(p); - memcpy(&data, p, sizeof(data)); - data.showHeader = 1; - data.mode = MODE_Column; - data.colWidth[0] = 3; - data.colWidth[1] = 15; - data.colWidth[2] = 58; - data.cnt = 0; - sqlite3_exec(p->db, "PRAGMA database_list; ", callback, &data, &zErrMsg); - if( zErrMsg ){ - fprintf(stderr,"Error: %s\n", zErrMsg); - sqlite3_free(zErrMsg); - rc = 1; - } - }else - - if( c=='d' && strncmp(azArg[0], "dump", n)==0 && nArg<3 ){ - open_db(p); - /* When playing back a "dump", the content might appear in an order - ** which causes immediate foreign key constraints to be violated. - ** So disable foreign-key constraint enforcement to prevent problems. */ - fprintf(p->out, "PRAGMA foreign_keys=OFF;\n"); - fprintf(p->out, "BEGIN TRANSACTION;\n"); - p->writableSchema = 0; - sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0); - p->nErr = 0; - if( nArg==1 ){ - run_schema_dump_query(p, - "SELECT name, type, sql FROM sqlite_master " - "WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'" - ); - run_schema_dump_query(p, - "SELECT name, type, sql FROM sqlite_master " - "WHERE name=='sqlite_sequence'" - ); - run_table_dump_query(p, - "SELECT sql FROM sqlite_master " - "WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0 - ); - }else{ - int i; - for(i=1; iwritableSchema ){ - fprintf(p->out, "PRAGMA writable_schema=OFF;\n"); - p->writableSchema = 0; - } - sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0); - sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0); - fprintf(p->out, p->nErr ? "ROLLBACK; -- due to errors\n" : "COMMIT;\n"); - }else - - if( c=='e' && strncmp(azArg[0], "echo", n)==0 && nArg>1 && nArg<3 ){ - p->echoOn = booleanValue(azArg[1]); - }else - - if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){ - if( nArg>1 && (rc = atoi(azArg[1]))!=0 ) exit(rc); - rc = 2; - }else - - if( c=='e' && strncmp(azArg[0], "explain", n)==0 && nArg<3 ){ - int val = nArg>=2 ? booleanValue(azArg[1]) : 1; - if(val == 1) { - if(!p->explainPrev.valid) { - p->explainPrev.valid = 1; - p->explainPrev.mode = p->mode; - p->explainPrev.showHeader = p->showHeader; - memcpy(p->explainPrev.colWidth,p->colWidth,sizeof(p->colWidth)); - } - /* We could put this code under the !p->explainValid - ** condition so that it does not execute if we are already in - ** explain mode. However, always executing it allows us an easy - ** was to reset to explain mode in case the user previously - ** did an .explain followed by a .width, .mode or .header - ** command. - */ - p->mode = MODE_Explain; - p->showHeader = 1; - memset(p->colWidth,0,ArraySize(p->colWidth)); - p->colWidth[0] = 4; /* addr */ - p->colWidth[1] = 13; /* opcode */ - p->colWidth[2] = 4; /* P1 */ - p->colWidth[3] = 4; /* P2 */ - p->colWidth[4] = 4; /* P3 */ - p->colWidth[5] = 13; /* P4 */ - p->colWidth[6] = 2; /* P5 */ - p->colWidth[7] = 13; /* Comment */ - }else if (p->explainPrev.valid) { - p->explainPrev.valid = 0; - p->mode = p->explainPrev.mode; - p->showHeader = p->explainPrev.showHeader; - memcpy(p->colWidth,p->explainPrev.colWidth,sizeof(p->colWidth)); - } - }else - - if( c=='h' && (strncmp(azArg[0], "header", n)==0 || - strncmp(azArg[0], "headers", n)==0) && nArg>1 && nArg<3 ){ - p->showHeader = booleanValue(azArg[1]); - }else - - if( c=='h' && strncmp(azArg[0], "help", n)==0 ){ - fprintf(stderr,"%s",zHelp); - if( HAS_TIMER ){ - fprintf(stderr,"%s",zTimerHelp); - } - }else - - if( c=='i' && strncmp(azArg[0], "import", n)==0 && nArg==3 ){ - char *zTable = azArg[2]; /* Insert data into this table */ - char *zFile = azArg[1]; /* The file from which to extract data */ - sqlite3_stmt *pStmt = NULL; /* A statement */ - int nCol; /* Number of columns in the table */ - int nByte; /* Number of bytes in an SQL string */ - int i, j; /* Loop counters */ - int nSep; /* Number of bytes in p->separator[] */ - char *zSql; /* An SQL statement */ - char *zLine; /* A single line of input from the file */ - char **azCol; /* zLine[] broken up into columns */ - char *zCommit; /* How to commit changes */ - FILE *in; /* The input file */ - int lineno = 0; /* Line number of input file */ - - open_db(p); - nSep = strlen30(p->separator); - if( nSep==0 ){ - fprintf(stderr, "Error: non-null separator required for import\n"); - return 1; - } - zSql = sqlite3_mprintf("SELECT * FROM %s", zTable); - if( zSql==0 ){ - fprintf(stderr, "Error: out of memory\n"); - return 1; - } - nByte = strlen30(zSql); - rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0); - sqlite3_free(zSql); - if( rc ){ - if (pStmt) sqlite3_finalize(pStmt); - fprintf(stderr,"Error: %s\n", sqlite3_errmsg(db)); - return 1; - } - nCol = sqlite3_column_count(pStmt); - sqlite3_finalize(pStmt); - pStmt = 0; - if( nCol==0 ) return 0; /* no columns, no error */ - zSql = malloc( nByte + 20 + nCol*2 ); - if( zSql==0 ){ - fprintf(stderr, "Error: out of memory\n"); - return 1; - } - sqlite3_snprintf(nByte+20, zSql, "INSERT INTO %s VALUES(?", zTable); - j = strlen30(zSql); - for(i=1; idb, zSql, -1, &pStmt, 0); - free(zSql); - if( rc ){ - fprintf(stderr, "Error: %s\n", sqlite3_errmsg(db)); - if (pStmt) sqlite3_finalize(pStmt); - return 1; - } - in = fopen(zFile, "rb"); - if( in==0 ){ - fprintf(stderr, "Error: cannot open \"%s\"\n", zFile); - sqlite3_finalize(pStmt); - return 1; - } - azCol = malloc( sizeof(azCol[0])*(nCol+1) ); - if( azCol==0 ){ - fprintf(stderr, "Error: out of memory\n"); - fclose(in); - sqlite3_finalize(pStmt); - return 1; - } - sqlite3_exec(p->db, "BEGIN", 0, 0, 0); - zCommit = "COMMIT"; - while( (zLine = local_getline(0, in, 1))!=0 ){ - char *z, c; - int inQuote = 0; - lineno++; - azCol[0] = zLine; - for(i=0, z=zLine; (c = *z)!=0; z++){ - if( c=='"' ) inQuote = !inQuote; - if( c=='\n' ) lineno++; - if( !inQuote && c==p->separator[0] && strncmp(z,p->separator,nSep)==0 ){ - *z = 0; - i++; - if( idb, zCommit, 0, 0, 0); - }else - - if( c=='i' && strncmp(azArg[0], "indices", n)==0 && nArg<3 ){ - struct callback_data data; - char *zErrMsg = 0; - open_db(p); - memcpy(&data, p, sizeof(data)); - data.showHeader = 0; - data.mode = MODE_List; - if( nArg==1 ){ - rc = sqlite3_exec(p->db, - "SELECT name FROM sqlite_master " - "WHERE type='index' AND name NOT LIKE 'sqlite_%' " - "UNION ALL " - "SELECT name FROM sqlite_temp_master " - "WHERE type='index' " - "ORDER BY 1", - callback, &data, &zErrMsg - ); - }else{ - zShellStatic = azArg[1]; - rc = sqlite3_exec(p->db, - "SELECT name FROM sqlite_master " - "WHERE type='index' AND tbl_name LIKE shellstatic() " - "UNION ALL " - "SELECT name FROM sqlite_temp_master " - "WHERE type='index' AND tbl_name LIKE shellstatic() " - "ORDER BY 1", - callback, &data, &zErrMsg - ); - zShellStatic = 0; - } - if( zErrMsg ){ - fprintf(stderr,"Error: %s\n", zErrMsg); - sqlite3_free(zErrMsg); - rc = 1; - }else if( rc != SQLITE_OK ){ - fprintf(stderr,"Error: querying sqlite_master and sqlite_temp_master\n"); - rc = 1; - } - }else - -#ifdef SQLITE_ENABLE_IOTRACE - if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){ - extern void (*sqlite3IoTrace)(const char*, ...); - if( iotrace && iotrace!=stdout ) fclose(iotrace); - iotrace = 0; - if( nArg<2 ){ - sqlite3IoTrace = 0; - }else if( strcmp(azArg[1], "-")==0 ){ - sqlite3IoTrace = iotracePrintf; - iotrace = stdout; - }else{ - iotrace = fopen(azArg[1], "w"); - if( iotrace==0 ){ - fprintf(stderr, "Error: cannot open \"%s\"\n", azArg[1]); - sqlite3IoTrace = 0; - rc = 1; - }else{ - sqlite3IoTrace = iotracePrintf; - } - } - }else -#endif - -#ifndef SQLITE_OMIT_LOAD_EXTENSION - if( c=='l' && strncmp(azArg[0], "load", n)==0 && nArg>=2 ){ - const char *zFile, *zProc; - char *zErrMsg = 0; - zFile = azArg[1]; - zProc = nArg>=3 ? azArg[2] : 0; - open_db(p); - rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg); - if( rc!=SQLITE_OK ){ - fprintf(stderr, "Error: %s\n", zErrMsg); - sqlite3_free(zErrMsg); - rc = 1; - } - }else -#endif - - if( c=='l' && strncmp(azArg[0], "log", n)==0 && nArg>=2 ){ - const char *zFile = azArg[1]; - output_file_close(p->pLog); - p->pLog = output_file_open(zFile); - }else - - if( c=='m' && strncmp(azArg[0], "mode", n)==0 && nArg==2 ){ - int n2 = strlen30(azArg[1]); - if( (n2==4 && strncmp(azArg[1],"line",n2)==0) - || - (n2==5 && strncmp(azArg[1],"lines",n2)==0) ){ - p->mode = MODE_Line; - }else if( (n2==6 && strncmp(azArg[1],"column",n2)==0) - || - (n2==7 && strncmp(azArg[1],"columns",n2)==0) ){ - p->mode = MODE_Column; - }else if( n2==4 && strncmp(azArg[1],"list",n2)==0 ){ - p->mode = MODE_List; - }else if( n2==4 && strncmp(azArg[1],"html",n2)==0 ){ - p->mode = MODE_Html; - }else if( n2==3 && strncmp(azArg[1],"tcl",n2)==0 ){ - p->mode = MODE_Tcl; - sqlite3_snprintf(sizeof(p->separator), p->separator, " "); - }else if( n2==3 && strncmp(azArg[1],"csv",n2)==0 ){ - p->mode = MODE_Csv; - sqlite3_snprintf(sizeof(p->separator), p->separator, ","); - }else if( n2==4 && strncmp(azArg[1],"tabs",n2)==0 ){ - p->mode = MODE_List; - sqlite3_snprintf(sizeof(p->separator), p->separator, "\t"); - }else if( n2==6 && strncmp(azArg[1],"insert",n2)==0 ){ - p->mode = MODE_Insert; - set_table_name(p, "table"); - }else { - fprintf(stderr,"Error: mode should be one of: " - "column csv html insert line list tabs tcl\n"); - rc = 1; - } - }else - - if( c=='m' && strncmp(azArg[0], "mode", n)==0 && nArg==3 ){ - int n2 = strlen30(azArg[1]); - if( n2==6 && strncmp(azArg[1],"insert",n2)==0 ){ - p->mode = MODE_Insert; - set_table_name(p, azArg[2]); - }else { - fprintf(stderr, "Error: invalid arguments: " - " \"%s\". Enter \".help\" for help\n", azArg[2]); - rc = 1; - } - }else - - if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 && nArg==2 ) { - sqlite3_snprintf(sizeof(p->nullvalue), p->nullvalue, - "%.*s", (int)ArraySize(p->nullvalue)-1, azArg[1]); - }else - - if( c=='o' && strncmp(azArg[0], "output", n)==0 && nArg==2 ){ - if( p->outfile[0]=='|' ){ - pclose(p->out); - }else{ - output_file_close(p->out); - } - p->outfile[0] = 0; - if( azArg[1][0]=='|' ){ - p->out = popen(&azArg[1][1], "w"); - if( p->out==0 ){ - fprintf(stderr,"Error: cannot open pipe \"%s\"\n", &azArg[1][1]); - p->out = stdout; - rc = 1; - }else{ - sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", azArg[1]); - } - }else{ - p->out = output_file_open(azArg[1]); - if( p->out==0 ){ - if( strcmp(azArg[1],"off")!=0 ){ - fprintf(stderr,"Error: cannot write to \"%s\"\n", azArg[1]); - } - p->out = stdout; - rc = 1; - } else { - sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", azArg[1]); - } - } - }else - - if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){ - int i; - for(i=1; i1 ) fprintf(p->out, " "); - fprintf(p->out, "%s", azArg[i]); - } - fprintf(p->out, "\n"); - }else - - if( c=='p' && strncmp(azArg[0], "prompt", n)==0 && (nArg==2 || nArg==3)){ - if( nArg >= 2) { - strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1); - } - if( nArg >= 3) { - strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1); - } - }else - - if( c=='q' && strncmp(azArg[0], "quit", n)==0 && nArg==1 ){ - rc = 2; - }else - - if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 && nArg==2 ){ - FILE *alt = fopen(azArg[1], "rb"); - if( alt==0 ){ - fprintf(stderr,"Error: cannot open \"%s\"\n", azArg[1]); - rc = 1; - }else{ - rc = process_input(p, alt); - fclose(alt); - } - }else - - if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 && nArg>1 && nArg<4){ - const char *zSrcFile; - const char *zDb; - sqlite3 *pSrc; - sqlite3_backup *pBackup; - int nTimeout = 0; - - if( nArg==2 ){ - zSrcFile = azArg[1]; - zDb = "main"; - }else{ - zSrcFile = azArg[2]; - zDb = azArg[1]; - } - rc = sqlite3_open(zSrcFile, &pSrc); - if( rc!=SQLITE_OK ){ - fprintf(stderr, "Error: cannot open \"%s\"\n", zSrcFile); - sqlite3_close(pSrc); - return 1; - } - open_db(p); - pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main"); - if( pBackup==0 ){ - fprintf(stderr, "Error: %s\n", sqlite3_errmsg(p->db)); - sqlite3_close(pSrc); - return 1; - } - while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK - || rc==SQLITE_BUSY ){ - if( rc==SQLITE_BUSY ){ - if( nTimeout++ >= 3 ) break; - sqlite3_sleep(100); - } - } - sqlite3_backup_finish(pBackup); - if( rc==SQLITE_DONE ){ - rc = 0; - }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){ - fprintf(stderr, "Error: source database is busy\n"); - rc = 1; - }else{ - fprintf(stderr, "Error: %s\n", sqlite3_errmsg(p->db)); - rc = 1; - } - sqlite3_close(pSrc); - }else - - if( c=='s' && strncmp(azArg[0], "schema", n)==0 && nArg<3 ){ - struct callback_data data; - char *zErrMsg = 0; - open_db(p); - memcpy(&data, p, sizeof(data)); - data.showHeader = 0; - data.mode = MODE_Semi; - if( nArg>1 ){ - int i; - for(i=0; azArg[1][i]; i++) azArg[1][i] = ToLower(azArg[1][i]); - if( strcmp(azArg[1],"sqlite_master")==0 ){ - char *new_argv[2], *new_colv[2]; - new_argv[0] = "CREATE TABLE sqlite_master (\n" - " type text,\n" - " name text,\n" - " tbl_name text,\n" - " rootpage integer,\n" - " sql text\n" - ")"; - new_argv[1] = 0; - new_colv[0] = "sql"; - new_colv[1] = 0; - callback(&data, 1, new_argv, new_colv); - rc = SQLITE_OK; - }else if( strcmp(azArg[1],"sqlite_temp_master")==0 ){ - char *new_argv[2], *new_colv[2]; - new_argv[0] = "CREATE TEMP TABLE sqlite_temp_master (\n" - " type text,\n" - " name text,\n" - " tbl_name text,\n" - " rootpage integer,\n" - " sql text\n" - ")"; - new_argv[1] = 0; - new_colv[0] = "sql"; - new_colv[1] = 0; - callback(&data, 1, new_argv, new_colv); - rc = SQLITE_OK; - }else{ - zShellStatic = azArg[1]; - rc = sqlite3_exec(p->db, - "SELECT sql FROM " - " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x" - " FROM sqlite_master UNION ALL" - " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) " - "WHERE lower(tbl_name) LIKE shellstatic()" - " AND type!='meta' AND sql NOTNULL " - "ORDER BY substr(type,2,1), " - " CASE type WHEN 'view' THEN rowid ELSE name END", - callback, &data, &zErrMsg); - zShellStatic = 0; - } - }else{ - rc = sqlite3_exec(p->db, - "SELECT sql FROM " - " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x" - " FROM sqlite_master UNION ALL" - " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) " - "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%'" - "ORDER BY substr(type,2,1)," - " CASE type WHEN 'view' THEN rowid ELSE name END", - callback, &data, &zErrMsg - ); - } - if( zErrMsg ){ - fprintf(stderr,"Error: %s\n", zErrMsg); - sqlite3_free(zErrMsg); - rc = 1; - }else if( rc != SQLITE_OK ){ - fprintf(stderr,"Error: querying schema information\n"); - rc = 1; - }else{ - rc = 0; - } - }else - - if( c=='s' && strncmp(azArg[0], "separator", n)==0 && nArg==2 ){ - sqlite3_snprintf(sizeof(p->separator), p->separator, - "%.*s", (int)sizeof(p->separator)-1, azArg[1]); - }else - - if( c=='s' && strncmp(azArg[0], "show", n)==0 && nArg==1 ){ - int i; - fprintf(p->out,"%9.9s: %s\n","echo", p->echoOn ? "on" : "off"); - fprintf(p->out,"%9.9s: %s\n","explain", p->explainPrev.valid ? "on" :"off"); - fprintf(p->out,"%9.9s: %s\n","headers", p->showHeader ? "on" : "off"); - fprintf(p->out,"%9.9s: %s\n","mode", modeDescr[p->mode]); - fprintf(p->out,"%9.9s: ", "nullvalue"); - output_c_string(p->out, p->nullvalue); - fprintf(p->out, "\n"); - fprintf(p->out,"%9.9s: %s\n","output", - strlen30(p->outfile) ? p->outfile : "stdout"); - fprintf(p->out,"%9.9s: ", "separator"); - output_c_string(p->out, p->separator); - fprintf(p->out, "\n"); - fprintf(p->out,"%9.9s: %s\n","stats", p->statsOn ? "on" : "off"); - fprintf(p->out,"%9.9s: ","width"); - for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) { - fprintf(p->out,"%d ",p->colWidth[i]); - } - fprintf(p->out,"\n"); - }else - - if( c=='s' && strncmp(azArg[0], "stats", n)==0 && nArg>1 && nArg<3 ){ - p->statsOn = booleanValue(azArg[1]); - }else - - if( c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0 && nArg<3 ){ - sqlite3_stmt *pStmt; - char **azResult; - int nRow, nAlloc; - char *zSql = 0; - int ii; - open_db(p); - rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0); - if( rc ) return rc; - zSql = sqlite3_mprintf( - "SELECT name FROM sqlite_master" - " WHERE type IN ('table','view')" - " AND name NOT LIKE 'sqlite_%%'" - " AND name LIKE ?1"); - while( sqlite3_step(pStmt)==SQLITE_ROW ){ - const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1); - if( zDbName==0 || strcmp(zDbName,"main")==0 ) continue; - if( strcmp(zDbName,"temp")==0 ){ - zSql = sqlite3_mprintf( - "%z UNION ALL " - "SELECT 'temp.' || name FROM sqlite_temp_master" - " WHERE type IN ('table','view')" - " AND name NOT LIKE 'sqlite_%%'" - " AND name LIKE ?1", zSql); - }else{ - zSql = sqlite3_mprintf( - "%z UNION ALL " - "SELECT '%q.' || name FROM \"%w\".sqlite_master" - " WHERE type IN ('table','view')" - " AND name NOT LIKE 'sqlite_%%'" - " AND name LIKE ?1", zSql, zDbName, zDbName); - } - } - sqlite3_finalize(pStmt); - zSql = sqlite3_mprintf("%z ORDER BY 1", zSql); - rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); - sqlite3_free(zSql); - if( rc ) return rc; - nRow = nAlloc = 0; - azResult = 0; - if( nArg>1 ){ - sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT); - }else{ - sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC); - } - while( sqlite3_step(pStmt)==SQLITE_ROW ){ - if( nRow>=nAlloc ){ - char **azNew; - int n = nAlloc*2 + 10; - azNew = sqlite3_realloc(azResult, sizeof(azResult[0])*n); - if( azNew==0 ){ - fprintf(stderr, "Error: out of memory\n"); - break; - } - nAlloc = n; - azResult = azNew; - } - azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0)); - if( azResult[nRow] ) nRow++; - } - sqlite3_finalize(pStmt); - if( nRow>0 ){ - int len, maxlen = 0; - int i, j; - int nPrintCol, nPrintRow; - for(i=0; imaxlen ) maxlen = len; - } - nPrintCol = 80/(maxlen+2); - if( nPrintCol<1 ) nPrintCol = 1; - nPrintRow = (nRow + nPrintCol - 1)/nPrintCol; - for(i=0; i=8 && strncmp(azArg[0], "testctrl", n)==0 && nArg>=2 ){ - static const struct { - const char *zCtrlName; /* Name of a test-control option */ - int ctrlCode; /* Integer code for that option */ - } aCtrl[] = { - { "prng_save", SQLITE_TESTCTRL_PRNG_SAVE }, - { "prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE }, - { "prng_reset", SQLITE_TESTCTRL_PRNG_RESET }, - { "bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST }, - { "fault_install", SQLITE_TESTCTRL_FAULT_INSTALL }, - { "benign_malloc_hooks", SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS }, - { "pending_byte", SQLITE_TESTCTRL_PENDING_BYTE }, - { "assert", SQLITE_TESTCTRL_ASSERT }, - { "always", SQLITE_TESTCTRL_ALWAYS }, - { "reserve", SQLITE_TESTCTRL_RESERVE }, - { "optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS }, - { "iskeyword", SQLITE_TESTCTRL_ISKEYWORD }, - { "scratchmalloc", SQLITE_TESTCTRL_SCRATCHMALLOC }, - }; - int testctrl = -1; - int rc = 0; - int i, n; - open_db(p); - - /* convert testctrl text option to value. allow any unique prefix - ** of the option name, or a numerical value. */ - n = strlen30(azArg[1]); - for(i=0; i<(int)(sizeof(aCtrl)/sizeof(aCtrl[0])); i++){ - if( strncmp(azArg[1], aCtrl[i].zCtrlName, n)==0 ){ - if( testctrl<0 ){ - testctrl = aCtrl[i].ctrlCode; - }else{ - fprintf(stderr, "ambiguous option name: \"%s\"\n", azArg[1]); - testctrl = -1; - break; - } - } - } - if( testctrl<0 ) testctrl = atoi(azArg[1]); - if( (testctrlSQLITE_TESTCTRL_LAST) ){ - fprintf(stderr,"Error: invalid testctrl option: %s\n", azArg[1]); - }else{ - switch(testctrl){ - - /* sqlite3_test_control(int, db, int) */ - case SQLITE_TESTCTRL_OPTIMIZATIONS: - case SQLITE_TESTCTRL_RESERVE: - if( nArg==3 ){ - int opt = (int)strtol(azArg[2], 0, 0); - rc = sqlite3_test_control(testctrl, p->db, opt); - printf("%d (0x%08x)\n", rc, rc); - } else { - fprintf(stderr,"Error: testctrl %s takes a single int option\n", - azArg[1]); - } - break; - - /* sqlite3_test_control(int) */ - case SQLITE_TESTCTRL_PRNG_SAVE: - case SQLITE_TESTCTRL_PRNG_RESTORE: - case SQLITE_TESTCTRL_PRNG_RESET: - if( nArg==2 ){ - rc = sqlite3_test_control(testctrl); - printf("%d (0x%08x)\n", rc, rc); - } else { - fprintf(stderr,"Error: testctrl %s takes no options\n", azArg[1]); - } - break; - - /* sqlite3_test_control(int, uint) */ - case SQLITE_TESTCTRL_PENDING_BYTE: - if( nArg==3 ){ - unsigned int opt = (unsigned int)atoi(azArg[2]); - rc = sqlite3_test_control(testctrl, opt); - printf("%d (0x%08x)\n", rc, rc); - } else { - fprintf(stderr,"Error: testctrl %s takes a single unsigned" - " int option\n", azArg[1]); - } - break; - - /* sqlite3_test_control(int, int) */ - case SQLITE_TESTCTRL_ASSERT: - case SQLITE_TESTCTRL_ALWAYS: - if( nArg==3 ){ - int opt = atoi(azArg[2]); - rc = sqlite3_test_control(testctrl, opt); - printf("%d (0x%08x)\n", rc, rc); - } else { - fprintf(stderr,"Error: testctrl %s takes a single int option\n", - azArg[1]); - } - break; - - /* sqlite3_test_control(int, char *) */ -#ifdef SQLITE_N_KEYWORD - case SQLITE_TESTCTRL_ISKEYWORD: - if( nArg==3 ){ - const char *opt = azArg[2]; - rc = sqlite3_test_control(testctrl, opt); - printf("%d (0x%08x)\n", rc, rc); - } else { - fprintf(stderr,"Error: testctrl %s takes a single char * option\n", - azArg[1]); - } - break; -#endif - - case SQLITE_TESTCTRL_BITVEC_TEST: - case SQLITE_TESTCTRL_FAULT_INSTALL: - case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: - case SQLITE_TESTCTRL_SCRATCHMALLOC: - default: - fprintf(stderr,"Error: CLI support for testctrl %s not implemented\n", - azArg[1]); - break; - } - } - }else - - if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 && nArg==2 ){ - open_db(p); - sqlite3_busy_timeout(p->db, atoi(azArg[1])); - }else - - if( HAS_TIMER && c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 - && nArg==2 - ){ - enableTimer = booleanValue(azArg[1]); - }else - - if( c=='t' && strncmp(azArg[0], "trace", n)==0 && nArg>1 ){ - open_db(p); - output_file_close(p->traceOut); - p->traceOut = output_file_open(azArg[1]); -#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) - if( p->traceOut==0 ){ - sqlite3_trace(p->db, 0, 0); - }else{ - sqlite3_trace(p->db, sql_trace_callback, p->traceOut); - } -#endif - }else - - if( c=='v' && strncmp(azArg[0], "version", n)==0 ){ - printf("SQLite %s %s\n" /*extra-version-info*/, - sqlite3_libversion(), sqlite3_sourceid()); - }else - - if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){ - const char *zDbName = nArg==2 ? azArg[1] : "main"; - char *zVfsName = 0; - if( p->db ){ - sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName); - if( zVfsName ){ - printf("%s\n", zVfsName); - sqlite3_free(zVfsName); - } - } - }else - -#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE) - if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){ - extern int sqlite3WhereTrace; - sqlite3WhereTrace = atoi(azArg[1]); - }else -#endif - - if( c=='w' && strncmp(azArg[0], "width", n)==0 && nArg>1 ){ - int j; - assert( nArg<=ArraySize(azArg) ); - for(j=1; jcolWidth); j++){ - p->colWidth[j-1] = atoi(azArg[j]); - } - }else - - { - fprintf(stderr, "Error: unknown command or invalid arguments: " - " \"%s\". Enter \".help\" for help\n", azArg[0]); - rc = 1; - } - - return rc; -} - -/* -** Return TRUE if a semicolon occurs anywhere in the first N characters -** of string z[]. -*/ -static int _contains_semicolon(const char *z, int N){ - int i; - for(i=0; iout); - free(zLine); - zLine = one_input_line(zSql, in); - if( zLine==0 ){ - /* End of input */ - if( stdin_is_interactive ) printf("\n"); - break; - } - if( seenInterrupt ){ - if( in!=0 ) break; - seenInterrupt = 0; - } - lineno++; - if( (zSql==0 || zSql[0]==0) && _all_whitespace(zLine) ) continue; - if( zLine && zLine[0]=='.' && nSql==0 ){ - if( p->echoOn ) printf("%s\n", zLine); - rc = do_meta_command(zLine, p); - if( rc==2 ){ /* exit requested */ - break; - }else if( rc ){ - errCnt++; - } - continue; - } - if( _is_command_terminator(zLine) && _is_complete(zSql, nSql) ){ - memcpy(zLine,";",2); - } - nSqlPrior = nSql; - if( zSql==0 ){ - int i; - for(i=0; zLine[i] && IsSpace(zLine[i]); i++){} - if( zLine[i]!=0 ){ - nSql = strlen30(zLine); - zSql = malloc( nSql+3 ); - if( zSql==0 ){ - fprintf(stderr, "Error: out of memory\n"); - exit(1); - } - memcpy(zSql, zLine, nSql+1); - startline = lineno; - } - }else{ - int len = strlen30(zLine); - zSql = realloc( zSql, nSql + len + 4 ); - if( zSql==0 ){ - fprintf(stderr,"Error: out of memory\n"); - exit(1); - } - zSql[nSql++] = '\n'; - memcpy(&zSql[nSql], zLine, len+1); - nSql += len; - } - if( zSql && _contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior) - && sqlite3_complete(zSql) ){ - p->cnt = 0; - open_db(p); - BEGIN_TIMER; - rc = shell_exec(p->db, zSql, shell_callback, p, &zErrMsg); - END_TIMER; - if( rc || zErrMsg ){ - char zPrefix[100]; - if( in!=0 || !stdin_is_interactive ){ - sqlite3_snprintf(sizeof(zPrefix), zPrefix, - "Error: near line %d:", startline); - }else{ - sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:"); - } - if( zErrMsg!=0 ){ - fprintf(stderr, "%s %s\n", zPrefix, zErrMsg); - sqlite3_free(zErrMsg); - zErrMsg = 0; - }else{ - fprintf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db)); - } - errCnt++; - } - free(zSql); - zSql = 0; - nSql = 0; - } - } - if( zSql ){ - if( !_all_whitespace(zSql) ){ - fprintf(stderr, "Error: incomplete SQL: %s\n", zSql); - } - free(zSql); - } - free(zLine); - return errCnt>0; -} - -/* -** Return a pathname which is the user's home directory. A -** 0 return indicates an error of some kind. -*/ -static char *find_home_dir(void){ - static char *home_dir = NULL; - if( home_dir ) return home_dir; - -#if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) && !defined(__RTP__) && !defined(_WRS_KERNEL) - { - struct passwd *pwent; - uid_t uid = getuid(); - if( (pwent=getpwuid(uid)) != NULL) { - home_dir = pwent->pw_dir; - } - } -#endif - -#if defined(_WIN32_WCE) - /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv() - */ - home_dir = "/"; -#else - -#if defined(_WIN32) || defined(WIN32) - if (!home_dir) { - home_dir = getenv("USERPROFILE"); - } -#endif - - if (!home_dir) { - home_dir = getenv("HOME"); - } - -#if defined(_WIN32) || defined(WIN32) - if (!home_dir) { - char *zDrive, *zPath; - int n; - zDrive = getenv("HOMEDRIVE"); - zPath = getenv("HOMEPATH"); - if( zDrive && zPath ){ - n = strlen30(zDrive) + strlen30(zPath) + 1; - home_dir = malloc( n ); - if( home_dir==0 ) return 0; - sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath); - return home_dir; - } - home_dir = "c:\\"; - } -#endif - -#endif /* !_WIN32_WCE */ - - if( home_dir ){ - int n = strlen30(home_dir) + 1; - char *z = malloc( n ); - if( z ) memcpy(z, home_dir, n); - home_dir = z; - } - - return home_dir; -} - -/* -** Read input from the file given by sqliterc_override. Or if that -** parameter is NULL, take input from ~/.sqliterc -** -** Returns the number of errors. -*/ -static int process_sqliterc( - struct callback_data *p, /* Configuration data */ - const char *sqliterc_override /* Name of config file. NULL to use default */ -){ - char *home_dir = NULL; - const char *sqliterc = sqliterc_override; - char *zBuf = 0; - FILE *in = NULL; - int rc = 0; - - if (sqliterc == NULL) { - home_dir = find_home_dir(); - if( home_dir==0 ){ -#if !defined(__RTP__) && !defined(_WRS_KERNEL) - fprintf(stderr,"%s: Error: cannot locate your home directory\n", Argv0); -#endif - return 1; - } - sqlite3_initialize(); - zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir); - sqliterc = zBuf; - } - in = fopen(sqliterc,"rb"); - if( in ){ - if( stdin_is_interactive ){ - fprintf(stderr,"-- Loading resources from %s\n",sqliterc); - } - rc = process_input(p,in); - fclose(in); - } - sqlite3_free(zBuf); - return rc; -} - -/* -** Show available command line options -*/ -static const char zOptions[] = - " -bail stop after hitting an error\n" - " -batch force batch I/O\n" - " -column set output mode to 'column'\n" - " -cmd COMMAND run \"COMMAND\" before reading stdin\n" - " -csv set output mode to 'csv'\n" - " -echo print commands before execution\n" - " -init FILENAME read/process named file\n" - " -[no]header turn headers on or off\n" -#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5) - " -heap SIZE Size of heap for memsys3 or memsys5\n" -#endif - " -help show this message\n" - " -html set output mode to HTML\n" - " -interactive force interactive I/O\n" - " -line set output mode to 'line'\n" - " -list set output mode to 'list'\n" -#ifdef SQLITE_ENABLE_MULTIPLEX - " -multiplex enable the multiplexor VFS\n" -#endif - " -nullvalue TEXT set text string for NULL values. Default ''\n" - " -separator SEP set output field separator. Default: '|'\n" - " -stats print memory stats before each finalize\n" - " -version show SQLite version\n" - " -vfs NAME use NAME as the default VFS\n" -#ifdef SQLITE_ENABLE_VFSTRACE - " -vfstrace enable tracing of all VFS calls\n" -#endif -; -static void usage(int showDetail){ - fprintf(stderr, - "Usage: %s [OPTIONS] FILENAME [SQL]\n" - "FILENAME is the name of an SQLite database. A new database is created\n" - "if the file does not previously exist.\n", Argv0); - if( showDetail ){ - fprintf(stderr, "OPTIONS include:\n%s", zOptions); - }else{ - fprintf(stderr, "Use the -help option for additional information\n"); - } - exit(1); -} - -/* -** Initialize the state information in data -*/ -static void main_init(struct callback_data *data) { - memset(data, 0, sizeof(*data)); - data->mode = MODE_List; - memcpy(data->separator,"|", 2); - data->showHeader = 0; - sqlite3_config(SQLITE_CONFIG_URI, 1); - sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data); - sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> "); - sqlite3_snprintf(sizeof(continuePrompt), continuePrompt," ...> "); - sqlite3_config(SQLITE_CONFIG_SINGLETHREAD); -} - -/* -** Get the argument to an --option. Throw an error and die if no argument -** is available. -*/ -static char *cmdline_option_value(int argc, char **argv, int i){ - if( i==argc ){ - fprintf(stderr, "%s: Error: missing argument to %s\n", - argv[0], argv[argc-1]); - exit(1); - } - return argv[i]; -} - -int main(int argc, char **argv){ - char *zErrMsg = 0; - struct callback_data data; - const char *zInitFile = 0; - char *zFirstCmd = 0; - int i; - int rc = 0; - - if( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)!=0 ){ - fprintf(stderr, "SQLite header and source version mismatch\n%s\n%s\n", - sqlite3_sourceid(), SQLITE_SOURCE_ID); - exit(1); - } - Argv0 = argv[0]; - main_init(&data); - stdin_is_interactive = isatty(0); - - /* Make sure we have a valid signal handler early, before anything - ** else is done. - */ -#ifdef SIGINT - signal(SIGINT, interrupt_handler); -#endif - - /* Do an initial pass through the command-line argument to locate - ** the name of the database file, the name of the initialization file, - ** the size of the alternative malloc heap, - ** and the first command to execute. - */ - for(i=1; i0x7fff0000 ) szHeap = 0x7fff0000; - sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64); -#endif -#ifdef SQLITE_ENABLE_VFSTRACE - }else if( strcmp(z,"-vfstrace")==0 ){ - extern int vfstrace_register( - const char *zTraceName, - const char *zOldVfsName, - int (*xOut)(const char*,void*), - void *pOutArg, - int makeDefault - ); - vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1); -#endif -#ifdef SQLITE_ENABLE_MULTIPLEX - }else if( strcmp(z,"-multiplex")==0 ){ - extern int sqlite3_multiple_initialize(const char*,int); - sqlite3_multiplex_initialize(0, 1); -#endif - }else if( strcmp(z,"-vfs")==0 ){ - sqlite3_vfs *pVfs = sqlite3_vfs_find(cmdline_option_value(argc,argv,++i)); - if( pVfs ){ - sqlite3_vfs_register(pVfs, 1); - }else{ - fprintf(stderr, "no such VFS: \"%s\"\n", argv[i]); - exit(1); - } - } - } - if( data.zDbFilename==0 ){ -#ifndef SQLITE_OMIT_MEMORYDB - data.zDbFilename = ":memory:"; -#else - fprintf(stderr,"%s: Error: no database filename specified\n", Argv0); - return 1; -#endif - } - data.out = stdout; - - /* Go ahead and open the database file if it already exists. If the - ** file does not exist, delay opening it. This prevents empty database - ** files from being created if a user mistypes the database name argument - ** to the sqlite command-line tool. - */ - if( access(data.zDbFilename, 0)==0 ){ - open_db(&data); - } - - /* Process the initialization file if there is one. If no -init option - ** is given on the command line, look for a file named ~/.sqliterc and - ** try to process it. - */ - rc = process_sqliterc(&data,zInitFile); - if( rc>0 ){ - return rc; - } - - /* Make a second pass through the command-line argument and set - ** options. This second pass is delayed until after the initialization - ** file is processed so that the command-line arguments will override - ** settings in the initialization file. - */ - for(i=1; i - - - - Debug - Win32 - - - Release - Win32 - - - - {C074BD80-7E37-4975-81CA-DF1E50DF64BA} - Win32Proj - sqlite - - - - StaticLibrary - true - Unicode - - - StaticLibrary - false - true - Unicode - - - - - - - - - - - - - - - - - Level3 - Disabled - WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions) - - - Windows - true - - - - - Level3 - - - MaxSpeed - true - true - WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions) - - - Windows - true - true - true - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/LibTools/ogr/windows/sqlite-amalgamation-3071602/sqlite/sqlite.vcxproj.filters b/LibTools/ogr/windows/sqlite-amalgamation-3071602/sqlite/sqlite.vcxproj.filters deleted file mode 100644 index 493f38800..000000000 --- a/LibTools/ogr/windows/sqlite-amalgamation-3071602/sqlite/sqlite.vcxproj.filters +++ /dev/null @@ -1,33 +0,0 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hpp;hxx;hm;inl;inc;xsd - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms - - - - - - - - Source Files - - - - - Header Files - - - Header Files - - - \ No newline at end of file diff --git a/LibTools/ogr/windows/sqlite-amalgamation-3071602/sqlite3.c b/LibTools/ogr/windows/sqlite-amalgamation-3071602/sqlite3.c deleted file mode 100644 index 51e54a189..000000000 --- a/LibTools/ogr/windows/sqlite-amalgamation-3071602/sqlite3.c +++ /dev/null @@ -1,138114 +0,0 @@ -/****************************************************************************** -** This file is an amalgamation of many separate C source files from SQLite -** version 3.7.16.2. By combining all the individual C code files into this -** single large file, the entire code can be compiled as a single translation -** unit. This allows many compilers to do optimizations that would not be -** possible if the files were compiled separately. Performance improvements -** of 5% or more are commonly seen when SQLite is compiled as a single -** translation unit. -** -** This file is all you need to compile SQLite. To use SQLite in other -** programs, you need this file and the "sqlite3.h" header file that defines -** the programming interface to the SQLite library. (If you do not have -** the "sqlite3.h" header file at hand, you will find a copy embedded within -** the text of this file. Search for "Begin file sqlite3.h" to find the start -** of the embedded sqlite3.h header file.) Additional code files may be needed -** if you want a wrapper to interface SQLite with your choice of programming -** language. The code for the "sqlite3" command-line shell is also in a -** separate file. This file contains only code for the core SQLite library. -*/ -#define SQLITE_CORE 1 -#define SQLITE_AMALGAMATION 1 -#ifndef SQLITE_PRIVATE -# define SQLITE_PRIVATE static -#endif -#ifndef SQLITE_API -# define SQLITE_API -#endif -/************** Begin file sqliteInt.h ***************************************/ -/* -** 2001 September 15 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** Internal interface definitions for SQLite. -** -*/ -#ifndef _SQLITEINT_H_ -#define _SQLITEINT_H_ - -/* -** These #defines should enable >2GB file support on POSIX if the -** underlying operating system supports it. If the OS lacks -** large file support, or if the OS is windows, these should be no-ops. -** -** Ticket #2739: The _LARGEFILE_SOURCE macro must appear before any -** system #includes. Hence, this block of code must be the very first -** code in all source files. -** -** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch -** on the compiler command line. This is necessary if you are compiling -** on a recent machine (ex: Red Hat 7.2) but you want your code to work -** on an older machine (ex: Red Hat 6.0). If you compile on Red Hat 7.2 -** without this option, LFS is enable. But LFS does not exist in the kernel -** in Red Hat 6.0, so the code won't work. Hence, for maximum binary -** portability you should omit LFS. -** -** Similar is true for Mac OS X. LFS is only supported on Mac OS X 9 and later. -*/ -#ifndef SQLITE_DISABLE_LFS -# define _LARGE_FILE 1 -# ifndef _FILE_OFFSET_BITS -# define _FILE_OFFSET_BITS 64 -# endif -# define _LARGEFILE_SOURCE 1 -#endif - -/* -** Include the configuration header output by 'configure' if we're using the -** autoconf-based build -*/ -#ifdef _HAVE_SQLITE_CONFIG_H -#include "config.h" -#endif - -/************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/ -/************** Begin file sqliteLimit.h *************************************/ -/* -** 2007 May 7 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** -** This file defines various limits of what SQLite can process. -*/ - -/* -** The maximum length of a TEXT or BLOB in bytes. This also -** limits the size of a row in a table or index. -** -** The hard limit is the ability of a 32-bit signed integer -** to count the size: 2^31-1 or 2147483647. -*/ -#ifndef SQLITE_MAX_LENGTH -# define SQLITE_MAX_LENGTH 1000000000 -#endif - -/* -** This is the maximum number of -** -** * Columns in a table -** * Columns in an index -** * Columns in a view -** * Terms in the SET clause of an UPDATE statement -** * Terms in the result set of a SELECT statement -** * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement. -** * Terms in the VALUES clause of an INSERT statement -** -** The hard upper limit here is 32676. Most database people will -** tell you that in a well-normalized database, you usually should -** not have more than a dozen or so columns in any table. And if -** that is the case, there is no point in having more than a few -** dozen values in any of the other situations described above. -*/ -#ifndef SQLITE_MAX_COLUMN -# define SQLITE_MAX_COLUMN 2000 -#endif - -/* -** The maximum length of a single SQL statement in bytes. -** -** It used to be the case that setting this value to zero would -** turn the limit off. That is no longer true. It is not possible -** to turn this limit off. -*/ -#ifndef SQLITE_MAX_SQL_LENGTH -# define SQLITE_MAX_SQL_LENGTH 1000000000 -#endif - -/* -** The maximum depth of an expression tree. This is limited to -** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might -** want to place more severe limits on the complexity of an -** expression. -** -** A value of 0 used to mean that the limit was not enforced. -** But that is no longer true. The limit is now strictly enforced -** at all times. -*/ -#ifndef SQLITE_MAX_EXPR_DEPTH -# define SQLITE_MAX_EXPR_DEPTH 1000 -#endif - -/* -** The maximum number of terms in a compound SELECT statement. -** The code generator for compound SELECT statements does one -** level of recursion for each term. A stack overflow can result -** if the number of terms is too large. In practice, most SQL -** never has more than 3 or 4 terms. Use a value of 0 to disable -** any limit on the number of terms in a compount SELECT. -*/ -#ifndef SQLITE_MAX_COMPOUND_SELECT -# define SQLITE_MAX_COMPOUND_SELECT 500 -#endif - -/* -** The maximum number of opcodes in a VDBE program. -** Not currently enforced. -*/ -#ifndef SQLITE_MAX_VDBE_OP -# define SQLITE_MAX_VDBE_OP 25000 -#endif - -/* -** The maximum number of arguments to an SQL function. -*/ -#ifndef SQLITE_MAX_FUNCTION_ARG -# define SQLITE_MAX_FUNCTION_ARG 127 -#endif - -/* -** The maximum number of in-memory pages to use for the main database -** table and for temporary tables. The SQLITE_DEFAULT_CACHE_SIZE -*/ -#ifndef SQLITE_DEFAULT_CACHE_SIZE -# define SQLITE_DEFAULT_CACHE_SIZE 2000 -#endif -#ifndef SQLITE_DEFAULT_TEMP_CACHE_SIZE -# define SQLITE_DEFAULT_TEMP_CACHE_SIZE 500 -#endif - -/* -** The default number of frames to accumulate in the log file before -** checkpointing the database in WAL mode. -*/ -#ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT -# define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT 1000 -#endif - -/* -** The maximum number of attached databases. This must be between 0 -** and 62. The upper bound on 62 is because a 64-bit integer bitmap -** is used internally to track attached databases. -*/ -#ifndef SQLITE_MAX_ATTACHED -# define SQLITE_MAX_ATTACHED 10 -#endif - - -/* -** The maximum value of a ?nnn wildcard that the parser will accept. -*/ -#ifndef SQLITE_MAX_VARIABLE_NUMBER -# define SQLITE_MAX_VARIABLE_NUMBER 999 -#endif - -/* Maximum page size. The upper bound on this value is 65536. This a limit -** imposed by the use of 16-bit offsets within each page. -** -** Earlier versions of SQLite allowed the user to change this value at -** compile time. This is no longer permitted, on the grounds that it creates -** a library that is technically incompatible with an SQLite library -** compiled with a different limit. If a process operating on a database -** with a page-size of 65536 bytes crashes, then an instance of SQLite -** compiled with the default page-size limit will not be able to rollback -** the aborted transaction. This could lead to database corruption. -*/ -#ifdef SQLITE_MAX_PAGE_SIZE -# undef SQLITE_MAX_PAGE_SIZE -#endif -#define SQLITE_MAX_PAGE_SIZE 65536 - - -/* -** The default size of a database page. -*/ -#ifndef SQLITE_DEFAULT_PAGE_SIZE -# define SQLITE_DEFAULT_PAGE_SIZE 1024 -#endif -#if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE -# undef SQLITE_DEFAULT_PAGE_SIZE -# define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE -#endif - -/* -** Ordinarily, if no value is explicitly provided, SQLite creates databases -** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain -** device characteristics (sector-size and atomic write() support), -** SQLite may choose a larger value. This constant is the maximum value -** SQLite will choose on its own. -*/ -#ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE -# define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192 -#endif -#if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE -# undef SQLITE_MAX_DEFAULT_PAGE_SIZE -# define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE -#endif - - -/* -** Maximum number of pages in one database file. -** -** This is really just the default value for the max_page_count pragma. -** This value can be lowered (or raised) at run-time using that the -** max_page_count macro. -*/ -#ifndef SQLITE_MAX_PAGE_COUNT -# define SQLITE_MAX_PAGE_COUNT 1073741823 -#endif - -/* -** Maximum length (in bytes) of the pattern in a LIKE or GLOB -** operator. -*/ -#ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH -# define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000 -#endif - -/* -** Maximum depth of recursion for triggers. -** -** A value of 1 means that a trigger program will not be able to itself -** fire any triggers. A value of 0 means that no trigger programs at all -** may be executed. -*/ -#ifndef SQLITE_MAX_TRIGGER_DEPTH -# define SQLITE_MAX_TRIGGER_DEPTH 1000 -#endif - -/************** End of sqliteLimit.h *****************************************/ -/************** Continuing where we left off in sqliteInt.h ******************/ - -/* Disable nuisance warnings on Borland compilers */ -#if defined(__BORLANDC__) -#pragma warn -rch /* unreachable code */ -#pragma warn -ccc /* Condition is always true or false */ -#pragma warn -aus /* Assigned value is never used */ -#pragma warn -csu /* Comparing signed and unsigned */ -#pragma warn -spa /* Suspicious pointer arithmetic */ -#endif - -/* Needed for various definitions... */ -#ifndef _GNU_SOURCE -# define _GNU_SOURCE -#endif - -#if defined(__OpenBSD__) && !defined(_BSD_SOURCE) -# define _BSD_SOURCE -#endif - -/* -** Include standard header files as necessary -*/ -#ifdef HAVE_STDINT_H -#include -#endif -#ifdef HAVE_INTTYPES_H -#include -#endif - -/* -** The following macros are used to cast pointers to integers and -** integers to pointers. The way you do this varies from one compiler -** to the next, so we have developed the following set of #if statements -** to generate appropriate macros for a wide range of compilers. -** -** The correct "ANSI" way to do this is to use the intptr_t type. -** Unfortunately, that typedef is not available on all compilers, or -** if it is available, it requires an #include of specific headers -** that vary from one machine to the next. -** -** Ticket #3860: The llvm-gcc-4.2 compiler from Apple chokes on -** the ((void*)&((char*)0)[X]) construct. But MSVC chokes on ((void*)(X)). -** So we have to define the macros in different ways depending on the -** compiler. -*/ -#if defined(__PTRDIFF_TYPE__) /* This case should work for GCC */ -# define SQLITE_INT_TO_PTR(X) ((void*)(__PTRDIFF_TYPE__)(X)) -# define SQLITE_PTR_TO_INT(X) ((int)(__PTRDIFF_TYPE__)(X)) -#elif !defined(__GNUC__) /* Works for compilers other than LLVM */ -# define SQLITE_INT_TO_PTR(X) ((void*)&((char*)0)[X]) -# define SQLITE_PTR_TO_INT(X) ((int)(((char*)X)-(char*)0)) -#elif defined(HAVE_STDINT_H) /* Use this case if we have ANSI headers */ -# define SQLITE_INT_TO_PTR(X) ((void*)(intptr_t)(X)) -# define SQLITE_PTR_TO_INT(X) ((int)(intptr_t)(X)) -#else /* Generates a warning - but it always works */ -# define SQLITE_INT_TO_PTR(X) ((void*)(X)) -# define SQLITE_PTR_TO_INT(X) ((int)(X)) -#endif - -/* -** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2. -** 0 means mutexes are permanently disable and the library is never -** threadsafe. 1 means the library is serialized which is the highest -** level of threadsafety. 2 means the libary is multithreaded - multiple -** threads can use SQLite as long as no two threads try to use the same -** database connection at the same time. -** -** Older versions of SQLite used an optional THREADSAFE macro. -** We support that for legacy. -*/ -#if !defined(SQLITE_THREADSAFE) -#if defined(THREADSAFE) -# define SQLITE_THREADSAFE THREADSAFE -#else -# define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */ -#endif -#endif - -/* -** Powersafe overwrite is on by default. But can be turned off using -** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option. -*/ -#ifndef SQLITE_POWERSAFE_OVERWRITE -# define SQLITE_POWERSAFE_OVERWRITE 1 -#endif - -/* -** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1. -** It determines whether or not the features related to -** SQLITE_CONFIG_MEMSTATUS are available by default or not. This value can -** be overridden at runtime using the sqlite3_config() API. -*/ -#if !defined(SQLITE_DEFAULT_MEMSTATUS) -# define SQLITE_DEFAULT_MEMSTATUS 1 -#endif - -/* -** Exactly one of the following macros must be defined in order to -** specify which memory allocation subsystem to use. -** -** SQLITE_SYSTEM_MALLOC // Use normal system malloc() -** SQLITE_WIN32_MALLOC // Use Win32 native heap API -** SQLITE_ZERO_MALLOC // Use a stub allocator that always fails -** SQLITE_MEMDEBUG // Debugging version of system malloc() -** -** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the -** assert() macro is enabled, each call into the Win32 native heap subsystem -** will cause HeapValidate to be called. If heap validation should fail, an -** assertion will be triggered. -** -** (Historical note: There used to be several other options, but we've -** pared it down to just these three.) -** -** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as -** the default. -*/ -#if defined(SQLITE_SYSTEM_MALLOC) \ - + defined(SQLITE_WIN32_MALLOC) \ - + defined(SQLITE_ZERO_MALLOC) \ - + defined(SQLITE_MEMDEBUG)>1 -# error "Two or more of the following compile-time configuration options\ - are defined but at most one is allowed:\ - SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG,\ - SQLITE_ZERO_MALLOC" -#endif -#if defined(SQLITE_SYSTEM_MALLOC) \ - + defined(SQLITE_WIN32_MALLOC) \ - + defined(SQLITE_ZERO_MALLOC) \ - + defined(SQLITE_MEMDEBUG)==0 -# define SQLITE_SYSTEM_MALLOC 1 -#endif - -/* -** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the -** sizes of memory allocations below this value where possible. -*/ -#if !defined(SQLITE_MALLOC_SOFT_LIMIT) -# define SQLITE_MALLOC_SOFT_LIMIT 1024 -#endif - -/* -** We need to define _XOPEN_SOURCE as follows in order to enable -** recursive mutexes on most Unix systems. But Mac OS X is different. -** The _XOPEN_SOURCE define causes problems for Mac OS X we are told, -** so it is omitted there. See ticket #2673. -** -** Later we learn that _XOPEN_SOURCE is poorly or incorrectly -** implemented on some systems. So we avoid defining it at all -** if it is already defined or if it is unneeded because we are -** not doing a threadsafe build. Ticket #2681. -** -** See also ticket #2741. -*/ -#if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) \ - && !defined(__APPLE__) && SQLITE_THREADSAFE -# define _XOPEN_SOURCE 500 /* Needed to enable pthread recursive mutexes */ -#endif - -/* -** The TCL headers are only needed when compiling the TCL bindings. -*/ -#if defined(SQLITE_TCL) || defined(TCLSH) -# include -#endif - -/* -** NDEBUG and SQLITE_DEBUG are opposites. It should always be true that -** defined(NDEBUG)==!defined(SQLITE_DEBUG). If this is not currently true, -** make it true by defining or undefining NDEBUG. -** -** Setting NDEBUG makes the code smaller and run faster by disabling the -** number assert() statements in the code. So we want the default action -** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG -** is set. Thus NDEBUG becomes an opt-in rather than an opt-out -** feature. -*/ -#if !defined(NDEBUG) && !defined(SQLITE_DEBUG) -# define NDEBUG 1 -#endif -#if defined(NDEBUG) && defined(SQLITE_DEBUG) -# undef NDEBUG -#endif - -/* -** The testcase() macro is used to aid in coverage testing. When -** doing coverage testing, the condition inside the argument to -** testcase() must be evaluated both true and false in order to -** get full branch coverage. The testcase() macro is inserted -** to help ensure adequate test coverage in places where simple -** condition/decision coverage is inadequate. For example, testcase() -** can be used to make sure boundary values are tested. For -** bitmask tests, testcase() can be used to make sure each bit -** is significant and used at least once. On switch statements -** where multiple cases go to the same block of code, testcase() -** can insure that all cases are evaluated. -** -*/ -#ifdef SQLITE_COVERAGE_TEST -SQLITE_PRIVATE void sqlite3Coverage(int); -# define testcase(X) if( X ){ sqlite3Coverage(__LINE__); } -#else -# define testcase(X) -#endif - -/* -** The TESTONLY macro is used to enclose variable declarations or -** other bits of code that are needed to support the arguments -** within testcase() and assert() macros. -*/ -#if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST) -# define TESTONLY(X) X -#else -# define TESTONLY(X) -#endif - -/* -** Sometimes we need a small amount of code such as a variable initialization -** to setup for a later assert() statement. We do not want this code to -** appear when assert() is disabled. The following macro is therefore -** used to contain that setup code. The "VVA" acronym stands for -** "Verification, Validation, and Accreditation". In other words, the -** code within VVA_ONLY() will only run during verification processes. -*/ -#ifndef NDEBUG -# define VVA_ONLY(X) X -#else -# define VVA_ONLY(X) -#endif - -/* -** The ALWAYS and NEVER macros surround boolean expressions which -** are intended to always be true or false, respectively. Such -** expressions could be omitted from the code completely. But they -** are included in a few cases in order to enhance the resilience -** of SQLite to unexpected behavior - to make the code "self-healing" -** or "ductile" rather than being "brittle" and crashing at the first -** hint of unplanned behavior. -** -** In other words, ALWAYS and NEVER are added for defensive code. -** -** When doing coverage testing ALWAYS and NEVER are hard-coded to -** be true and false so that the unreachable code then specify will -** not be counted as untested code. -*/ -#if defined(SQLITE_COVERAGE_TEST) -# define ALWAYS(X) (1) -# define NEVER(X) (0) -#elif !defined(NDEBUG) -# define ALWAYS(X) ((X)?1:(assert(0),0)) -# define NEVER(X) ((X)?(assert(0),1):0) -#else -# define ALWAYS(X) (X) -# define NEVER(X) (X) -#endif - -/* -** Return true (non-zero) if the input is a integer that is too large -** to fit in 32-bits. This macro is used inside of various testcase() -** macros to verify that we have tested SQLite for large-file support. -*/ -#define IS_BIG_INT(X) (((X)&~(i64)0xffffffff)!=0) - -/* -** The macro unlikely() is a hint that surrounds a boolean -** expression that is usually false. Macro likely() surrounds -** a boolean expression that is usually true. GCC is able to -** use these hints to generate better code, sometimes. -*/ -#if defined(__GNUC__) && 0 -# define likely(X) __builtin_expect((X),1) -# define unlikely(X) __builtin_expect((X),0) -#else -# define likely(X) !!(X) -# define unlikely(X) !!(X) -#endif - -/************** Include sqlite3.h in the middle of sqliteInt.h ***************/ -/************** Begin file sqlite3.h *****************************************/ -/* -** 2001 September 15 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** This header file defines the interface that the SQLite library -** presents to client programs. If a C-function, structure, datatype, -** or constant definition does not appear in this file, then it is -** not a published API of SQLite, is subject to change without -** notice, and should not be referenced by programs that use SQLite. -** -** Some of the definitions that are in this file are marked as -** "experimental". Experimental interfaces are normally new -** features recently added to SQLite. We do not anticipate changes -** to experimental interfaces but reserve the right to make minor changes -** if experience from use "in the wild" suggest such changes are prudent. -** -** The official C-language API documentation for SQLite is derived -** from comments in this file. This file is the authoritative source -** on how SQLite interfaces are suppose to operate. -** -** The name of this file under configuration management is "sqlite.h.in". -** The makefile makes some minor changes to this file (such as inserting -** the version number) and changes its name to "sqlite3.h" as -** part of the build process. -*/ -#ifndef _SQLITE3_H_ -#define _SQLITE3_H_ -#include /* Needed for the definition of va_list */ - -/* -** Make sure we can call this stuff from C++. -*/ -#if 0 -extern "C" { -#endif - - -/* -** Add the ability to override 'extern' -*/ -#ifndef SQLITE_EXTERN -# define SQLITE_EXTERN extern -#endif - -#ifndef SQLITE_API -# define SQLITE_API -#endif - - -/* -** These no-op macros are used in front of interfaces to mark those -** interfaces as either deprecated or experimental. New applications -** should not use deprecated interfaces - they are support for backwards -** compatibility only. Application writers should be aware that -** experimental interfaces are subject to change in point releases. -** -** These macros used to resolve to various kinds of compiler magic that -** would generate warning messages when they were used. But that -** compiler magic ended up generating such a flurry of bug reports -** that we have taken it all out and gone back to using simple -** noop macros. -*/ -#define SQLITE_DEPRECATED -#define SQLITE_EXPERIMENTAL - -/* -** Ensure these symbols were not defined by some previous header file. -*/ -#ifdef SQLITE_VERSION -# undef SQLITE_VERSION -#endif -#ifdef SQLITE_VERSION_NUMBER -# undef SQLITE_VERSION_NUMBER -#endif - -/* -** CAPI3REF: Compile-Time Library Version Numbers -** -** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header -** evaluates to a string literal that is the SQLite version in the -** format "X.Y.Z" where X is the major version number (always 3 for -** SQLite3) and Y is the minor version number and Z is the release number.)^ -** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer -** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same -** numbers used in [SQLITE_VERSION].)^ -** The SQLITE_VERSION_NUMBER for any given release of SQLite will also -** be larger than the release from which it is derived. Either Y will -** be held constant and Z will be incremented or else Y will be incremented -** and Z will be reset to zero. -** -** Since version 3.6.18, SQLite source code has been stored in the -** Fossil configuration management -** system. ^The SQLITE_SOURCE_ID macro evaluates to -** a string which identifies a particular check-in of SQLite -** within its configuration management system. ^The SQLITE_SOURCE_ID -** string contains the date and time of the check-in (UTC) and an SHA1 -** hash of the entire source tree. -** -** See also: [sqlite3_libversion()], -** [sqlite3_libversion_number()], [sqlite3_sourceid()], -** [sqlite_version()] and [sqlite_source_id()]. -*/ -#define SQLITE_VERSION "3.7.16.2" -#define SQLITE_VERSION_NUMBER 3007016 -#define SQLITE_SOURCE_ID "2013-04-12 11:52:43 cbea02d93865ce0e06789db95fd9168ebac970c7" - -/* -** CAPI3REF: Run-Time Library Version Numbers -** KEYWORDS: sqlite3_version, sqlite3_sourceid -** -** These interfaces provide the same information as the [SQLITE_VERSION], -** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros -** but are associated with the library instead of the header file. ^(Cautious -** programmers might include assert() statements in their application to -** verify that values returned by these interfaces match the macros in -** the header, and thus insure that the application is -** compiled with matching library and header files. -** -**
    -** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
    -** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
    -** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
    -** 
    )^ -** -** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION] -** macro. ^The sqlite3_libversion() function returns a pointer to the -** to the sqlite3_version[] string constant. The sqlite3_libversion() -** function is provided for use in DLLs since DLL users usually do not have -** direct access to string constants within the DLL. ^The -** sqlite3_libversion_number() function returns an integer equal to -** [SQLITE_VERSION_NUMBER]. ^The sqlite3_sourceid() function returns -** a pointer to a string constant whose value is the same as the -** [SQLITE_SOURCE_ID] C preprocessor macro. -** -** See also: [sqlite_version()] and [sqlite_source_id()]. -*/ -SQLITE_API const char sqlite3_version[] = SQLITE_VERSION; -SQLITE_API const char *sqlite3_libversion(void); -SQLITE_API const char *sqlite3_sourceid(void); -SQLITE_API int sqlite3_libversion_number(void); - -/* -** CAPI3REF: Run-Time Library Compilation Options Diagnostics -** -** ^The sqlite3_compileoption_used() function returns 0 or 1 -** indicating whether the specified option was defined at -** compile time. ^The SQLITE_ prefix may be omitted from the -** option name passed to sqlite3_compileoption_used(). -** -** ^The sqlite3_compileoption_get() function allows iterating -** over the list of options that were defined at compile time by -** returning the N-th compile time option string. ^If N is out of range, -** sqlite3_compileoption_get() returns a NULL pointer. ^The SQLITE_ -** prefix is omitted from any strings returned by -** sqlite3_compileoption_get(). -** -** ^Support for the diagnostic functions sqlite3_compileoption_used() -** and sqlite3_compileoption_get() may be omitted by specifying the -** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time. -** -** See also: SQL functions [sqlite_compileoption_used()] and -** [sqlite_compileoption_get()] and the [compile_options pragma]. -*/ -#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS -SQLITE_API int sqlite3_compileoption_used(const char *zOptName); -SQLITE_API const char *sqlite3_compileoption_get(int N); -#endif - -/* -** CAPI3REF: Test To See If The Library Is Threadsafe -** -** ^The sqlite3_threadsafe() function returns zero if and only if -** SQLite was compiled with mutexing code omitted due to the -** [SQLITE_THREADSAFE] compile-time option being set to 0. -** -** SQLite can be compiled with or without mutexes. When -** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes -** are enabled and SQLite is threadsafe. When the -** [SQLITE_THREADSAFE] macro is 0, -** the mutexes are omitted. Without the mutexes, it is not safe -** to use SQLite concurrently from more than one thread. -** -** Enabling mutexes incurs a measurable performance penalty. -** So if speed is of utmost importance, it makes sense to disable -** the mutexes. But for maximum safety, mutexes should be enabled. -** ^The default behavior is for mutexes to be enabled. -** -** This interface can be used by an application to make sure that the -** version of SQLite that it is linking against was compiled with -** the desired setting of the [SQLITE_THREADSAFE] macro. -** -** This interface only reports on the compile-time mutex setting -** of the [SQLITE_THREADSAFE] flag. If SQLite is compiled with -** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but -** can be fully or partially disabled using a call to [sqlite3_config()] -** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD], -** or [SQLITE_CONFIG_MUTEX]. ^(The return value of the -** sqlite3_threadsafe() function shows only the compile-time setting of -** thread safety, not any run-time changes to that setting made by -** sqlite3_config(). In other words, the return value from sqlite3_threadsafe() -** is unchanged by calls to sqlite3_config().)^ -** -** See the [threading mode] documentation for additional information. -*/ -SQLITE_API int sqlite3_threadsafe(void); - -/* -** CAPI3REF: Database Connection Handle -** KEYWORDS: {database connection} {database connections} -** -** Each open SQLite database is represented by a pointer to an instance of -** the opaque structure named "sqlite3". It is useful to think of an sqlite3 -** pointer as an object. The [sqlite3_open()], [sqlite3_open16()], and -** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()] -** and [sqlite3_close_v2()] are its destructors. There are many other -** interfaces (such as -** [sqlite3_prepare_v2()], [sqlite3_create_function()], and -** [sqlite3_busy_timeout()] to name but three) that are methods on an -** sqlite3 object. -*/ -typedef struct sqlite3 sqlite3; - -/* -** CAPI3REF: 64-Bit Integer Types -** KEYWORDS: sqlite_int64 sqlite_uint64 -** -** Because there is no cross-platform way to specify 64-bit integer types -** SQLite includes typedefs for 64-bit signed and unsigned integers. -** -** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions. -** The sqlite_int64 and sqlite_uint64 types are supported for backwards -** compatibility only. -** -** ^The sqlite3_int64 and sqlite_int64 types can store integer values -** between -9223372036854775808 and +9223372036854775807 inclusive. ^The -** sqlite3_uint64 and sqlite_uint64 types can store integer values -** between 0 and +18446744073709551615 inclusive. -*/ -#ifdef SQLITE_INT64_TYPE - typedef SQLITE_INT64_TYPE sqlite_int64; - typedef unsigned SQLITE_INT64_TYPE sqlite_uint64; -#elif defined(_MSC_VER) || defined(__BORLANDC__) - typedef __int64 sqlite_int64; - typedef unsigned __int64 sqlite_uint64; -#else - typedef long long int sqlite_int64; - typedef unsigned long long int sqlite_uint64; -#endif -typedef sqlite_int64 sqlite3_int64; -typedef sqlite_uint64 sqlite3_uint64; - -/* -** If compiling for a processor that lacks floating point support, -** substitute integer for floating-point. -*/ -#ifdef SQLITE_OMIT_FLOATING_POINT -# define double sqlite3_int64 -#endif - -/* -** CAPI3REF: Closing A Database Connection -** -** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors -** for the [sqlite3] object. -** ^Calls to sqlite3_close() and sqlite3_close_v2() return SQLITE_OK if -** the [sqlite3] object is successfully destroyed and all associated -** resources are deallocated. -** -** ^If the database connection is associated with unfinalized prepared -** statements or unfinished sqlite3_backup objects then sqlite3_close() -** will leave the database connection open and return [SQLITE_BUSY]. -** ^If sqlite3_close_v2() is called with unfinalized prepared statements -** and unfinished sqlite3_backups, then the database connection becomes -** an unusable "zombie" which will automatically be deallocated when the -** last prepared statement is finalized or the last sqlite3_backup is -** finished. The sqlite3_close_v2() interface is intended for use with -** host languages that are garbage collected, and where the order in which -** destructors are called is arbitrary. -** -** Applications should [sqlite3_finalize | finalize] all [prepared statements], -** [sqlite3_blob_close | close] all [BLOB handles], and -** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated -** with the [sqlite3] object prior to attempting to close the object. ^If -** sqlite3_close_v2() is called on a [database connection] that still has -** outstanding [prepared statements], [BLOB handles], and/or -** [sqlite3_backup] objects then it returns SQLITE_OK but the deallocation -** of resources is deferred until all [prepared statements], [BLOB handles], -** and [sqlite3_backup] objects are also destroyed. -** -** ^If an [sqlite3] object is destroyed while a transaction is open, -** the transaction is automatically rolled back. -** -** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)] -** must be either a NULL -** pointer or an [sqlite3] object pointer obtained -** from [sqlite3_open()], [sqlite3_open16()], or -** [sqlite3_open_v2()], and not previously closed. -** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer -** argument is a harmless no-op. -*/ -SQLITE_API int sqlite3_close(sqlite3*); -SQLITE_API int sqlite3_close_v2(sqlite3*); - -/* -** The type for a callback function. -** This is legacy and deprecated. It is included for historical -** compatibility and is not documented. -*/ -typedef int (*sqlite3_callback)(void*,int,char**, char**); - -/* -** CAPI3REF: One-Step Query Execution Interface -** -** The sqlite3_exec() interface is a convenience wrapper around -** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()], -** that allows an application to run multiple statements of SQL -** without having to use a lot of C code. -** -** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded, -** semicolon-separate SQL statements passed into its 2nd argument, -** in the context of the [database connection] passed in as its 1st -** argument. ^If the callback function of the 3rd argument to -** sqlite3_exec() is not NULL, then it is invoked for each result row -** coming out of the evaluated SQL statements. ^The 4th argument to -** sqlite3_exec() is relayed through to the 1st argument of each -** callback invocation. ^If the callback pointer to sqlite3_exec() -** is NULL, then no callback is ever invoked and result rows are -** ignored. -** -** ^If an error occurs while evaluating the SQL statements passed into -** sqlite3_exec(), then execution of the current statement stops and -** subsequent statements are skipped. ^If the 5th parameter to sqlite3_exec() -** is not NULL then any error message is written into memory obtained -** from [sqlite3_malloc()] and passed back through the 5th parameter. -** To avoid memory leaks, the application should invoke [sqlite3_free()] -** on error message strings returned through the 5th parameter of -** of sqlite3_exec() after the error message string is no longer needed. -** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors -** occur, then sqlite3_exec() sets the pointer in its 5th parameter to -** NULL before returning. -** -** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec() -** routine returns SQLITE_ABORT without invoking the callback again and -** without running any subsequent SQL statements. -** -** ^The 2nd argument to the sqlite3_exec() callback function is the -** number of columns in the result. ^The 3rd argument to the sqlite3_exec() -** callback is an array of pointers to strings obtained as if from -** [sqlite3_column_text()], one for each column. ^If an element of a -** result row is NULL then the corresponding string pointer for the -** sqlite3_exec() callback is a NULL pointer. ^The 4th argument to the -** sqlite3_exec() callback is an array of pointers to strings where each -** entry represents the name of corresponding result column as obtained -** from [sqlite3_column_name()]. -** -** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer -** to an empty string, or a pointer that contains only whitespace and/or -** SQL comments, then no SQL statements are evaluated and the database -** is not changed. -** -** Restrictions: -** -**
      -**
    • The application must insure that the 1st parameter to sqlite3_exec() -** is a valid and open [database connection]. -**
    • The application must not close [database connection] specified by -** the 1st parameter to sqlite3_exec() while sqlite3_exec() is running. -**
    • The application must not modify the SQL statement text passed into -** the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running. -**
    -*/ -SQLITE_API int sqlite3_exec( - sqlite3*, /* An open database */ - const char *sql, /* SQL to be evaluated */ - int (*callback)(void*,int,char**,char**), /* Callback function */ - void *, /* 1st argument to callback */ - char **errmsg /* Error msg written here */ -); - -/* -** CAPI3REF: Result Codes -** KEYWORDS: SQLITE_OK {error code} {error codes} -** KEYWORDS: {result code} {result codes} -** -** Many SQLite functions return an integer result code from the set shown -** here in order to indicate success or failure. -** -** New error codes may be added in future versions of SQLite. -** -** See also: [SQLITE_IOERR_READ | extended result codes], -** [sqlite3_vtab_on_conflict()] [SQLITE_ROLLBACK | result codes]. -*/ -#define SQLITE_OK 0 /* Successful result */ -/* beginning-of-error-codes */ -#define SQLITE_ERROR 1 /* SQL error or missing database */ -#define SQLITE_INTERNAL 2 /* Internal logic error in SQLite */ -#define SQLITE_PERM 3 /* Access permission denied */ -#define SQLITE_ABORT 4 /* Callback routine requested an abort */ -#define SQLITE_BUSY 5 /* The database file is locked */ -#define SQLITE_LOCKED 6 /* A table in the database is locked */ -#define SQLITE_NOMEM 7 /* A malloc() failed */ -#define SQLITE_READONLY 8 /* Attempt to write a readonly database */ -#define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/ -#define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */ -#define SQLITE_CORRUPT 11 /* The database disk image is malformed */ -#define SQLITE_NOTFOUND 12 /* Unknown opcode in sqlite3_file_control() */ -#define SQLITE_FULL 13 /* Insertion failed because database is full */ -#define SQLITE_CANTOPEN 14 /* Unable to open the database file */ -#define SQLITE_PROTOCOL 15 /* Database lock protocol error */ -#define SQLITE_EMPTY 16 /* Database is empty */ -#define SQLITE_SCHEMA 17 /* The database schema changed */ -#define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */ -#define SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */ -#define SQLITE_MISMATCH 20 /* Data type mismatch */ -#define SQLITE_MISUSE 21 /* Library used incorrectly */ -#define SQLITE_NOLFS 22 /* Uses OS features not supported on host */ -#define SQLITE_AUTH 23 /* Authorization denied */ -#define SQLITE_FORMAT 24 /* Auxiliary database format error */ -#define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */ -#define SQLITE_NOTADB 26 /* File opened that is not a database file */ -#define SQLITE_ROW 100 /* sqlite3_step() has another row ready */ -#define SQLITE_DONE 101 /* sqlite3_step() has finished executing */ -/* end-of-error-codes */ - -/* -** CAPI3REF: Extended Result Codes -** KEYWORDS: {extended error code} {extended error codes} -** KEYWORDS: {extended result code} {extended result codes} -** -** In its default configuration, SQLite API routines return one of 26 integer -** [SQLITE_OK | result codes]. However, experience has shown that many of -** these result codes are too coarse-grained. They do not provide as -** much information about problems as programmers might like. In an effort to -** address this, newer versions of SQLite (version 3.3.8 and later) include -** support for additional result codes that provide more detailed information -** about errors. The extended result codes are enabled or disabled -** on a per database connection basis using the -** [sqlite3_extended_result_codes()] API. -** -** Some of the available extended result codes are listed here. -** One may expect the number of extended result codes will be expand -** over time. Software that uses extended result codes should expect -** to see new result codes in future releases of SQLite. -** -** The SQLITE_OK result code will never be extended. It will always -** be exactly zero. -*/ -#define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8)) -#define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8)) -#define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8)) -#define SQLITE_IOERR_FSYNC (SQLITE_IOERR | (4<<8)) -#define SQLITE_IOERR_DIR_FSYNC (SQLITE_IOERR | (5<<8)) -#define SQLITE_IOERR_TRUNCATE (SQLITE_IOERR | (6<<8)) -#define SQLITE_IOERR_FSTAT (SQLITE_IOERR | (7<<8)) -#define SQLITE_IOERR_UNLOCK (SQLITE_IOERR | (8<<8)) -#define SQLITE_IOERR_RDLOCK (SQLITE_IOERR | (9<<8)) -#define SQLITE_IOERR_DELETE (SQLITE_IOERR | (10<<8)) -#define SQLITE_IOERR_BLOCKED (SQLITE_IOERR | (11<<8)) -#define SQLITE_IOERR_NOMEM (SQLITE_IOERR | (12<<8)) -#define SQLITE_IOERR_ACCESS (SQLITE_IOERR | (13<<8)) -#define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8)) -#define SQLITE_IOERR_LOCK (SQLITE_IOERR | (15<<8)) -#define SQLITE_IOERR_CLOSE (SQLITE_IOERR | (16<<8)) -#define SQLITE_IOERR_DIR_CLOSE (SQLITE_IOERR | (17<<8)) -#define SQLITE_IOERR_SHMOPEN (SQLITE_IOERR | (18<<8)) -#define SQLITE_IOERR_SHMSIZE (SQLITE_IOERR | (19<<8)) -#define SQLITE_IOERR_SHMLOCK (SQLITE_IOERR | (20<<8)) -#define SQLITE_IOERR_SHMMAP (SQLITE_IOERR | (21<<8)) -#define SQLITE_IOERR_SEEK (SQLITE_IOERR | (22<<8)) -#define SQLITE_IOERR_DELETE_NOENT (SQLITE_IOERR | (23<<8)) -#define SQLITE_LOCKED_SHAREDCACHE (SQLITE_LOCKED | (1<<8)) -#define SQLITE_BUSY_RECOVERY (SQLITE_BUSY | (1<<8)) -#define SQLITE_CANTOPEN_NOTEMPDIR (SQLITE_CANTOPEN | (1<<8)) -#define SQLITE_CANTOPEN_ISDIR (SQLITE_CANTOPEN | (2<<8)) -#define SQLITE_CANTOPEN_FULLPATH (SQLITE_CANTOPEN | (3<<8)) -#define SQLITE_CORRUPT_VTAB (SQLITE_CORRUPT | (1<<8)) -#define SQLITE_READONLY_RECOVERY (SQLITE_READONLY | (1<<8)) -#define SQLITE_READONLY_CANTLOCK (SQLITE_READONLY | (2<<8)) -#define SQLITE_READONLY_ROLLBACK (SQLITE_READONLY | (3<<8)) -#define SQLITE_ABORT_ROLLBACK (SQLITE_ABORT | (2<<8)) -#define SQLITE_CONSTRAINT_CHECK (SQLITE_CONSTRAINT | (1<<8)) -#define SQLITE_CONSTRAINT_COMMITHOOK (SQLITE_CONSTRAINT | (2<<8)) -#define SQLITE_CONSTRAINT_FOREIGNKEY (SQLITE_CONSTRAINT | (3<<8)) -#define SQLITE_CONSTRAINT_FUNCTION (SQLITE_CONSTRAINT | (4<<8)) -#define SQLITE_CONSTRAINT_NOTNULL (SQLITE_CONSTRAINT | (5<<8)) -#define SQLITE_CONSTRAINT_PRIMARYKEY (SQLITE_CONSTRAINT | (6<<8)) -#define SQLITE_CONSTRAINT_TRIGGER (SQLITE_CONSTRAINT | (7<<8)) -#define SQLITE_CONSTRAINT_UNIQUE (SQLITE_CONSTRAINT | (8<<8)) -#define SQLITE_CONSTRAINT_VTAB (SQLITE_CONSTRAINT | (9<<8)) - -/* -** CAPI3REF: Flags For File Open Operations -** -** These bit values are intended for use in the -** 3rd parameter to the [sqlite3_open_v2()] interface and -** in the 4th parameter to the [sqlite3_vfs.xOpen] method. -*/ -#define SQLITE_OPEN_READONLY 0x00000001 /* Ok for sqlite3_open_v2() */ -#define SQLITE_OPEN_READWRITE 0x00000002 /* Ok for sqlite3_open_v2() */ -#define SQLITE_OPEN_CREATE 0x00000004 /* Ok for sqlite3_open_v2() */ -#define SQLITE_OPEN_DELETEONCLOSE 0x00000008 /* VFS only */ -#define SQLITE_OPEN_EXCLUSIVE 0x00000010 /* VFS only */ -#define SQLITE_OPEN_AUTOPROXY 0x00000020 /* VFS only */ -#define SQLITE_OPEN_URI 0x00000040 /* Ok for sqlite3_open_v2() */ -#define SQLITE_OPEN_MEMORY 0x00000080 /* Ok for sqlite3_open_v2() */ -#define SQLITE_OPEN_MAIN_DB 0x00000100 /* VFS only */ -#define SQLITE_OPEN_TEMP_DB 0x00000200 /* VFS only */ -#define SQLITE_OPEN_TRANSIENT_DB 0x00000400 /* VFS only */ -#define SQLITE_OPEN_MAIN_JOURNAL 0x00000800 /* VFS only */ -#define SQLITE_OPEN_TEMP_JOURNAL 0x00001000 /* VFS only */ -#define SQLITE_OPEN_SUBJOURNAL 0x00002000 /* VFS only */ -#define SQLITE_OPEN_MASTER_JOURNAL 0x00004000 /* VFS only */ -#define SQLITE_OPEN_NOMUTEX 0x00008000 /* Ok for sqlite3_open_v2() */ -#define SQLITE_OPEN_FULLMUTEX 0x00010000 /* Ok for sqlite3_open_v2() */ -#define SQLITE_OPEN_SHAREDCACHE 0x00020000 /* Ok for sqlite3_open_v2() */ -#define SQLITE_OPEN_PRIVATECACHE 0x00040000 /* Ok for sqlite3_open_v2() */ -#define SQLITE_OPEN_WAL 0x00080000 /* VFS only */ - -/* Reserved: 0x00F00000 */ - -/* -** CAPI3REF: Device Characteristics -** -** The xDeviceCharacteristics method of the [sqlite3_io_methods] -** object returns an integer which is a vector of these -** bit values expressing I/O characteristics of the mass storage -** device that holds the file that the [sqlite3_io_methods] -** refers to. -** -** The SQLITE_IOCAP_ATOMIC property means that all writes of -** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values -** mean that writes of blocks that are nnn bytes in size and -** are aligned to an address which is an integer multiple of -** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means -** that when data is appended to a file, the data is appended -** first then the size of the file is extended, never the other -** way around. The SQLITE_IOCAP_SEQUENTIAL property means that -** information is written to disk in the same order as calls -** to xWrite(). The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that -** after reboot following a crash or power loss, the only bytes in a -** file that were written at the application level might have changed -** and that adjacent bytes, even bytes within the same sector are -** guaranteed to be unchanged. -*/ -#define SQLITE_IOCAP_ATOMIC 0x00000001 -#define SQLITE_IOCAP_ATOMIC512 0x00000002 -#define SQLITE_IOCAP_ATOMIC1K 0x00000004 -#define SQLITE_IOCAP_ATOMIC2K 0x00000008 -#define SQLITE_IOCAP_ATOMIC4K 0x00000010 -#define SQLITE_IOCAP_ATOMIC8K 0x00000020 -#define SQLITE_IOCAP_ATOMIC16K 0x00000040 -#define SQLITE_IOCAP_ATOMIC32K 0x00000080 -#define SQLITE_IOCAP_ATOMIC64K 0x00000100 -#define SQLITE_IOCAP_SAFE_APPEND 0x00000200 -#define SQLITE_IOCAP_SEQUENTIAL 0x00000400 -#define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN 0x00000800 -#define SQLITE_IOCAP_POWERSAFE_OVERWRITE 0x00001000 - -/* -** CAPI3REF: File Locking Levels -** -** SQLite uses one of these integer values as the second -** argument to calls it makes to the xLock() and xUnlock() methods -** of an [sqlite3_io_methods] object. -*/ -#define SQLITE_LOCK_NONE 0 -#define SQLITE_LOCK_SHARED 1 -#define SQLITE_LOCK_RESERVED 2 -#define SQLITE_LOCK_PENDING 3 -#define SQLITE_LOCK_EXCLUSIVE 4 - -/* -** CAPI3REF: Synchronization Type Flags -** -** When SQLite invokes the xSync() method of an -** [sqlite3_io_methods] object it uses a combination of -** these integer values as the second argument. -** -** When the SQLITE_SYNC_DATAONLY flag is used, it means that the -** sync operation only needs to flush data to mass storage. Inode -** information need not be flushed. If the lower four bits of the flag -** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics. -** If the lower four bits equal SQLITE_SYNC_FULL, that means -** to use Mac OS X style fullsync instead of fsync(). -** -** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags -** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL -** settings. The [synchronous pragma] determines when calls to the -** xSync VFS method occur and applies uniformly across all platforms. -** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how -** energetic or rigorous or forceful the sync operations are and -** only make a difference on Mac OSX for the default SQLite code. -** (Third-party VFS implementations might also make the distinction -** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the -** operating systems natively supported by SQLite, only Mac OSX -** cares about the difference.) -*/ -#define SQLITE_SYNC_NORMAL 0x00002 -#define SQLITE_SYNC_FULL 0x00003 -#define SQLITE_SYNC_DATAONLY 0x00010 - -/* -** CAPI3REF: OS Interface Open File Handle -** -** An [sqlite3_file] object represents an open file in the -** [sqlite3_vfs | OS interface layer]. Individual OS interface -** implementations will -** want to subclass this object by appending additional fields -** for their own use. The pMethods entry is a pointer to an -** [sqlite3_io_methods] object that defines methods for performing -** I/O operations on the open file. -*/ -typedef struct sqlite3_file sqlite3_file; -struct sqlite3_file { - const struct sqlite3_io_methods *pMethods; /* Methods for an open file */ -}; - -/* -** CAPI3REF: OS Interface File Virtual Methods Object -** -** Every file opened by the [sqlite3_vfs.xOpen] method populates an -** [sqlite3_file] object (or, more commonly, a subclass of the -** [sqlite3_file] object) with a pointer to an instance of this object. -** This object defines the methods used to perform various operations -** against the open file represented by the [sqlite3_file] object. -** -** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element -** to a non-NULL pointer, then the sqlite3_io_methods.xClose method -** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed. The -** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen] -** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element -** to NULL. -** -** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or -** [SQLITE_SYNC_FULL]. The first choice is the normal fsync(). -** The second choice is a Mac OS X style fullsync. The [SQLITE_SYNC_DATAONLY] -** flag may be ORed in to indicate that only the data of the file -** and not its inode needs to be synced. -** -** The integer values to xLock() and xUnlock() are one of -**
      -**
    • [SQLITE_LOCK_NONE], -**
    • [SQLITE_LOCK_SHARED], -**
    • [SQLITE_LOCK_RESERVED], -**
    • [SQLITE_LOCK_PENDING], or -**
    • [SQLITE_LOCK_EXCLUSIVE]. -**
    -** xLock() increases the lock. xUnlock() decreases the lock. -** The xCheckReservedLock() method checks whether any database connection, -** either in this process or in some other process, is holding a RESERVED, -** PENDING, or EXCLUSIVE lock on the file. It returns true -** if such a lock exists and false otherwise. -** -** The xFileControl() method is a generic interface that allows custom -** VFS implementations to directly control an open file using the -** [sqlite3_file_control()] interface. The second "op" argument is an -** integer opcode. The third argument is a generic pointer intended to -** point to a structure that may contain arguments or space in which to -** write return values. Potential uses for xFileControl() might be -** functions to enable blocking locks with timeouts, to change the -** locking strategy (for example to use dot-file locks), to inquire -** about the status of a lock, or to break stale locks. The SQLite -** core reserves all opcodes less than 100 for its own use. -** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available. -** Applications that define a custom xFileControl method should use opcodes -** greater than 100 to avoid conflicts. VFS implementations should -** return [SQLITE_NOTFOUND] for file control opcodes that they do not -** recognize. -** -** The xSectorSize() method returns the sector size of the -** device that underlies the file. The sector size is the -** minimum write that can be performed without disturbing -** other bytes in the file. The xDeviceCharacteristics() -** method returns a bit vector describing behaviors of the -** underlying device: -** -**
      -**
    • [SQLITE_IOCAP_ATOMIC] -**
    • [SQLITE_IOCAP_ATOMIC512] -**
    • [SQLITE_IOCAP_ATOMIC1K] -**
    • [SQLITE_IOCAP_ATOMIC2K] -**
    • [SQLITE_IOCAP_ATOMIC4K] -**
    • [SQLITE_IOCAP_ATOMIC8K] -**
    • [SQLITE_IOCAP_ATOMIC16K] -**
    • [SQLITE_IOCAP_ATOMIC32K] -**
    • [SQLITE_IOCAP_ATOMIC64K] -**
    • [SQLITE_IOCAP_SAFE_APPEND] -**
    • [SQLITE_IOCAP_SEQUENTIAL] -**
    -** -** The SQLITE_IOCAP_ATOMIC property means that all writes of -** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values -** mean that writes of blocks that are nnn bytes in size and -** are aligned to an address which is an integer multiple of -** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means -** that when data is appended to a file, the data is appended -** first then the size of the file is extended, never the other -** way around. The SQLITE_IOCAP_SEQUENTIAL property means that -** information is written to disk in the same order as calls -** to xWrite(). -** -** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill -** in the unread portions of the buffer with zeros. A VFS that -** fails to zero-fill short reads might seem to work. However, -** failure to zero-fill short reads will eventually lead to -** database corruption. -*/ -typedef struct sqlite3_io_methods sqlite3_io_methods; -struct sqlite3_io_methods { - int iVersion; - int (*xClose)(sqlite3_file*); - int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst); - int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst); - int (*xTruncate)(sqlite3_file*, sqlite3_int64 size); - int (*xSync)(sqlite3_file*, int flags); - int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize); - int (*xLock)(sqlite3_file*, int); - int (*xUnlock)(sqlite3_file*, int); - int (*xCheckReservedLock)(sqlite3_file*, int *pResOut); - int (*xFileControl)(sqlite3_file*, int op, void *pArg); - int (*xSectorSize)(sqlite3_file*); - int (*xDeviceCharacteristics)(sqlite3_file*); - /* Methods above are valid for version 1 */ - int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**); - int (*xShmLock)(sqlite3_file*, int offset, int n, int flags); - void (*xShmBarrier)(sqlite3_file*); - int (*xShmUnmap)(sqlite3_file*, int deleteFlag); - /* Methods above are valid for version 2 */ - /* Additional methods may be added in future releases */ -}; - -/* -** CAPI3REF: Standard File Control Opcodes -** -** These integer constants are opcodes for the xFileControl method -** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()] -** interface. -** -** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging. This -** opcode causes the xFileControl method to write the current state of -** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED], -** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE]) -** into an integer that the pArg argument points to. This capability -** is used during testing and only needs to be supported when SQLITE_TEST -** is defined. -**
      -**
    • [[SQLITE_FCNTL_SIZE_HINT]] -** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS -** layer a hint of how large the database file will grow to be during the -** current transaction. This hint is not guaranteed to be accurate but it -** is often close. The underlying VFS might choose to preallocate database -** file space based on this hint in order to help writes to the database -** file run faster. -** -**
    • [[SQLITE_FCNTL_CHUNK_SIZE]] -** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS -** extends and truncates the database file in chunks of a size specified -** by the user. The fourth argument to [sqlite3_file_control()] should -** point to an integer (type int) containing the new chunk-size to use -** for the nominated database. Allocating database file space in large -** chunks (say 1MB at a time), may reduce file-system fragmentation and -** improve performance on some systems. -** -**
    • [[SQLITE_FCNTL_FILE_POINTER]] -** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer -** to the [sqlite3_file] object associated with a particular database -** connection. See the [sqlite3_file_control()] documentation for -** additional information. -** -**
    • [[SQLITE_FCNTL_SYNC_OMITTED]] -** ^(The [SQLITE_FCNTL_SYNC_OMITTED] opcode is generated internally by -** SQLite and sent to all VFSes in place of a call to the xSync method -** when the database connection has [PRAGMA synchronous] set to OFF.)^ -** Some specialized VFSes need this signal in order to operate correctly -** when [PRAGMA synchronous | PRAGMA synchronous=OFF] is set, but most -** VFSes do not need this signal and should silently ignore this opcode. -** Applications should not call [sqlite3_file_control()] with this -** opcode as doing so may disrupt the operation of the specialized VFSes -** that do require it. -** -**
    • [[SQLITE_FCNTL_WIN32_AV_RETRY]] -** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic -** retry counts and intervals for certain disk I/O operations for the -** windows [VFS] in order to provide robustness in the presence of -** anti-virus programs. By default, the windows VFS will retry file read, -** file write, and file delete operations up to 10 times, with a delay -** of 25 milliseconds before the first retry and with the delay increasing -** by an additional 25 milliseconds with each subsequent retry. This -** opcode allows these two values (10 retries and 25 milliseconds of delay) -** to be adjusted. The values are changed for all database connections -** within the same process. The argument is a pointer to an array of two -** integers where the first integer i the new retry count and the second -** integer is the delay. If either integer is negative, then the setting -** is not changed but instead the prior value of that setting is written -** into the array entry, allowing the current retry settings to be -** interrogated. The zDbName parameter is ignored. -** -**
    • [[SQLITE_FCNTL_PERSIST_WAL]] -** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the -** persistent [WAL | Write Ahead Log] setting. By default, the auxiliary -** write ahead log and shared memory files used for transaction control -** are automatically deleted when the latest connection to the database -** closes. Setting persistent WAL mode causes those files to persist after -** close. Persisting the files is useful when other processes that do not -** have write permission on the directory containing the database file want -** to read the database file, as the WAL and shared memory files must exist -** in order for the database to be readable. The fourth parameter to -** [sqlite3_file_control()] for this opcode should be a pointer to an integer. -** That integer is 0 to disable persistent WAL mode or 1 to enable persistent -** WAL mode. If the integer is -1, then it is overwritten with the current -** WAL persistence setting. -** -**
    • [[SQLITE_FCNTL_POWERSAFE_OVERWRITE]] -** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the -** persistent "powersafe-overwrite" or "PSOW" setting. The PSOW setting -** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the -** xDeviceCharacteristics methods. The fourth parameter to -** [sqlite3_file_control()] for this opcode should be a pointer to an integer. -** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage -** mode. If the integer is -1, then it is overwritten with the current -** zero-damage mode setting. -** -**
    • [[SQLITE_FCNTL_OVERWRITE]] -** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening -** a write transaction to indicate that, unless it is rolled back for some -** reason, the entire database file will be overwritten by the current -** transaction. This is used by VACUUM operations. -** -**
    • [[SQLITE_FCNTL_VFSNAME]] -** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of -** all [VFSes] in the VFS stack. The names are of all VFS shims and the -** final bottom-level VFS are written into memory obtained from -** [sqlite3_malloc()] and the result is stored in the char* variable -** that the fourth parameter of [sqlite3_file_control()] points to. -** The caller is responsible for freeing the memory when done. As with -** all file-control actions, there is no guarantee that this will actually -** do anything. Callers should initialize the char* variable to a NULL -** pointer in case this file-control is not implemented. This file-control -** is intended for diagnostic use only. -** -**
    • [[SQLITE_FCNTL_PRAGMA]] -** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA] -** file control is sent to the open [sqlite3_file] object corresponding -** to the database file to which the pragma statement refers. ^The argument -** to the [SQLITE_FCNTL_PRAGMA] file control is an array of -** pointers to strings (char**) in which the second element of the array -** is the name of the pragma and the third element is the argument to the -** pragma or NULL if the pragma has no argument. ^The handler for an -** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element -** of the char** argument point to a string obtained from [sqlite3_mprintf()] -** or the equivalent and that string will become the result of the pragma or -** the error message if the pragma fails. ^If the -** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal -** [PRAGMA] processing continues. ^If the [SQLITE_FCNTL_PRAGMA] -** file control returns [SQLITE_OK], then the parser assumes that the -** VFS has handled the PRAGMA itself and the parser generates a no-op -** prepared statement. ^If the [SQLITE_FCNTL_PRAGMA] file control returns -** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means -** that the VFS encountered an error while handling the [PRAGMA] and the -** compilation of the PRAGMA fails with an error. ^The [SQLITE_FCNTL_PRAGMA] -** file control occurs at the beginning of pragma statement analysis and so -** it is able to override built-in [PRAGMA] statements. -** -**
    • [[SQLITE_FCNTL_BUSYHANDLER]] -** ^This file-control may be invoked by SQLite on the database file handle -** shortly after it is opened in order to provide a custom VFS with access -** to the connections busy-handler callback. The argument is of type (void **) -** - an array of two (void *) values. The first (void *) actually points -** to a function of type (int (*)(void *)). In order to invoke the connections -** busy-handler, this function should be invoked with the second (void *) in -** the array as the only argument. If it returns non-zero, then the operation -** should be retried. If it returns zero, the custom VFS should abandon the -** current operation. -** -**
    • [[SQLITE_FCNTL_TEMPFILENAME]] -** ^Application can invoke this file-control to have SQLite generate a -** temporary filename using the same algorithm that is followed to generate -** temporary filenames for TEMP tables and other internal uses. The -** argument should be a char** which will be filled with the filename -** written into memory obtained from [sqlite3_malloc()]. The caller should -** invoke [sqlite3_free()] on the result to avoid a memory leak. -** -**
    -*/ -#define SQLITE_FCNTL_LOCKSTATE 1 -#define SQLITE_GET_LOCKPROXYFILE 2 -#define SQLITE_SET_LOCKPROXYFILE 3 -#define SQLITE_LAST_ERRNO 4 -#define SQLITE_FCNTL_SIZE_HINT 5 -#define SQLITE_FCNTL_CHUNK_SIZE 6 -#define SQLITE_FCNTL_FILE_POINTER 7 -#define SQLITE_FCNTL_SYNC_OMITTED 8 -#define SQLITE_FCNTL_WIN32_AV_RETRY 9 -#define SQLITE_FCNTL_PERSIST_WAL 10 -#define SQLITE_FCNTL_OVERWRITE 11 -#define SQLITE_FCNTL_VFSNAME 12 -#define SQLITE_FCNTL_POWERSAFE_OVERWRITE 13 -#define SQLITE_FCNTL_PRAGMA 14 -#define SQLITE_FCNTL_BUSYHANDLER 15 -#define SQLITE_FCNTL_TEMPFILENAME 16 - -/* -** CAPI3REF: Mutex Handle -** -** The mutex module within SQLite defines [sqlite3_mutex] to be an -** abstract type for a mutex object. The SQLite core never looks -** at the internal representation of an [sqlite3_mutex]. It only -** deals with pointers to the [sqlite3_mutex] object. -** -** Mutexes are created using [sqlite3_mutex_alloc()]. -*/ -typedef struct sqlite3_mutex sqlite3_mutex; - -/* -** CAPI3REF: OS Interface Object -** -** An instance of the sqlite3_vfs object defines the interface between -** the SQLite core and the underlying operating system. The "vfs" -** in the name of the object stands for "virtual file system". See -** the [VFS | VFS documentation] for further information. -** -** The value of the iVersion field is initially 1 but may be larger in -** future versions of SQLite. Additional fields may be appended to this -** object when the iVersion value is increased. Note that the structure -** of the sqlite3_vfs object changes in the transaction between -** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not -** modified. -** -** The szOsFile field is the size of the subclassed [sqlite3_file] -** structure used by this VFS. mxPathname is the maximum length of -** a pathname in this VFS. -** -** Registered sqlite3_vfs objects are kept on a linked list formed by -** the pNext pointer. The [sqlite3_vfs_register()] -** and [sqlite3_vfs_unregister()] interfaces manage this list -** in a thread-safe way. The [sqlite3_vfs_find()] interface -** searches the list. Neither the application code nor the VFS -** implementation should use the pNext pointer. -** -** The pNext field is the only field in the sqlite3_vfs -** structure that SQLite will ever modify. SQLite will only access -** or modify this field while holding a particular static mutex. -** The application should never modify anything within the sqlite3_vfs -** object once the object has been registered. -** -** The zName field holds the name of the VFS module. The name must -** be unique across all VFS modules. -** -** [[sqlite3_vfs.xOpen]] -** ^SQLite guarantees that the zFilename parameter to xOpen -** is either a NULL pointer or string obtained -** from xFullPathname() with an optional suffix added. -** ^If a suffix is added to the zFilename parameter, it will -** consist of a single "-" character followed by no more than -** 11 alphanumeric and/or "-" characters. -** ^SQLite further guarantees that -** the string will be valid and unchanged until xClose() is -** called. Because of the previous sentence, -** the [sqlite3_file] can safely store a pointer to the -** filename if it needs to remember the filename for some reason. -** If the zFilename parameter to xOpen is a NULL pointer then xOpen -** must invent its own temporary name for the file. ^Whenever the -** xFilename parameter is NULL it will also be the case that the -** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE]. -** -** The flags argument to xOpen() includes all bits set in -** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()] -** or [sqlite3_open16()] is used, then flags includes at least -** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. -** If xOpen() opens a file read-only then it sets *pOutFlags to -** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be set. -** -** ^(SQLite will also add one of the following flags to the xOpen() -** call, depending on the object being opened: -** -**
      -**
    • [SQLITE_OPEN_MAIN_DB] -**
    • [SQLITE_OPEN_MAIN_JOURNAL] -**
    • [SQLITE_OPEN_TEMP_DB] -**
    • [SQLITE_OPEN_TEMP_JOURNAL] -**
    • [SQLITE_OPEN_TRANSIENT_DB] -**
    • [SQLITE_OPEN_SUBJOURNAL] -**
    • [SQLITE_OPEN_MASTER_JOURNAL] -**
    • [SQLITE_OPEN_WAL] -**
    )^ -** -** The file I/O implementation can use the object type flags to -** change the way it deals with files. For example, an application -** that does not care about crash recovery or rollback might make -** the open of a journal file a no-op. Writes to this journal would -** also be no-ops, and any attempt to read the journal would return -** SQLITE_IOERR. Or the implementation might recognize that a database -** file will be doing page-aligned sector reads and writes in a random -** order and set up its I/O subsystem accordingly. -** -** SQLite might also add one of the following flags to the xOpen method: -** -**
      -**
    • [SQLITE_OPEN_DELETEONCLOSE] -**
    • [SQLITE_OPEN_EXCLUSIVE] -**
    -** -** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be -** deleted when it is closed. ^The [SQLITE_OPEN_DELETEONCLOSE] -** will be set for TEMP databases and their journals, transient -** databases, and subjournals. -** -** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction -** with the [SQLITE_OPEN_CREATE] flag, which are both directly -** analogous to the O_EXCL and O_CREAT flags of the POSIX open() -** API. The SQLITE_OPEN_EXCLUSIVE flag, when paired with the -** SQLITE_OPEN_CREATE, is used to indicate that file should always -** be created, and that it is an error if it already exists. -** It is not used to indicate the file should be opened -** for exclusive access. -** -** ^At least szOsFile bytes of memory are allocated by SQLite -** to hold the [sqlite3_file] structure passed as the third -** argument to xOpen. The xOpen method does not have to -** allocate the structure; it should just fill it in. Note that -** the xOpen method must set the sqlite3_file.pMethods to either -** a valid [sqlite3_io_methods] object or to NULL. xOpen must do -** this even if the open fails. SQLite expects that the sqlite3_file.pMethods -** element will be valid after xOpen returns regardless of the success -** or failure of the xOpen call. -** -** [[sqlite3_vfs.xAccess]] -** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS] -** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to -** test whether a file is readable and writable, or [SQLITE_ACCESS_READ] -** to test whether a file is at least readable. The file can be a -** directory. -** -** ^SQLite will always allocate at least mxPathname+1 bytes for the -** output buffer xFullPathname. The exact size of the output buffer -** is also passed as a parameter to both methods. If the output buffer -** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is -** handled as a fatal error by SQLite, vfs implementations should endeavor -** to prevent this by setting mxPathname to a sufficiently large value. -** -** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64() -** interfaces are not strictly a part of the filesystem, but they are -** included in the VFS structure for completeness. -** The xRandomness() function attempts to return nBytes bytes -** of good-quality randomness into zOut. The return value is -** the actual number of bytes of randomness obtained. -** The xSleep() method causes the calling thread to sleep for at -** least the number of microseconds given. ^The xCurrentTime() -** method returns a Julian Day Number for the current date and time as -** a floating point value. -** ^The xCurrentTimeInt64() method returns, as an integer, the Julian -** Day Number multiplied by 86400000 (the number of milliseconds in -** a 24-hour day). -** ^SQLite will use the xCurrentTimeInt64() method to get the current -** date and time if that method is available (if iVersion is 2 or -** greater and the function pointer is not NULL) and will fall back -** to xCurrentTime() if xCurrentTimeInt64() is unavailable. -** -** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces -** are not used by the SQLite core. These optional interfaces are provided -** by some VFSes to facilitate testing of the VFS code. By overriding -** system calls with functions under its control, a test program can -** simulate faults and error conditions that would otherwise be difficult -** or impossible to induce. The set of system calls that can be overridden -** varies from one VFS to another, and from one version of the same VFS to the -** next. Applications that use these interfaces must be prepared for any -** or all of these interfaces to be NULL or for their behavior to change -** from one release to the next. Applications must not attempt to access -** any of these methods if the iVersion of the VFS is less than 3. -*/ -typedef struct sqlite3_vfs sqlite3_vfs; -typedef void (*sqlite3_syscall_ptr)(void); -struct sqlite3_vfs { - int iVersion; /* Structure version number (currently 3) */ - int szOsFile; /* Size of subclassed sqlite3_file */ - int mxPathname; /* Maximum file pathname length */ - sqlite3_vfs *pNext; /* Next registered VFS */ - const char *zName; /* Name of this virtual file system */ - void *pAppData; /* Pointer to application-specific data */ - int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*, - int flags, int *pOutFlags); - int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir); - int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut); - int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut); - void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename); - void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg); - void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void); - void (*xDlClose)(sqlite3_vfs*, void*); - int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut); - int (*xSleep)(sqlite3_vfs*, int microseconds); - int (*xCurrentTime)(sqlite3_vfs*, double*); - int (*xGetLastError)(sqlite3_vfs*, int, char *); - /* - ** The methods above are in version 1 of the sqlite_vfs object - ** definition. Those that follow are added in version 2 or later - */ - int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*); - /* - ** The methods above are in versions 1 and 2 of the sqlite_vfs object. - ** Those below are for version 3 and greater. - */ - int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr); - sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName); - const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName); - /* - ** The methods above are in versions 1 through 3 of the sqlite_vfs object. - ** New fields may be appended in figure versions. The iVersion - ** value will increment whenever this happens. - */ -}; - -/* -** CAPI3REF: Flags for the xAccess VFS method -** -** These integer constants can be used as the third parameter to -** the xAccess method of an [sqlite3_vfs] object. They determine -** what kind of permissions the xAccess method is looking for. -** With SQLITE_ACCESS_EXISTS, the xAccess method -** simply checks whether the file exists. -** With SQLITE_ACCESS_READWRITE, the xAccess method -** checks whether the named directory is both readable and writable -** (in other words, if files can be added, removed, and renamed within -** the directory). -** The SQLITE_ACCESS_READWRITE constant is currently used only by the -** [temp_store_directory pragma], though this could change in a future -** release of SQLite. -** With SQLITE_ACCESS_READ, the xAccess method -** checks whether the file is readable. The SQLITE_ACCESS_READ constant is -** currently unused, though it might be used in a future release of -** SQLite. -*/ -#define SQLITE_ACCESS_EXISTS 0 -#define SQLITE_ACCESS_READWRITE 1 /* Used by PRAGMA temp_store_directory */ -#define SQLITE_ACCESS_READ 2 /* Unused */ - -/* -** CAPI3REF: Flags for the xShmLock VFS method -** -** These integer constants define the various locking operations -** allowed by the xShmLock method of [sqlite3_io_methods]. The -** following are the only legal combinations of flags to the -** xShmLock method: -** -**
      -**
    • SQLITE_SHM_LOCK | SQLITE_SHM_SHARED -**
    • SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE -**
    • SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED -**
    • SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE -**
    -** -** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as -** was given no the corresponding lock. -** -** The xShmLock method can transition between unlocked and SHARED or -** between unlocked and EXCLUSIVE. It cannot transition between SHARED -** and EXCLUSIVE. -*/ -#define SQLITE_SHM_UNLOCK 1 -#define SQLITE_SHM_LOCK 2 -#define SQLITE_SHM_SHARED 4 -#define SQLITE_SHM_EXCLUSIVE 8 - -/* -** CAPI3REF: Maximum xShmLock index -** -** The xShmLock method on [sqlite3_io_methods] may use values -** between 0 and this upper bound as its "offset" argument. -** The SQLite core will never attempt to acquire or release a -** lock outside of this range -*/ -#define SQLITE_SHM_NLOCK 8 - - -/* -** CAPI3REF: Initialize The SQLite Library -** -** ^The sqlite3_initialize() routine initializes the -** SQLite library. ^The sqlite3_shutdown() routine -** deallocates any resources that were allocated by sqlite3_initialize(). -** These routines are designed to aid in process initialization and -** shutdown on embedded systems. Workstation applications using -** SQLite normally do not need to invoke either of these routines. -** -** A call to sqlite3_initialize() is an "effective" call if it is -** the first time sqlite3_initialize() is invoked during the lifetime of -** the process, or if it is the first time sqlite3_initialize() is invoked -** following a call to sqlite3_shutdown(). ^(Only an effective call -** of sqlite3_initialize() does any initialization. All other calls -** are harmless no-ops.)^ -** -** A call to sqlite3_shutdown() is an "effective" call if it is the first -** call to sqlite3_shutdown() since the last sqlite3_initialize(). ^(Only -** an effective call to sqlite3_shutdown() does any deinitialization. -** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^ -** -** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown() -** is not. The sqlite3_shutdown() interface must only be called from a -** single thread. All open [database connections] must be closed and all -** other SQLite resources must be deallocated prior to invoking -** sqlite3_shutdown(). -** -** Among other things, ^sqlite3_initialize() will invoke -** sqlite3_os_init(). Similarly, ^sqlite3_shutdown() -** will invoke sqlite3_os_end(). -** -** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success. -** ^If for some reason, sqlite3_initialize() is unable to initialize -** the library (perhaps it is unable to allocate a needed resource such -** as a mutex) it returns an [error code] other than [SQLITE_OK]. -** -** ^The sqlite3_initialize() routine is called internally by many other -** SQLite interfaces so that an application usually does not need to -** invoke sqlite3_initialize() directly. For example, [sqlite3_open()] -** calls sqlite3_initialize() so the SQLite library will be automatically -** initialized when [sqlite3_open()] is called if it has not be initialized -** already. ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT] -** compile-time option, then the automatic calls to sqlite3_initialize() -** are omitted and the application must call sqlite3_initialize() directly -** prior to using any other SQLite interface. For maximum portability, -** it is recommended that applications always invoke sqlite3_initialize() -** directly prior to using any other SQLite interface. Future releases -** of SQLite may require this. In other words, the behavior exhibited -** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the -** default behavior in some future release of SQLite. -** -** The sqlite3_os_init() routine does operating-system specific -** initialization of the SQLite library. The sqlite3_os_end() -** routine undoes the effect of sqlite3_os_init(). Typical tasks -** performed by these routines include allocation or deallocation -** of static resources, initialization of global variables, -** setting up a default [sqlite3_vfs] module, or setting up -** a default configuration using [sqlite3_config()]. -** -** The application should never invoke either sqlite3_os_init() -** or sqlite3_os_end() directly. The application should only invoke -** sqlite3_initialize() and sqlite3_shutdown(). The sqlite3_os_init() -** interface is called automatically by sqlite3_initialize() and -** sqlite3_os_end() is called by sqlite3_shutdown(). Appropriate -** implementations for sqlite3_os_init() and sqlite3_os_end() -** are built into SQLite when it is compiled for Unix, Windows, or OS/2. -** When [custom builds | built for other platforms] -** (using the [SQLITE_OS_OTHER=1] compile-time -** option) the application must supply a suitable implementation for -** sqlite3_os_init() and sqlite3_os_end(). An application-supplied -** implementation of sqlite3_os_init() or sqlite3_os_end() -** must return [SQLITE_OK] on success and some other [error code] upon -** failure. -*/ -SQLITE_API int sqlite3_initialize(void); -SQLITE_API int sqlite3_shutdown(void); -SQLITE_API int sqlite3_os_init(void); -SQLITE_API int sqlite3_os_end(void); - -/* -** CAPI3REF: Configuring The SQLite Library -** -** The sqlite3_config() interface is used to make global configuration -** changes to SQLite in order to tune SQLite to the specific needs of -** the application. The default configuration is recommended for most -** applications and so this routine is usually not necessary. It is -** provided to support rare applications with unusual needs. -** -** The sqlite3_config() interface is not threadsafe. The application -** must insure that no other SQLite interfaces are invoked by other -** threads while sqlite3_config() is running. Furthermore, sqlite3_config() -** may only be invoked prior to library initialization using -** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()]. -** ^If sqlite3_config() is called after [sqlite3_initialize()] and before -** [sqlite3_shutdown()] then it will return SQLITE_MISUSE. -** Note, however, that ^sqlite3_config() can be called as part of the -** implementation of an application-defined [sqlite3_os_init()]. -** -** The first argument to sqlite3_config() is an integer -** [configuration option] that determines -** what property of SQLite is to be configured. Subsequent arguments -** vary depending on the [configuration option] -** in the first argument. -** -** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK]. -** ^If the option is unknown or SQLite is unable to set the option -** then this routine returns a non-zero [error code]. -*/ -SQLITE_API int sqlite3_config(int, ...); - -/* -** CAPI3REF: Configure database connections -** -** The sqlite3_db_config() interface is used to make configuration -** changes to a [database connection]. The interface is similar to -** [sqlite3_config()] except that the changes apply to a single -** [database connection] (specified in the first argument). -** -** The second argument to sqlite3_db_config(D,V,...) is the -** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code -** that indicates what aspect of the [database connection] is being configured. -** Subsequent arguments vary depending on the configuration verb. -** -** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if -** the call is considered successful. -*/ -SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...); - -/* -** CAPI3REF: Memory Allocation Routines -** -** An instance of this object defines the interface between SQLite -** and low-level memory allocation routines. -** -** This object is used in only one place in the SQLite interface. -** A pointer to an instance of this object is the argument to -** [sqlite3_config()] when the configuration option is -** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC]. -** By creating an instance of this object -** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC]) -** during configuration, an application can specify an alternative -** memory allocation subsystem for SQLite to use for all of its -** dynamic memory needs. -** -** Note that SQLite comes with several [built-in memory allocators] -** that are perfectly adequate for the overwhelming majority of applications -** and that this object is only useful to a tiny minority of applications -** with specialized memory allocation requirements. This object is -** also used during testing of SQLite in order to specify an alternative -** memory allocator that simulates memory out-of-memory conditions in -** order to verify that SQLite recovers gracefully from such -** conditions. -** -** The xMalloc, xRealloc, and xFree methods must work like the -** malloc(), realloc() and free() functions from the standard C library. -** ^SQLite guarantees that the second argument to -** xRealloc is always a value returned by a prior call to xRoundup. -** -** xSize should return the allocated size of a memory allocation -** previously obtained from xMalloc or xRealloc. The allocated size -** is always at least as big as the requested size but may be larger. -** -** The xRoundup method returns what would be the allocated size of -** a memory allocation given a particular requested size. Most memory -** allocators round up memory allocations at least to the next multiple -** of 8. Some allocators round up to a larger multiple or to a power of 2. -** Every memory allocation request coming in through [sqlite3_malloc()] -** or [sqlite3_realloc()] first calls xRoundup. If xRoundup returns 0, -** that causes the corresponding memory allocation to fail. -** -** The xInit method initializes the memory allocator. (For example, -** it might allocate any require mutexes or initialize internal data -** structures. The xShutdown method is invoked (indirectly) by -** [sqlite3_shutdown()] and should deallocate any resources acquired -** by xInit. The pAppData pointer is used as the only parameter to -** xInit and xShutdown. -** -** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes -** the xInit method, so the xInit method need not be threadsafe. The -** xShutdown method is only called from [sqlite3_shutdown()] so it does -** not need to be threadsafe either. For all other methods, SQLite -** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the -** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which -** it is by default) and so the methods are automatically serialized. -** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other -** methods must be threadsafe or else make their own arrangements for -** serialization. -** -** SQLite will never invoke xInit() more than once without an intervening -** call to xShutdown(). -*/ -typedef struct sqlite3_mem_methods sqlite3_mem_methods; -struct sqlite3_mem_methods { - void *(*xMalloc)(int); /* Memory allocation function */ - void (*xFree)(void*); /* Free a prior allocation */ - void *(*xRealloc)(void*,int); /* Resize an allocation */ - int (*xSize)(void*); /* Return the size of an allocation */ - int (*xRoundup)(int); /* Round up request size to allocation size */ - int (*xInit)(void*); /* Initialize the memory allocator */ - void (*xShutdown)(void*); /* Deinitialize the memory allocator */ - void *pAppData; /* Argument to xInit() and xShutdown() */ -}; - -/* -** CAPI3REF: Configuration Options -** KEYWORDS: {configuration option} -** -** These constants are the available integer configuration options that -** can be passed as the first argument to the [sqlite3_config()] interface. -** -** New configuration options may be added in future releases of SQLite. -** Existing configuration options might be discontinued. Applications -** should check the return code from [sqlite3_config()] to make sure that -** the call worked. The [sqlite3_config()] interface will return a -** non-zero [error code] if a discontinued or unsupported configuration option -** is invoked. -** -**
    -** [[SQLITE_CONFIG_SINGLETHREAD]]
    SQLITE_CONFIG_SINGLETHREAD
    -**
    There are no arguments to this option. ^This option sets the -** [threading mode] to Single-thread. In other words, it disables -** all mutexing and puts SQLite into a mode where it can only be used -** by a single thread. ^If SQLite is compiled with -** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then -** it is not possible to change the [threading mode] from its default -** value of Single-thread and so [sqlite3_config()] will return -** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD -** configuration option.
    -** -** [[SQLITE_CONFIG_MULTITHREAD]]
    SQLITE_CONFIG_MULTITHREAD
    -**
    There are no arguments to this option. ^This option sets the -** [threading mode] to Multi-thread. In other words, it disables -** mutexing on [database connection] and [prepared statement] objects. -** The application is responsible for serializing access to -** [database connections] and [prepared statements]. But other mutexes -** are enabled so that SQLite will be safe to use in a multi-threaded -** environment as long as no two threads attempt to use the same -** [database connection] at the same time. ^If SQLite is compiled with -** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then -** it is not possible to set the Multi-thread [threading mode] and -** [sqlite3_config()] will return [SQLITE_ERROR] if called with the -** SQLITE_CONFIG_MULTITHREAD configuration option.
    -** -** [[SQLITE_CONFIG_SERIALIZED]]
    SQLITE_CONFIG_SERIALIZED
    -**
    There are no arguments to this option. ^This option sets the -** [threading mode] to Serialized. In other words, this option enables -** all mutexes including the recursive -** mutexes on [database connection] and [prepared statement] objects. -** In this mode (which is the default when SQLite is compiled with -** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access -** to [database connections] and [prepared statements] so that the -** application is free to use the same [database connection] or the -** same [prepared statement] in different threads at the same time. -** ^If SQLite is compiled with -** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then -** it is not possible to set the Serialized [threading mode] and -** [sqlite3_config()] will return [SQLITE_ERROR] if called with the -** SQLITE_CONFIG_SERIALIZED configuration option.
    -** -** [[SQLITE_CONFIG_MALLOC]]
    SQLITE_CONFIG_MALLOC
    -**
    ^(This option takes a single argument which is a pointer to an -** instance of the [sqlite3_mem_methods] structure. The argument specifies -** alternative low-level memory allocation routines to be used in place of -** the memory allocation routines built into SQLite.)^ ^SQLite makes -** its own private copy of the content of the [sqlite3_mem_methods] structure -** before the [sqlite3_config()] call returns.
    -** -** [[SQLITE_CONFIG_GETMALLOC]]
    SQLITE_CONFIG_GETMALLOC
    -**
    ^(This option takes a single argument which is a pointer to an -** instance of the [sqlite3_mem_methods] structure. The [sqlite3_mem_methods] -** structure is filled with the currently defined memory allocation routines.)^ -** This option can be used to overload the default memory allocation -** routines with a wrapper that simulations memory allocation failure or -** tracks memory usage, for example.
    -** -** [[SQLITE_CONFIG_MEMSTATUS]]
    SQLITE_CONFIG_MEMSTATUS
    -**
    ^This option takes single argument of type int, interpreted as a -** boolean, which enables or disables the collection of memory allocation -** statistics. ^(When memory allocation statistics are disabled, the -** following SQLite interfaces become non-operational: -**
      -**
    • [sqlite3_memory_used()] -**
    • [sqlite3_memory_highwater()] -**
    • [sqlite3_soft_heap_limit64()] -**
    • [sqlite3_status()] -**
    )^ -** ^Memory allocation statistics are enabled by default unless SQLite is -** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory -** allocation statistics are disabled by default. -**
    -** -** [[SQLITE_CONFIG_SCRATCH]]
    SQLITE_CONFIG_SCRATCH
    -**
    ^This option specifies a static memory buffer that SQLite can use for -** scratch memory. There are three arguments: A pointer an 8-byte -** aligned memory buffer from which the scratch allocations will be -** drawn, the size of each scratch allocation (sz), -** and the maximum number of scratch allocations (N). The sz -** argument must be a multiple of 16. -** The first argument must be a pointer to an 8-byte aligned buffer -** of at least sz*N bytes of memory. -** ^SQLite will use no more than two scratch buffers per thread. So -** N should be set to twice the expected maximum number of threads. -** ^SQLite will never require a scratch buffer that is more than 6 -** times the database page size. ^If SQLite needs needs additional -** scratch memory beyond what is provided by this configuration option, then -** [sqlite3_malloc()] will be used to obtain the memory needed.
    -** -** [[SQLITE_CONFIG_PAGECACHE]]
    SQLITE_CONFIG_PAGECACHE
    -**
    ^This option specifies a static memory buffer that SQLite can use for -** the database page cache with the default page cache implementation. -** This configuration should not be used if an application-define page -** cache implementation is loaded using the SQLITE_CONFIG_PCACHE2 option. -** There are three arguments to this option: A pointer to 8-byte aligned -** memory, the size of each page buffer (sz), and the number of pages (N). -** The sz argument should be the size of the largest database page -** (a power of two between 512 and 32768) plus a little extra for each -** page header. ^The page header size is 20 to 40 bytes depending on -** the host architecture. ^It is harmless, apart from the wasted memory, -** to make sz a little too large. The first -** argument should point to an allocation of at least sz*N bytes of memory. -** ^SQLite will use the memory provided by the first argument to satisfy its -** memory needs for the first N pages that it adds to cache. ^If additional -** page cache memory is needed beyond what is provided by this option, then -** SQLite goes to [sqlite3_malloc()] for the additional storage space. -** The pointer in the first argument must -** be aligned to an 8-byte boundary or subsequent behavior of SQLite -** will be undefined.
    -** -** [[SQLITE_CONFIG_HEAP]]
    SQLITE_CONFIG_HEAP
    -**
    ^This option specifies a static memory buffer that SQLite will use -** for all of its dynamic memory allocation needs beyond those provided -** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE]. -** There are three arguments: An 8-byte aligned pointer to the memory, -** the number of bytes in the memory buffer, and the minimum allocation size. -** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts -** to using its default memory allocator (the system malloc() implementation), -** undoing any prior invocation of [SQLITE_CONFIG_MALLOC]. ^If the -** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or -** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory -** allocator is engaged to handle all of SQLites memory allocation needs. -** The first pointer (the memory pointer) must be aligned to an 8-byte -** boundary or subsequent behavior of SQLite will be undefined. -** The minimum allocation size is capped at 2**12. Reasonable values -** for the minimum allocation size are 2**5 through 2**8.
    -** -** [[SQLITE_CONFIG_MUTEX]]
    SQLITE_CONFIG_MUTEX
    -**
    ^(This option takes a single argument which is a pointer to an -** instance of the [sqlite3_mutex_methods] structure. The argument specifies -** alternative low-level mutex routines to be used in place -** the mutex routines built into SQLite.)^ ^SQLite makes a copy of the -** content of the [sqlite3_mutex_methods] structure before the call to -** [sqlite3_config()] returns. ^If SQLite is compiled with -** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then -** the entire mutexing subsystem is omitted from the build and hence calls to -** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will -** return [SQLITE_ERROR].
    -** -** [[SQLITE_CONFIG_GETMUTEX]]
    SQLITE_CONFIG_GETMUTEX
    -**
    ^(This option takes a single argument which is a pointer to an -** instance of the [sqlite3_mutex_methods] structure. The -** [sqlite3_mutex_methods] -** structure is filled with the currently defined mutex routines.)^ -** This option can be used to overload the default mutex allocation -** routines with a wrapper used to track mutex usage for performance -** profiling or testing, for example. ^If SQLite is compiled with -** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then -** the entire mutexing subsystem is omitted from the build and hence calls to -** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will -** return [SQLITE_ERROR].
    -** -** [[SQLITE_CONFIG_LOOKASIDE]]
    SQLITE_CONFIG_LOOKASIDE
    -**
    ^(This option takes two arguments that determine the default -** memory allocation for the lookaside memory allocator on each -** [database connection]. The first argument is the -** size of each lookaside buffer slot and the second is the number of -** slots allocated to each database connection.)^ ^(This option sets the -** default lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE] -** verb to [sqlite3_db_config()] can be used to change the lookaside -** configuration on individual connections.)^
    -** -** [[SQLITE_CONFIG_PCACHE2]]
    SQLITE_CONFIG_PCACHE2
    -**
    ^(This option takes a single argument which is a pointer to -** an [sqlite3_pcache_methods2] object. This object specifies the interface -** to a custom page cache implementation.)^ ^SQLite makes a copy of the -** object and uses it for page cache memory allocations.
    -** -** [[SQLITE_CONFIG_GETPCACHE2]]
    SQLITE_CONFIG_GETPCACHE2
    -**
    ^(This option takes a single argument which is a pointer to an -** [sqlite3_pcache_methods2] object. SQLite copies of the current -** page cache implementation into that object.)^
    -** -** [[SQLITE_CONFIG_LOG]]
    SQLITE_CONFIG_LOG
    -**
    ^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a -** function with a call signature of void(*)(void*,int,const char*), -** and a pointer to void. ^If the function pointer is not NULL, it is -** invoked by [sqlite3_log()] to process each logging event. ^If the -** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op. -** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is -** passed through as the first parameter to the application-defined logger -** function whenever that function is invoked. ^The second parameter to -** the logger function is a copy of the first parameter to the corresponding -** [sqlite3_log()] call and is intended to be a [result code] or an -** [extended result code]. ^The third parameter passed to the logger is -** log message after formatting via [sqlite3_snprintf()]. -** The SQLite logging interface is not reentrant; the logger function -** supplied by the application must not invoke any SQLite interface. -** In a multi-threaded application, the application-defined logger -** function must be threadsafe.
    -** -** [[SQLITE_CONFIG_URI]]
    SQLITE_CONFIG_URI -**
    This option takes a single argument of type int. If non-zero, then -** URI handling is globally enabled. If the parameter is zero, then URI handling -** is globally disabled. If URI handling is globally enabled, all filenames -** passed to [sqlite3_open()], [sqlite3_open_v2()], [sqlite3_open16()] or -** specified as part of [ATTACH] commands are interpreted as URIs, regardless -** of whether or not the [SQLITE_OPEN_URI] flag is set when the database -** connection is opened. If it is globally disabled, filenames are -** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the -** database connection is opened. By default, URI handling is globally -** disabled. The default value may be changed by compiling with the -** [SQLITE_USE_URI] symbol defined. -** -** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]]
    SQLITE_CONFIG_COVERING_INDEX_SCAN -**
    This option takes a single integer argument which is interpreted as -** a boolean in order to enable or disable the use of covering indices for -** full table scans in the query optimizer. The default setting is determined -** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on" -** if that compile-time option is omitted. -** The ability to disable the use of covering indices for full table scans -** is because some incorrectly coded legacy applications might malfunction -** malfunction when the optimization is enabled. Providing the ability to -** disable the optimization allows the older, buggy application code to work -** without change even with newer versions of SQLite. -** -** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]] -**
    SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE -**
    These options are obsolete and should not be used by new code. -** They are retained for backwards compatibility but are now no-ops. -**
    -** -** [[SQLITE_CONFIG_SQLLOG]] -**
    SQLITE_CONFIG_SQLLOG -**
    This option is only available if sqlite is compiled with the -** SQLITE_ENABLE_SQLLOG pre-processor macro defined. The first argument should -** be a pointer to a function of type void(*)(void*,sqlite3*,const char*, int). -** The second should be of type (void*). The callback is invoked by the library -** in three separate circumstances, identified by the value passed as the -** fourth parameter. If the fourth parameter is 0, then the database connection -** passed as the second argument has just been opened. The third argument -** points to a buffer containing the name of the main database file. If the -** fourth parameter is 1, then the SQL statement that the third parameter -** points to has just been executed. Or, if the fourth parameter is 2, then -** the connection being passed as the second parameter is being closed. The -** third parameter is passed NULL In this case. -** -*/ -#define SQLITE_CONFIG_SINGLETHREAD 1 /* nil */ -#define SQLITE_CONFIG_MULTITHREAD 2 /* nil */ -#define SQLITE_CONFIG_SERIALIZED 3 /* nil */ -#define SQLITE_CONFIG_MALLOC 4 /* sqlite3_mem_methods* */ -#define SQLITE_CONFIG_GETMALLOC 5 /* sqlite3_mem_methods* */ -#define SQLITE_CONFIG_SCRATCH 6 /* void*, int sz, int N */ -#define SQLITE_CONFIG_PAGECACHE 7 /* void*, int sz, int N */ -#define SQLITE_CONFIG_HEAP 8 /* void*, int nByte, int min */ -#define SQLITE_CONFIG_MEMSTATUS 9 /* boolean */ -#define SQLITE_CONFIG_MUTEX 10 /* sqlite3_mutex_methods* */ -#define SQLITE_CONFIG_GETMUTEX 11 /* sqlite3_mutex_methods* */ -/* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */ -#define SQLITE_CONFIG_LOOKASIDE 13 /* int int */ -#define SQLITE_CONFIG_PCACHE 14 /* no-op */ -#define SQLITE_CONFIG_GETPCACHE 15 /* no-op */ -#define SQLITE_CONFIG_LOG 16 /* xFunc, void* */ -#define SQLITE_CONFIG_URI 17 /* int */ -#define SQLITE_CONFIG_PCACHE2 18 /* sqlite3_pcache_methods2* */ -#define SQLITE_CONFIG_GETPCACHE2 19 /* sqlite3_pcache_methods2* */ -#define SQLITE_CONFIG_COVERING_INDEX_SCAN 20 /* int */ -#define SQLITE_CONFIG_SQLLOG 21 /* xSqllog, void* */ - -/* -** CAPI3REF: Database Connection Configuration Options -** -** These constants are the available integer configuration options that -** can be passed as the second argument to the [sqlite3_db_config()] interface. -** -** New configuration options may be added in future releases of SQLite. -** Existing configuration options might be discontinued. Applications -** should check the return code from [sqlite3_db_config()] to make sure that -** the call worked. ^The [sqlite3_db_config()] interface will return a -** non-zero [error code] if a discontinued or unsupported configuration option -** is invoked. -** -**
    -**
    SQLITE_DBCONFIG_LOOKASIDE
    -**
    ^This option takes three additional arguments that determine the -** [lookaside memory allocator] configuration for the [database connection]. -** ^The first argument (the third parameter to [sqlite3_db_config()] is a -** pointer to a memory buffer to use for lookaside memory. -** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb -** may be NULL in which case SQLite will allocate the -** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the -** size of each lookaside buffer slot. ^The third argument is the number of -** slots. The size of the buffer in the first argument must be greater than -** or equal to the product of the second and third arguments. The buffer -** must be aligned to an 8-byte boundary. ^If the second argument to -** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally -** rounded down to the next smaller multiple of 8. ^(The lookaside memory -** configuration for a database connection can only be changed when that -** connection is not currently using lookaside memory, or in other words -** when the "current value" returned by -** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero. -** Any attempt to change the lookaside memory configuration when lookaside -** memory is in use leaves the configuration unchanged and returns -** [SQLITE_BUSY].)^
    -** -**
    SQLITE_DBCONFIG_ENABLE_FKEY
    -**
    ^This option is used to enable or disable the enforcement of -** [foreign key constraints]. There should be two additional arguments. -** The first argument is an integer which is 0 to disable FK enforcement, -** positive to enable FK enforcement or negative to leave FK enforcement -** unchanged. The second parameter is a pointer to an integer into which -** is written 0 or 1 to indicate whether FK enforcement is off or on -** following this call. The second parameter may be a NULL pointer, in -** which case the FK enforcement setting is not reported back.
    -** -**
    SQLITE_DBCONFIG_ENABLE_TRIGGER
    -**
    ^This option is used to enable or disable [CREATE TRIGGER | triggers]. -** There should be two additional arguments. -** The first argument is an integer which is 0 to disable triggers, -** positive to enable triggers or negative to leave the setting unchanged. -** The second parameter is a pointer to an integer into which -** is written 0 or 1 to indicate whether triggers are disabled or enabled -** following this call. The second parameter may be a NULL pointer, in -** which case the trigger setting is not reported back.
    -** -**
    -*/ -#define SQLITE_DBCONFIG_LOOKASIDE 1001 /* void* int int */ -#define SQLITE_DBCONFIG_ENABLE_FKEY 1002 /* int int* */ -#define SQLITE_DBCONFIG_ENABLE_TRIGGER 1003 /* int int* */ - - -/* -** CAPI3REF: Enable Or Disable Extended Result Codes -** -** ^The sqlite3_extended_result_codes() routine enables or disables the -** [extended result codes] feature of SQLite. ^The extended result -** codes are disabled by default for historical compatibility. -*/ -SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff); - -/* -** CAPI3REF: Last Insert Rowid -** -** ^Each entry in an SQLite table has a unique 64-bit signed -** integer key called the [ROWID | "rowid"]. ^The rowid is always available -** as an undeclared column named ROWID, OID, or _ROWID_ as long as those -** names are not also used by explicitly declared columns. ^If -** the table has a column of type [INTEGER PRIMARY KEY] then that column -** is another alias for the rowid. -** -** ^This routine returns the [rowid] of the most recent -** successful [INSERT] into the database from the [database connection] -** in the first argument. ^As of SQLite version 3.7.7, this routines -** records the last insert rowid of both ordinary tables and [virtual tables]. -** ^If no successful [INSERT]s -** have ever occurred on that database connection, zero is returned. -** -** ^(If an [INSERT] occurs within a trigger or within a [virtual table] -** method, then this routine will return the [rowid] of the inserted -** row as long as the trigger or virtual table method is running. -** But once the trigger or virtual table method ends, the value returned -** by this routine reverts to what it was before the trigger or virtual -** table method began.)^ -** -** ^An [INSERT] that fails due to a constraint violation is not a -** successful [INSERT] and does not change the value returned by this -** routine. ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK, -** and INSERT OR ABORT make no changes to the return value of this -** routine when their insertion fails. ^(When INSERT OR REPLACE -** encounters a constraint violation, it does not fail. The -** INSERT continues to completion after deleting rows that caused -** the constraint problem so INSERT OR REPLACE will always change -** the return value of this interface.)^ -** -** ^For the purposes of this routine, an [INSERT] is considered to -** be successful even if it is subsequently rolled back. -** -** This function is accessible to SQL statements via the -** [last_insert_rowid() SQL function]. -** -** If a separate thread performs a new [INSERT] on the same -** database connection while the [sqlite3_last_insert_rowid()] -** function is running and thus changes the last insert [rowid], -** then the value returned by [sqlite3_last_insert_rowid()] is -** unpredictable and might not equal either the old or the new -** last insert [rowid]. -*/ -SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*); - -/* -** CAPI3REF: Count The Number Of Rows Modified -** -** ^This function returns the number of database rows that were changed -** or inserted or deleted by the most recently completed SQL statement -** on the [database connection] specified by the first parameter. -** ^(Only changes that are directly specified by the [INSERT], [UPDATE], -** or [DELETE] statement are counted. Auxiliary changes caused by -** triggers or [foreign key actions] are not counted.)^ Use the -** [sqlite3_total_changes()] function to find the total number of changes -** including changes caused by triggers and foreign key actions. -** -** ^Changes to a view that are simulated by an [INSTEAD OF trigger] -** are not counted. Only real table changes are counted. -** -** ^(A "row change" is a change to a single row of a single table -** caused by an INSERT, DELETE, or UPDATE statement. Rows that -** are changed as side effects of [REPLACE] constraint resolution, -** rollback, ABORT processing, [DROP TABLE], or by any other -** mechanisms do not count as direct row changes.)^ -** -** A "trigger context" is a scope of execution that begins and -** ends with the script of a [CREATE TRIGGER | trigger]. -** Most SQL statements are -** evaluated outside of any trigger. This is the "top level" -** trigger context. If a trigger fires from the top level, a -** new trigger context is entered for the duration of that one -** trigger. Subtriggers create subcontexts for their duration. -** -** ^Calling [sqlite3_exec()] or [sqlite3_step()] recursively does -** not create a new trigger context. -** -** ^This function returns the number of direct row changes in the -** most recent INSERT, UPDATE, or DELETE statement within the same -** trigger context. -** -** ^Thus, when called from the top level, this function returns the -** number of changes in the most recent INSERT, UPDATE, or DELETE -** that also occurred at the top level. ^(Within the body of a trigger, -** the sqlite3_changes() interface can be called to find the number of -** changes in the most recently completed INSERT, UPDATE, or DELETE -** statement within the body of the same trigger. -** However, the number returned does not include changes -** caused by subtriggers since those have their own context.)^ -** -** See also the [sqlite3_total_changes()] interface, the -** [count_changes pragma], and the [changes() SQL function]. -** -** If a separate thread makes changes on the same database connection -** while [sqlite3_changes()] is running then the value returned -** is unpredictable and not meaningful. -*/ -SQLITE_API int sqlite3_changes(sqlite3*); - -/* -** CAPI3REF: Total Number Of Rows Modified -** -** ^This function returns the number of row changes caused by [INSERT], -** [UPDATE] or [DELETE] statements since the [database connection] was opened. -** ^(The count returned by sqlite3_total_changes() includes all changes -** from all [CREATE TRIGGER | trigger] contexts and changes made by -** [foreign key actions]. However, -** the count does not include changes used to implement [REPLACE] constraints, -** do rollbacks or ABORT processing, or [DROP TABLE] processing. The -** count does not include rows of views that fire an [INSTEAD OF trigger], -** though if the INSTEAD OF trigger makes changes of its own, those changes -** are counted.)^ -** ^The sqlite3_total_changes() function counts the changes as soon as -** the statement that makes them is completed (when the statement handle -** is passed to [sqlite3_reset()] or [sqlite3_finalize()]). -** -** See also the [sqlite3_changes()] interface, the -** [count_changes pragma], and the [total_changes() SQL function]. -** -** If a separate thread makes changes on the same database connection -** while [sqlite3_total_changes()] is running then the value -** returned is unpredictable and not meaningful. -*/ -SQLITE_API int sqlite3_total_changes(sqlite3*); - -/* -** CAPI3REF: Interrupt A Long-Running Query -** -** ^This function causes any pending database operation to abort and -** return at its earliest opportunity. This routine is typically -** called in response to a user action such as pressing "Cancel" -** or Ctrl-C where the user wants a long query operation to halt -** immediately. -** -** ^It is safe to call this routine from a thread different from the -** thread that is currently running the database operation. But it -** is not safe to call this routine with a [database connection] that -** is closed or might close before sqlite3_interrupt() returns. -** -** ^If an SQL operation is very nearly finished at the time when -** sqlite3_interrupt() is called, then it might not have an opportunity -** to be interrupted and might continue to completion. -** -** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT]. -** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE -** that is inside an explicit transaction, then the entire transaction -** will be rolled back automatically. -** -** ^The sqlite3_interrupt(D) call is in effect until all currently running -** SQL statements on [database connection] D complete. ^Any new SQL statements -** that are started after the sqlite3_interrupt() call and before the -** running statements reaches zero are interrupted as if they had been -** running prior to the sqlite3_interrupt() call. ^New SQL statements -** that are started after the running statement count reaches zero are -** not effected by the sqlite3_interrupt(). -** ^A call to sqlite3_interrupt(D) that occurs when there are no running -** SQL statements is a no-op and has no effect on SQL statements -** that are started after the sqlite3_interrupt() call returns. -** -** If the database connection closes while [sqlite3_interrupt()] -** is running then bad things will likely happen. -*/ -SQLITE_API void sqlite3_interrupt(sqlite3*); - -/* -** CAPI3REF: Determine If An SQL Statement Is Complete -** -** These routines are useful during command-line input to determine if the -** currently entered text seems to form a complete SQL statement or -** if additional input is needed before sending the text into -** SQLite for parsing. ^These routines return 1 if the input string -** appears to be a complete SQL statement. ^A statement is judged to be -** complete if it ends with a semicolon token and is not a prefix of a -** well-formed CREATE TRIGGER statement. ^Semicolons that are embedded within -** string literals or quoted identifier names or comments are not -** independent tokens (they are part of the token in which they are -** embedded) and thus do not count as a statement terminator. ^Whitespace -** and comments that follow the final semicolon are ignored. -** -** ^These routines return 0 if the statement is incomplete. ^If a -** memory allocation fails, then SQLITE_NOMEM is returned. -** -** ^These routines do not parse the SQL statements thus -** will not detect syntactically incorrect SQL. -** -** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior -** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked -** automatically by sqlite3_complete16(). If that initialization fails, -** then the return value from sqlite3_complete16() will be non-zero -** regardless of whether or not the input SQL is complete.)^ -** -** The input to [sqlite3_complete()] must be a zero-terminated -** UTF-8 string. -** -** The input to [sqlite3_complete16()] must be a zero-terminated -** UTF-16 string in native byte order. -*/ -SQLITE_API int sqlite3_complete(const char *sql); -SQLITE_API int sqlite3_complete16(const void *sql); - -/* -** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors -** -** ^This routine sets a callback function that might be invoked whenever -** an attempt is made to open a database table that another thread -** or process has locked. -** -** ^If the busy callback is NULL, then [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] -** is returned immediately upon encountering the lock. ^If the busy callback -** is not NULL, then the callback might be invoked with two arguments. -** -** ^The first argument to the busy handler is a copy of the void* pointer which -** is the third argument to sqlite3_busy_handler(). ^The second argument to -** the busy handler callback is the number of times that the busy handler has -** been invoked for this locking event. ^If the -** busy callback returns 0, then no additional attempts are made to -** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned. -** ^If the callback returns non-zero, then another attempt -** is made to open the database for reading and the cycle repeats. -** -** The presence of a busy handler does not guarantee that it will be invoked -** when there is lock contention. ^If SQLite determines that invoking the busy -** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY] -** or [SQLITE_IOERR_BLOCKED] instead of invoking the busy handler. -** Consider a scenario where one process is holding a read lock that -** it is trying to promote to a reserved lock and -** a second process is holding a reserved lock that it is trying -** to promote to an exclusive lock. The first process cannot proceed -** because it is blocked by the second and the second process cannot -** proceed because it is blocked by the first. If both processes -** invoke the busy handlers, neither will make any progress. Therefore, -** SQLite returns [SQLITE_BUSY] for the first process, hoping that this -** will induce the first process to release its read lock and allow -** the second process to proceed. -** -** ^The default busy callback is NULL. -** -** ^The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED] -** when SQLite is in the middle of a large transaction where all the -** changes will not fit into the in-memory cache. SQLite will -** already hold a RESERVED lock on the database file, but it needs -** to promote this lock to EXCLUSIVE so that it can spill cache -** pages into the database file without harm to concurrent -** readers. ^If it is unable to promote the lock, then the in-memory -** cache will be left in an inconsistent state and so the error -** code is promoted from the relatively benign [SQLITE_BUSY] to -** the more severe [SQLITE_IOERR_BLOCKED]. ^This error code promotion -** forces an automatic rollback of the changes. See the -** -** CorruptionFollowingBusyError wiki page for a discussion of why -** this is important. -** -** ^(There can only be a single busy handler defined for each -** [database connection]. Setting a new busy handler clears any -** previously set handler.)^ ^Note that calling [sqlite3_busy_timeout()] -** will also set or clear the busy handler. -** -** The busy callback should not take any actions which modify the -** database connection that invoked the busy handler. Any such actions -** result in undefined behavior. -** -** A busy handler must not close the database connection -** or [prepared statement] that invoked the busy handler. -*/ -SQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*); - -/* -** CAPI3REF: Set A Busy Timeout -** -** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps -** for a specified amount of time when a table is locked. ^The handler -** will sleep multiple times until at least "ms" milliseconds of sleeping -** have accumulated. ^After at least "ms" milliseconds of sleeping, -** the handler returns 0 which causes [sqlite3_step()] to return -** [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]. -** -** ^Calling this routine with an argument less than or equal to zero -** turns off all busy handlers. -** -** ^(There can only be a single busy handler for a particular -** [database connection] any any given moment. If another busy handler -** was defined (using [sqlite3_busy_handler()]) prior to calling -** this routine, that other busy handler is cleared.)^ -*/ -SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms); - -/* -** CAPI3REF: Convenience Routines For Running Queries -** -** This is a legacy interface that is preserved for backwards compatibility. -** Use of this interface is not recommended. -** -** Definition: A result table is memory data structure created by the -** [sqlite3_get_table()] interface. A result table records the -** complete query results from one or more queries. -** -** The table conceptually has a number of rows and columns. But -** these numbers are not part of the result table itself. These -** numbers are obtained separately. Let N be the number of rows -** and M be the number of columns. -** -** A result table is an array of pointers to zero-terminated UTF-8 strings. -** There are (N+1)*M elements in the array. The first M pointers point -** to zero-terminated strings that contain the names of the columns. -** The remaining entries all point to query results. NULL values result -** in NULL pointers. All other values are in their UTF-8 zero-terminated -** string representation as returned by [sqlite3_column_text()]. -** -** A result table might consist of one or more memory allocations. -** It is not safe to pass a result table directly to [sqlite3_free()]. -** A result table should be deallocated using [sqlite3_free_table()]. -** -** ^(As an example of the result table format, suppose a query result -** is as follows: -** -**
    -**        Name        | Age
    -**        -----------------------
    -**        Alice       | 43
    -**        Bob         | 28
    -**        Cindy       | 21
    -** 
    -** -** There are two column (M==2) and three rows (N==3). Thus the -** result table has 8 entries. Suppose the result table is stored -** in an array names azResult. Then azResult holds this content: -** -**
    -**        azResult[0] = "Name";
    -**        azResult[1] = "Age";
    -**        azResult[2] = "Alice";
    -**        azResult[3] = "43";
    -**        azResult[4] = "Bob";
    -**        azResult[5] = "28";
    -**        azResult[6] = "Cindy";
    -**        azResult[7] = "21";
    -** 
    )^ -** -** ^The sqlite3_get_table() function evaluates one or more -** semicolon-separated SQL statements in the zero-terminated UTF-8 -** string of its 2nd parameter and returns a result table to the -** pointer given in its 3rd parameter. -** -** After the application has finished with the result from sqlite3_get_table(), -** it must pass the result table pointer to sqlite3_free_table() in order to -** release the memory that was malloced. Because of the way the -** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling -** function must not try to call [sqlite3_free()] directly. Only -** [sqlite3_free_table()] is able to release the memory properly and safely. -** -** The sqlite3_get_table() interface is implemented as a wrapper around -** [sqlite3_exec()]. The sqlite3_get_table() routine does not have access -** to any internal data structures of SQLite. It uses only the public -** interface defined here. As a consequence, errors that occur in the -** wrapper layer outside of the internal [sqlite3_exec()] call are not -** reflected in subsequent calls to [sqlite3_errcode()] or -** [sqlite3_errmsg()]. -*/ -SQLITE_API int sqlite3_get_table( - sqlite3 *db, /* An open database */ - const char *zSql, /* SQL to be evaluated */ - char ***pazResult, /* Results of the query */ - int *pnRow, /* Number of result rows written here */ - int *pnColumn, /* Number of result columns written here */ - char **pzErrmsg /* Error msg written here */ -); -SQLITE_API void sqlite3_free_table(char **result); - -/* -** CAPI3REF: Formatted String Printing Functions -** -** These routines are work-alikes of the "printf()" family of functions -** from the standard C library. -** -** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their -** results into memory obtained from [sqlite3_malloc()]. -** The strings returned by these two routines should be -** released by [sqlite3_free()]. ^Both routines return a -** NULL pointer if [sqlite3_malloc()] is unable to allocate enough -** memory to hold the resulting string. -** -** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from -** the standard C library. The result is written into the -** buffer supplied as the second parameter whose size is given by -** the first parameter. Note that the order of the -** first two parameters is reversed from snprintf().)^ This is an -** historical accident that cannot be fixed without breaking -** backwards compatibility. ^(Note also that sqlite3_snprintf() -** returns a pointer to its buffer instead of the number of -** characters actually written into the buffer.)^ We admit that -** the number of characters written would be a more useful return -** value but we cannot change the implementation of sqlite3_snprintf() -** now without breaking compatibility. -** -** ^As long as the buffer size is greater than zero, sqlite3_snprintf() -** guarantees that the buffer is always zero-terminated. ^The first -** parameter "n" is the total size of the buffer, including space for -** the zero terminator. So the longest string that can be completely -** written will be n-1 characters. -** -** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf(). -** -** These routines all implement some additional formatting -** options that are useful for constructing SQL statements. -** All of the usual printf() formatting options apply. In addition, there -** is are "%q", "%Q", and "%z" options. -** -** ^(The %q option works like %s in that it substitutes a nul-terminated -** string from the argument list. But %q also doubles every '\'' character. -** %q is designed for use inside a string literal.)^ By doubling each '\'' -** character it escapes that character and allows it to be inserted into -** the string. -** -** For example, assume the string variable zText contains text as follows: -** -**
    -**  char *zText = "It's a happy day!";
    -** 
    -** -** One can use this text in an SQL statement as follows: -** -**
    -**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
    -**  sqlite3_exec(db, zSQL, 0, 0, 0);
    -**  sqlite3_free(zSQL);
    -** 
    -** -** Because the %q format string is used, the '\'' character in zText -** is escaped and the SQL generated is as follows: -** -**
    -**  INSERT INTO table1 VALUES('It''s a happy day!')
    -** 
    -** -** This is correct. Had we used %s instead of %q, the generated SQL -** would have looked like this: -** -**
    -**  INSERT INTO table1 VALUES('It's a happy day!');
    -** 
    -** -** This second example is an SQL syntax error. As a general rule you should -** always use %q instead of %s when inserting text into a string literal. -** -** ^(The %Q option works like %q except it also adds single quotes around -** the outside of the total string. Additionally, if the parameter in the -** argument list is a NULL pointer, %Q substitutes the text "NULL" (without -** single quotes).)^ So, for example, one could say: -** -**
    -**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
    -**  sqlite3_exec(db, zSQL, 0, 0, 0);
    -**  sqlite3_free(zSQL);
    -** 
    -** -** The code above will render a correct SQL statement in the zSQL -** variable even if the zText variable is a NULL pointer. -** -** ^(The "%z" formatting option works like "%s" but with the -** addition that after the string has been read and copied into -** the result, [sqlite3_free()] is called on the input string.)^ -*/ -SQLITE_API char *sqlite3_mprintf(const char*,...); -SQLITE_API char *sqlite3_vmprintf(const char*, va_list); -SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...); -SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list); - -/* -** CAPI3REF: Memory Allocation Subsystem -** -** The SQLite core uses these three routines for all of its own -** internal memory allocation needs. "Core" in the previous sentence -** does not include operating-system specific VFS implementation. The -** Windows VFS uses native malloc() and free() for some operations. -** -** ^The sqlite3_malloc() routine returns a pointer to a block -** of memory at least N bytes in length, where N is the parameter. -** ^If sqlite3_malloc() is unable to obtain sufficient free -** memory, it returns a NULL pointer. ^If the parameter N to -** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns -** a NULL pointer. -** -** ^Calling sqlite3_free() with a pointer previously returned -** by sqlite3_malloc() or sqlite3_realloc() releases that memory so -** that it might be reused. ^The sqlite3_free() routine is -** a no-op if is called with a NULL pointer. Passing a NULL pointer -** to sqlite3_free() is harmless. After being freed, memory -** should neither be read nor written. Even reading previously freed -** memory might result in a segmentation fault or other severe error. -** Memory corruption, a segmentation fault, or other severe error -** might result if sqlite3_free() is called with a non-NULL pointer that -** was not obtained from sqlite3_malloc() or sqlite3_realloc(). -** -** ^(The sqlite3_realloc() interface attempts to resize a -** prior memory allocation to be at least N bytes, where N is the -** second parameter. The memory allocation to be resized is the first -** parameter.)^ ^ If the first parameter to sqlite3_realloc() -** is a NULL pointer then its behavior is identical to calling -** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc(). -** ^If the second parameter to sqlite3_realloc() is zero or -** negative then the behavior is exactly the same as calling -** sqlite3_free(P) where P is the first parameter to sqlite3_realloc(). -** ^sqlite3_realloc() returns a pointer to a memory allocation -** of at least N bytes in size or NULL if sufficient memory is unavailable. -** ^If M is the size of the prior allocation, then min(N,M) bytes -** of the prior allocation are copied into the beginning of buffer returned -** by sqlite3_realloc() and the prior allocation is freed. -** ^If sqlite3_realloc() returns NULL, then the prior allocation -** is not freed. -** -** ^The memory returned by sqlite3_malloc() and sqlite3_realloc() -** is always aligned to at least an 8 byte boundary, or to a -** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time -** option is used. -** -** In SQLite version 3.5.0 and 3.5.1, it was possible to define -** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in -** implementation of these routines to be omitted. That capability -** is no longer provided. Only built-in memory allocators can be used. -** -** Prior to SQLite version 3.7.10, the Windows OS interface layer called -** the system malloc() and free() directly when converting -** filenames between the UTF-8 encoding used by SQLite -** and whatever filename encoding is used by the particular Windows -** installation. Memory allocation errors were detected, but -** they were reported back as [SQLITE_CANTOPEN] or -** [SQLITE_IOERR] rather than [SQLITE_NOMEM]. -** -** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()] -** must be either NULL or else pointers obtained from a prior -** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have -** not yet been released. -** -** The application must not read or write any part of -** a block of memory after it has been released using -** [sqlite3_free()] or [sqlite3_realloc()]. -*/ -SQLITE_API void *sqlite3_malloc(int); -SQLITE_API void *sqlite3_realloc(void*, int); -SQLITE_API void sqlite3_free(void*); - -/* -** CAPI3REF: Memory Allocator Statistics -** -** SQLite provides these two interfaces for reporting on the status -** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()] -** routines, which form the built-in memory allocation subsystem. -** -** ^The [sqlite3_memory_used()] routine returns the number of bytes -** of memory currently outstanding (malloced but not freed). -** ^The [sqlite3_memory_highwater()] routine returns the maximum -** value of [sqlite3_memory_used()] since the high-water mark -** was last reset. ^The values returned by [sqlite3_memory_used()] and -** [sqlite3_memory_highwater()] include any overhead -** added by SQLite in its implementation of [sqlite3_malloc()], -** but not overhead added by the any underlying system library -** routines that [sqlite3_malloc()] may call. -** -** ^The memory high-water mark is reset to the current value of -** [sqlite3_memory_used()] if and only if the parameter to -** [sqlite3_memory_highwater()] is true. ^The value returned -** by [sqlite3_memory_highwater(1)] is the high-water mark -** prior to the reset. -*/ -SQLITE_API sqlite3_int64 sqlite3_memory_used(void); -SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag); - -/* -** CAPI3REF: Pseudo-Random Number Generator -** -** SQLite contains a high-quality pseudo-random number generator (PRNG) used to -** select random [ROWID | ROWIDs] when inserting new records into a table that -** already uses the largest possible [ROWID]. The PRNG is also used for -** the build-in random() and randomblob() SQL functions. This interface allows -** applications to access the same PRNG for other purposes. -** -** ^A call to this routine stores N bytes of randomness into buffer P. -** -** ^The first time this routine is invoked (either internally or by -** the application) the PRNG is seeded using randomness obtained -** from the xRandomness method of the default [sqlite3_vfs] object. -** ^On all subsequent invocations, the pseudo-randomness is generated -** internally and without recourse to the [sqlite3_vfs] xRandomness -** method. -*/ -SQLITE_API void sqlite3_randomness(int N, void *P); - -/* -** CAPI3REF: Compile-Time Authorization Callbacks -** -** ^This routine registers an authorizer callback with a particular -** [database connection], supplied in the first argument. -** ^The authorizer callback is invoked as SQL statements are being compiled -** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()], -** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()]. ^At various -** points during the compilation process, as logic is being created -** to perform various actions, the authorizer callback is invoked to -** see if those actions are allowed. ^The authorizer callback should -** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the -** specific action but allow the SQL statement to continue to be -** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be -** rejected with an error. ^If the authorizer callback returns -** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY] -** then the [sqlite3_prepare_v2()] or equivalent call that triggered -** the authorizer will fail with an error message. -** -** When the callback returns [SQLITE_OK], that means the operation -** requested is ok. ^When the callback returns [SQLITE_DENY], the -** [sqlite3_prepare_v2()] or equivalent call that triggered the -** authorizer will fail with an error message explaining that -** access is denied. -** -** ^The first parameter to the authorizer callback is a copy of the third -** parameter to the sqlite3_set_authorizer() interface. ^The second parameter -** to the callback is an integer [SQLITE_COPY | action code] that specifies -** the particular action to be authorized. ^The third through sixth parameters -** to the callback are zero-terminated strings that contain additional -** details about the action to be authorized. -** -** ^If the action code is [SQLITE_READ] -** and the callback returns [SQLITE_IGNORE] then the -** [prepared statement] statement is constructed to substitute -** a NULL value in place of the table column that would have -** been read if [SQLITE_OK] had been returned. The [SQLITE_IGNORE] -** return can be used to deny an untrusted user access to individual -** columns of a table. -** ^If the action code is [SQLITE_DELETE] and the callback returns -** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the -** [truncate optimization] is disabled and all rows are deleted individually. -** -** An authorizer is used when [sqlite3_prepare | preparing] -** SQL statements from an untrusted source, to ensure that the SQL statements -** do not try to access data they are not allowed to see, or that they do not -** try to execute malicious statements that damage the database. For -** example, an application may allow a user to enter arbitrary -** SQL queries for evaluation by a database. But the application does -** not want the user to be able to make arbitrary changes to the -** database. An authorizer could then be put in place while the -** user-entered SQL is being [sqlite3_prepare | prepared] that -** disallows everything except [SELECT] statements. -** -** Applications that need to process SQL from untrusted sources -** might also consider lowering resource limits using [sqlite3_limit()] -** and limiting database size using the [max_page_count] [PRAGMA] -** in addition to using an authorizer. -** -** ^(Only a single authorizer can be in place on a database connection -** at a time. Each call to sqlite3_set_authorizer overrides the -** previous call.)^ ^Disable the authorizer by installing a NULL callback. -** The authorizer is disabled by default. -** -** The authorizer callback must not do anything that will modify -** the database connection that invoked the authorizer callback. -** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their -** database connections for the meaning of "modify" in this paragraph. -** -** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the -** statement might be re-prepared during [sqlite3_step()] due to a -** schema change. Hence, the application should ensure that the -** correct authorizer callback remains in place during the [sqlite3_step()]. -** -** ^Note that the authorizer callback is invoked only during -** [sqlite3_prepare()] or its variants. Authorization is not -** performed during statement evaluation in [sqlite3_step()], unless -** as stated in the previous paragraph, sqlite3_step() invokes -** sqlite3_prepare_v2() to reprepare a statement after a schema change. -*/ -SQLITE_API int sqlite3_set_authorizer( - sqlite3*, - int (*xAuth)(void*,int,const char*,const char*,const char*,const char*), - void *pUserData -); - -/* -** CAPI3REF: Authorizer Return Codes -** -** The [sqlite3_set_authorizer | authorizer callback function] must -** return either [SQLITE_OK] or one of these two constants in order -** to signal SQLite whether or not the action is permitted. See the -** [sqlite3_set_authorizer | authorizer documentation] for additional -** information. -** -** Note that SQLITE_IGNORE is also used as a [SQLITE_ROLLBACK | return code] -** from the [sqlite3_vtab_on_conflict()] interface. -*/ -#define SQLITE_DENY 1 /* Abort the SQL statement with an error */ -#define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */ - -/* -** CAPI3REF: Authorizer Action Codes -** -** The [sqlite3_set_authorizer()] interface registers a callback function -** that is invoked to authorize certain SQL statement actions. The -** second parameter to the callback is an integer code that specifies -** what action is being authorized. These are the integer action codes that -** the authorizer callback may be passed. -** -** These action code values signify what kind of operation is to be -** authorized. The 3rd and 4th parameters to the authorization -** callback function will be parameters or NULL depending on which of these -** codes is used as the second parameter. ^(The 5th parameter to the -** authorizer callback is the name of the database ("main", "temp", -** etc.) if applicable.)^ ^The 6th parameter to the authorizer callback -** is the name of the inner-most trigger or view that is responsible for -** the access attempt or NULL if this access attempt is directly from -** top-level SQL code. -*/ -/******************************************* 3rd ************ 4th ***********/ -#define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */ -#define SQLITE_CREATE_TABLE 2 /* Table Name NULL */ -#define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */ -#define SQLITE_CREATE_TEMP_TABLE 4 /* Table Name NULL */ -#define SQLITE_CREATE_TEMP_TRIGGER 5 /* Trigger Name Table Name */ -#define SQLITE_CREATE_TEMP_VIEW 6 /* View Name NULL */ -#define SQLITE_CREATE_TRIGGER 7 /* Trigger Name Table Name */ -#define SQLITE_CREATE_VIEW 8 /* View Name NULL */ -#define SQLITE_DELETE 9 /* Table Name NULL */ -#define SQLITE_DROP_INDEX 10 /* Index Name Table Name */ -#define SQLITE_DROP_TABLE 11 /* Table Name NULL */ -#define SQLITE_DROP_TEMP_INDEX 12 /* Index Name Table Name */ -#define SQLITE_DROP_TEMP_TABLE 13 /* Table Name NULL */ -#define SQLITE_DROP_TEMP_TRIGGER 14 /* Trigger Name Table Name */ -#define SQLITE_DROP_TEMP_VIEW 15 /* View Name NULL */ -#define SQLITE_DROP_TRIGGER 16 /* Trigger Name Table Name */ -#define SQLITE_DROP_VIEW 17 /* View Name NULL */ -#define SQLITE_INSERT 18 /* Table Name NULL */ -#define SQLITE_PRAGMA 19 /* Pragma Name 1st arg or NULL */ -#define SQLITE_READ 20 /* Table Name Column Name */ -#define SQLITE_SELECT 21 /* NULL NULL */ -#define SQLITE_TRANSACTION 22 /* Operation NULL */ -#define SQLITE_UPDATE 23 /* Table Name Column Name */ -#define SQLITE_ATTACH 24 /* Filename NULL */ -#define SQLITE_DETACH 25 /* Database Name NULL */ -#define SQLITE_ALTER_TABLE 26 /* Database Name Table Name */ -#define SQLITE_REINDEX 27 /* Index Name NULL */ -#define SQLITE_ANALYZE 28 /* Table Name NULL */ -#define SQLITE_CREATE_VTABLE 29 /* Table Name Module Name */ -#define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */ -#define SQLITE_FUNCTION 31 /* NULL Function Name */ -#define SQLITE_SAVEPOINT 32 /* Operation Savepoint Name */ -#define SQLITE_COPY 0 /* No longer used */ - -/* -** CAPI3REF: Tracing And Profiling Functions -** -** These routines register callback functions that can be used for -** tracing and profiling the execution of SQL statements. -** -** ^The callback function registered by sqlite3_trace() is invoked at -** various times when an SQL statement is being run by [sqlite3_step()]. -** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the -** SQL statement text as the statement first begins executing. -** ^(Additional sqlite3_trace() callbacks might occur -** as each triggered subprogram is entered. The callbacks for triggers -** contain a UTF-8 SQL comment that identifies the trigger.)^ -** -** ^The callback function registered by sqlite3_profile() is invoked -** as each SQL statement finishes. ^The profile callback contains -** the original statement text and an estimate of wall-clock time -** of how long that statement took to run. ^The profile callback -** time is in units of nanoseconds, however the current implementation -** is only capable of millisecond resolution so the six least significant -** digits in the time are meaningless. Future versions of SQLite -** might provide greater resolution on the profiler callback. The -** sqlite3_profile() function is considered experimental and is -** subject to change in future versions of SQLite. -*/ -SQLITE_API void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*); -SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*, - void(*xProfile)(void*,const char*,sqlite3_uint64), void*); - -/* -** CAPI3REF: Query Progress Callbacks -** -** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback -** function X to be invoked periodically during long running calls to -** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for -** database connection D. An example use for this -** interface is to keep a GUI updated during a large query. -** -** ^The parameter P is passed through as the only parameter to the -** callback function X. ^The parameter N is the number of -** [virtual machine instructions] that are evaluated between successive -** invocations of the callback X. -** -** ^Only a single progress handler may be defined at one time per -** [database connection]; setting a new progress handler cancels the -** old one. ^Setting parameter X to NULL disables the progress handler. -** ^The progress handler is also disabled by setting N to a value less -** than 1. -** -** ^If the progress callback returns non-zero, the operation is -** interrupted. This feature can be used to implement a -** "Cancel" button on a GUI progress dialog box. -** -** The progress handler callback must not do anything that will modify -** the database connection that invoked the progress handler. -** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their -** database connections for the meaning of "modify" in this paragraph. -** -*/ -SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*); - -/* -** CAPI3REF: Opening A New Database Connection -** -** ^These routines open an SQLite database file as specified by the -** filename argument. ^The filename argument is interpreted as UTF-8 for -** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte -** order for sqlite3_open16(). ^(A [database connection] handle is usually -** returned in *ppDb, even if an error occurs. The only exception is that -** if SQLite is unable to allocate memory to hold the [sqlite3] object, -** a NULL will be written into *ppDb instead of a pointer to the [sqlite3] -** object.)^ ^(If the database is opened (and/or created) successfully, then -** [SQLITE_OK] is returned. Otherwise an [error code] is returned.)^ ^The -** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain -** an English language description of the error following a failure of any -** of the sqlite3_open() routines. -** -** ^The default encoding for the database will be UTF-8 if -** sqlite3_open() or sqlite3_open_v2() is called and -** UTF-16 in the native byte order if sqlite3_open16() is used. -** -** Whether or not an error occurs when it is opened, resources -** associated with the [database connection] handle should be released by -** passing it to [sqlite3_close()] when it is no longer required. -** -** The sqlite3_open_v2() interface works like sqlite3_open() -** except that it accepts two additional parameters for additional control -** over the new database connection. ^(The flags parameter to -** sqlite3_open_v2() can take one of -** the following three values, optionally combined with the -** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE], -** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^ -** -**
    -** ^(
    [SQLITE_OPEN_READONLY]
    -**
    The database is opened in read-only mode. If the database does not -** already exist, an error is returned.
    )^ -** -** ^(
    [SQLITE_OPEN_READWRITE]
    -**
    The database is opened for reading and writing if possible, or reading -** only if the file is write protected by the operating system. In either -** case the database must already exist, otherwise an error is returned.
    )^ -** -** ^(
    [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]
    -**
    The database is opened for reading and writing, and is created if -** it does not already exist. This is the behavior that is always used for -** sqlite3_open() and sqlite3_open16().
    )^ -**
    -** -** If the 3rd parameter to sqlite3_open_v2() is not one of the -** combinations shown above optionally combined with other -** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits] -** then the behavior is undefined. -** -** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection -** opens in the multi-thread [threading mode] as long as the single-thread -** mode has not been set at compile-time or start-time. ^If the -** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens -** in the serialized [threading mode] unless single-thread was -** previously selected at compile-time or start-time. -** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be -** eligible to use [shared cache mode], regardless of whether or not shared -** cache is enabled using [sqlite3_enable_shared_cache()]. ^The -** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not -** participate in [shared cache mode] even if it is enabled. -** -** ^The fourth parameter to sqlite3_open_v2() is the name of the -** [sqlite3_vfs] object that defines the operating system interface that -** the new database connection should use. ^If the fourth parameter is -** a NULL pointer then the default [sqlite3_vfs] object is used. -** -** ^If the filename is ":memory:", then a private, temporary in-memory database -** is created for the connection. ^This in-memory database will vanish when -** the database connection is closed. Future versions of SQLite might -** make use of additional special filenames that begin with the ":" character. -** It is recommended that when a database filename actually does begin with -** a ":" character you should prefix the filename with a pathname such as -** "./" to avoid ambiguity. -** -** ^If the filename is an empty string, then a private, temporary -** on-disk database will be created. ^This private database will be -** automatically deleted as soon as the database connection is closed. -** -** [[URI filenames in sqlite3_open()]]

    URI Filenames

    -** -** ^If [URI filename] interpretation is enabled, and the filename argument -** begins with "file:", then the filename is interpreted as a URI. ^URI -** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is -** set in the fourth argument to sqlite3_open_v2(), or if it has -** been enabled globally using the [SQLITE_CONFIG_URI] option with the -** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option. -** As of SQLite version 3.7.7, URI filename interpretation is turned off -** by default, but future releases of SQLite might enable URI filename -** interpretation by default. See "[URI filenames]" for additional -** information. -** -** URI filenames are parsed according to RFC 3986. ^If the URI contains an -** authority, then it must be either an empty string or the string -** "localhost". ^If the authority is not an empty string or "localhost", an -** error is returned to the caller. ^The fragment component of a URI, if -** present, is ignored. -** -** ^SQLite uses the path component of the URI as the name of the disk file -** which contains the database. ^If the path begins with a '/' character, -** then it is interpreted as an absolute path. ^If the path does not begin -** with a '/' (meaning that the authority section is omitted from the URI) -** then the path is interpreted as a relative path. -** ^On windows, the first component of an absolute path -** is a drive specification (e.g. "C:"). -** -** [[core URI query parameters]] -** The query component of a URI may contain parameters that are interpreted -** either by SQLite itself, or by a [VFS | custom VFS implementation]. -** SQLite interprets the following three query parameters: -** -**
      -**
    • vfs: ^The "vfs" parameter may be used to specify the name of -** a VFS object that provides the operating system interface that should -** be used to access the database file on disk. ^If this option is set to -** an empty string the default VFS object is used. ^Specifying an unknown -** VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is -** present, then the VFS specified by the option takes precedence over -** the value passed as the fourth parameter to sqlite3_open_v2(). -** -**
    • mode: ^(The mode parameter may be set to either "ro", "rw", -** "rwc", or "memory". Attempting to set it to any other value is -** an error)^. -** ^If "ro" is specified, then the database is opened for read-only -** access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the -** third argument to sqlite3_open_v2(). ^If the mode option is set to -** "rw", then the database is opened for read-write (but not create) -** access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had -** been set. ^Value "rwc" is equivalent to setting both -** SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE. ^If the mode option is -** set to "memory" then a pure [in-memory database] that never reads -** or writes from disk is used. ^It is an error to specify a value for -** the mode parameter that is less restrictive than that specified by -** the flags passed in the third parameter to sqlite3_open_v2(). -** -**
    • cache: ^The cache parameter may be set to either "shared" or -** "private". ^Setting it to "shared" is equivalent to setting the -** SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to -** sqlite3_open_v2(). ^Setting the cache parameter to "private" is -** equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit. -** ^If sqlite3_open_v2() is used and the "cache" parameter is present in -** a URI filename, its value overrides any behavior requested by setting -** SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag. -**
    -** -** ^Specifying an unknown parameter in the query component of a URI is not an -** error. Future versions of SQLite might understand additional query -** parameters. See "[query parameters with special meaning to SQLite]" for -** additional information. -** -** [[URI filename examples]]

    URI filename examples

    -** -**
    -**
    URI filenames Results -**
    file:data.db -** Open the file "data.db" in the current directory. -**
    file:/home/fred/data.db
    -** file:///home/fred/data.db
    -** file://localhost/home/fred/data.db
    -** Open the database file "/home/fred/data.db". -**
    file://darkstar/home/fred/data.db -** An error. "darkstar" is not a recognized authority. -**
    -** file:///C:/Documents%20and%20Settings/fred/Desktop/data.db -** Windows only: Open the file "data.db" on fred's desktop on drive -** C:. Note that the %20 escaping in this example is not strictly -** necessary - space characters can be used literally -** in URI filenames. -**
    file:data.db?mode=ro&cache=private -** Open file "data.db" in the current directory for read-only access. -** Regardless of whether or not shared-cache mode is enabled by -** default, use a private cache. -**
    file:/home/fred/data.db?vfs=unix-nolock -** Open file "/home/fred/data.db". Use the special VFS "unix-nolock". -**
    file:data.db?mode=readonly -** An error. "readonly" is not a valid option for the "mode" parameter. -**
    -** -** ^URI hexadecimal escape sequences (%HH) are supported within the path and -** query components of a URI. A hexadecimal escape sequence consists of a -** percent sign - "%" - followed by exactly two hexadecimal digits -** specifying an octet value. ^Before the path or query components of a -** URI filename are interpreted, they are encoded using UTF-8 and all -** hexadecimal escape sequences replaced by a single byte containing the -** corresponding octet. If this process generates an invalid UTF-8 encoding, -** the results are undefined. -** -** Note to Windows users: The encoding used for the filename argument -** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever -** codepage is currently defined. Filenames containing international -** characters must be converted to UTF-8 prior to passing them into -** sqlite3_open() or sqlite3_open_v2(). -** -** Note to Windows Runtime users: The temporary directory must be set -** prior to calling sqlite3_open() or sqlite3_open_v2(). Otherwise, various -** features that require the use of temporary files may fail. -** -** See also: [sqlite3_temp_directory] -*/ -SQLITE_API int sqlite3_open( - const char *filename, /* Database filename (UTF-8) */ - sqlite3 **ppDb /* OUT: SQLite db handle */ -); -SQLITE_API int sqlite3_open16( - const void *filename, /* Database filename (UTF-16) */ - sqlite3 **ppDb /* OUT: SQLite db handle */ -); -SQLITE_API int sqlite3_open_v2( - const char *filename, /* Database filename (UTF-8) */ - sqlite3 **ppDb, /* OUT: SQLite db handle */ - int flags, /* Flags */ - const char *zVfs /* Name of VFS module to use */ -); - -/* -** CAPI3REF: Obtain Values For URI Parameters -** -** These are utility routines, useful to VFS implementations, that check -** to see if a database file was a URI that contained a specific query -** parameter, and if so obtains the value of that query parameter. -** -** If F is the database filename pointer passed into the xOpen() method of -** a VFS implementation when the flags parameter to xOpen() has one or -** more of the [SQLITE_OPEN_URI] or [SQLITE_OPEN_MAIN_DB] bits set and -** P is the name of the query parameter, then -** sqlite3_uri_parameter(F,P) returns the value of the P -** parameter if it exists or a NULL pointer if P does not appear as a -** query parameter on F. If P is a query parameter of F -** has no explicit value, then sqlite3_uri_parameter(F,P) returns -** a pointer to an empty string. -** -** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean -** parameter and returns true (1) or false (0) according to the value -** of P. The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the -** value of query parameter P is one of "yes", "true", or "on" in any -** case or if the value begins with a non-zero number. The -** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of -** query parameter P is one of "no", "false", or "off" in any case or -** if the value begins with a numeric zero. If P is not a query -** parameter on F or if the value of P is does not match any of the -** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0). -** -** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a -** 64-bit signed integer and returns that integer, or D if P does not -** exist. If the value of P is something other than an integer, then -** zero is returned. -** -** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and -** sqlite3_uri_boolean(F,P,B) returns B. If F is not a NULL pointer and -** is not a database file pathname pointer that SQLite passed into the xOpen -** VFS method, then the behavior of this routine is undefined and probably -** undesirable. -*/ -SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam); -SQLITE_API int sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault); -SQLITE_API sqlite3_int64 sqlite3_uri_int64(const char*, const char*, sqlite3_int64); - - -/* -** CAPI3REF: Error Codes And Messages -** -** ^The sqlite3_errcode() interface returns the numeric [result code] or -** [extended result code] for the most recent failed sqlite3_* API call -** associated with a [database connection]. If a prior API call failed -** but the most recent API call succeeded, the return value from -** sqlite3_errcode() is undefined. ^The sqlite3_extended_errcode() -** interface is the same except that it always returns the -** [extended result code] even when extended result codes are -** disabled. -** -** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language -** text that describes the error, as either UTF-8 or UTF-16 respectively. -** ^(Memory to hold the error message string is managed internally. -** The application does not need to worry about freeing the result. -** However, the error string might be overwritten or deallocated by -** subsequent calls to other SQLite interface functions.)^ -** -** ^The sqlite3_errstr() interface returns the English-language text -** that describes the [result code], as UTF-8. -** ^(Memory to hold the error message string is managed internally -** and must not be freed by the application)^. -** -** When the serialized [threading mode] is in use, it might be the -** case that a second error occurs on a separate thread in between -** the time of the first error and the call to these interfaces. -** When that happens, the second error will be reported since these -** interfaces always report the most recent result. To avoid -** this, each thread can obtain exclusive use of the [database connection] D -** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning -** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after -** all calls to the interfaces listed here are completed. -** -** If an interface fails with SQLITE_MISUSE, that means the interface -** was invoked incorrectly by the application. In that case, the -** error code and message may or may not be set. -*/ -SQLITE_API int sqlite3_errcode(sqlite3 *db); -SQLITE_API int sqlite3_extended_errcode(sqlite3 *db); -SQLITE_API const char *sqlite3_errmsg(sqlite3*); -SQLITE_API const void *sqlite3_errmsg16(sqlite3*); -SQLITE_API const char *sqlite3_errstr(int); - -/* -** CAPI3REF: SQL Statement Object -** KEYWORDS: {prepared statement} {prepared statements} -** -** An instance of this object represents a single SQL statement. -** This object is variously known as a "prepared statement" or a -** "compiled SQL statement" or simply as a "statement". -** -** The life of a statement object goes something like this: -** -**
      -**
    1. Create the object using [sqlite3_prepare_v2()] or a related -** function. -**
    2. Bind values to [host parameters] using the sqlite3_bind_*() -** interfaces. -**
    3. Run the SQL by calling [sqlite3_step()] one or more times. -**
    4. Reset the statement using [sqlite3_reset()] then go back -** to step 2. Do this zero or more times. -**
    5. Destroy the object using [sqlite3_finalize()]. -**
    -** -** Refer to documentation on individual methods above for additional -** information. -*/ -typedef struct sqlite3_stmt sqlite3_stmt; - -/* -** CAPI3REF: Run-time Limits -** -** ^(This interface allows the size of various constructs to be limited -** on a connection by connection basis. The first parameter is the -** [database connection] whose limit is to be set or queried. The -** second parameter is one of the [limit categories] that define a -** class of constructs to be size limited. The third parameter is the -** new limit for that construct.)^ -** -** ^If the new limit is a negative number, the limit is unchanged. -** ^(For each limit category SQLITE_LIMIT_NAME there is a -** [limits | hard upper bound] -** set at compile-time by a C preprocessor macro called -** [limits | SQLITE_MAX_NAME]. -** (The "_LIMIT_" in the name is changed to "_MAX_".))^ -** ^Attempts to increase a limit above its hard upper bound are -** silently truncated to the hard upper bound. -** -** ^Regardless of whether or not the limit was changed, the -** [sqlite3_limit()] interface returns the prior value of the limit. -** ^Hence, to find the current value of a limit without changing it, -** simply invoke this interface with the third parameter set to -1. -** -** Run-time limits are intended for use in applications that manage -** both their own internal database and also databases that are controlled -** by untrusted external sources. An example application might be a -** web browser that has its own databases for storing history and -** separate databases controlled by JavaScript applications downloaded -** off the Internet. The internal databases can be given the -** large, default limits. Databases managed by external sources can -** be given much smaller limits designed to prevent a denial of service -** attack. Developers might also want to use the [sqlite3_set_authorizer()] -** interface to further control untrusted SQL. The size of the database -** created by an untrusted script can be contained using the -** [max_page_count] [PRAGMA]. -** -** New run-time limit categories may be added in future releases. -*/ -SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal); - -/* -** CAPI3REF: Run-Time Limit Categories -** KEYWORDS: {limit category} {*limit categories} -** -** These constants define various performance limits -** that can be lowered at run-time using [sqlite3_limit()]. -** The synopsis of the meanings of the various limits is shown below. -** Additional information is available at [limits | Limits in SQLite]. -** -**
    -** [[SQLITE_LIMIT_LENGTH]] ^(
    SQLITE_LIMIT_LENGTH
    -**
    The maximum size of any string or BLOB or table row, in bytes.
    )^ -** -** [[SQLITE_LIMIT_SQL_LENGTH]] ^(
    SQLITE_LIMIT_SQL_LENGTH
    -**
    The maximum length of an SQL statement, in bytes.
    )^ -** -** [[SQLITE_LIMIT_COLUMN]] ^(
    SQLITE_LIMIT_COLUMN
    -**
    The maximum number of columns in a table definition or in the -** result set of a [SELECT] or the maximum number of columns in an index -** or in an ORDER BY or GROUP BY clause.
    )^ -** -** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(
    SQLITE_LIMIT_EXPR_DEPTH
    -**
    The maximum depth of the parse tree on any expression.
    )^ -** -** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(
    SQLITE_LIMIT_COMPOUND_SELECT
    -**
    The maximum number of terms in a compound SELECT statement.
    )^ -** -** [[SQLITE_LIMIT_VDBE_OP]] ^(
    SQLITE_LIMIT_VDBE_OP
    -**
    The maximum number of instructions in a virtual machine program -** used to implement an SQL statement. This limit is not currently -** enforced, though that might be added in some future release of -** SQLite.
    )^ -** -** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(
    SQLITE_LIMIT_FUNCTION_ARG
    -**
    The maximum number of arguments on a function.
    )^ -** -** [[SQLITE_LIMIT_ATTACHED]] ^(
    SQLITE_LIMIT_ATTACHED
    -**
    The maximum number of [ATTACH | attached databases].)^
    -** -** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]] -** ^(
    SQLITE_LIMIT_LIKE_PATTERN_LENGTH
    -**
    The maximum length of the pattern argument to the [LIKE] or -** [GLOB] operators.
    )^ -** -** [[SQLITE_LIMIT_VARIABLE_NUMBER]] -** ^(
    SQLITE_LIMIT_VARIABLE_NUMBER
    -**
    The maximum index number of any [parameter] in an SQL statement.)^ -** -** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(
    SQLITE_LIMIT_TRIGGER_DEPTH
    -**
    The maximum depth of recursion for triggers.
    )^ -**
    -*/ -#define SQLITE_LIMIT_LENGTH 0 -#define SQLITE_LIMIT_SQL_LENGTH 1 -#define SQLITE_LIMIT_COLUMN 2 -#define SQLITE_LIMIT_EXPR_DEPTH 3 -#define SQLITE_LIMIT_COMPOUND_SELECT 4 -#define SQLITE_LIMIT_VDBE_OP 5 -#define SQLITE_LIMIT_FUNCTION_ARG 6 -#define SQLITE_LIMIT_ATTACHED 7 -#define SQLITE_LIMIT_LIKE_PATTERN_LENGTH 8 -#define SQLITE_LIMIT_VARIABLE_NUMBER 9 -#define SQLITE_LIMIT_TRIGGER_DEPTH 10 - -/* -** CAPI3REF: Compiling An SQL Statement -** KEYWORDS: {SQL statement compiler} -** -** To execute an SQL query, it must first be compiled into a byte-code -** program using one of these routines. -** -** The first argument, "db", is a [database connection] obtained from a -** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or -** [sqlite3_open16()]. The database connection must not have been closed. -** -** The second argument, "zSql", is the statement to be compiled, encoded -** as either UTF-8 or UTF-16. The sqlite3_prepare() and sqlite3_prepare_v2() -** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2() -** use UTF-16. -** -** ^If the nByte argument is less than zero, then zSql is read up to the -** first zero terminator. ^If nByte is non-negative, then it is the maximum -** number of bytes read from zSql. ^When nByte is non-negative, the -** zSql string ends at either the first '\000' or '\u0000' character or -** the nByte-th byte, whichever comes first. If the caller knows -** that the supplied string is nul-terminated, then there is a small -** performance advantage to be gained by passing an nByte parameter that -** is equal to the number of bytes in the input string including -** the nul-terminator bytes as this saves SQLite from having to -** make a copy of the input string. -** -** ^If pzTail is not NULL then *pzTail is made to point to the first byte -** past the end of the first SQL statement in zSql. These routines only -** compile the first statement in zSql, so *pzTail is left pointing to -** what remains uncompiled. -** -** ^*ppStmt is left pointing to a compiled [prepared statement] that can be -** executed using [sqlite3_step()]. ^If there is an error, *ppStmt is set -** to NULL. ^If the input text contains no SQL (if the input is an empty -** string or a comment) then *ppStmt is set to NULL. -** The calling procedure is responsible for deleting the compiled -** SQL statement using [sqlite3_finalize()] after it has finished with it. -** ppStmt may not be NULL. -** -** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK]; -** otherwise an [error code] is returned. -** -** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are -** recommended for all new programs. The two older interfaces are retained -** for backwards compatibility, but their use is discouraged. -** ^In the "v2" interfaces, the prepared statement -** that is returned (the [sqlite3_stmt] object) contains a copy of the -** original SQL text. This causes the [sqlite3_step()] interface to -** behave differently in three ways: -** -**
      -**
    1. -** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it -** always used to do, [sqlite3_step()] will automatically recompile the SQL -** statement and try to run it again. -**
    2. -** -**
    3. -** ^When an error occurs, [sqlite3_step()] will return one of the detailed -** [error codes] or [extended error codes]. ^The legacy behavior was that -** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code -** and the application would have to make a second call to [sqlite3_reset()] -** in order to find the underlying cause of the problem. With the "v2" prepare -** interfaces, the underlying reason for the error is returned immediately. -**
    4. -** -**
    5. -** ^If the specific value bound to [parameter | host parameter] in the -** WHERE clause might influence the choice of query plan for a statement, -** then the statement will be automatically recompiled, as if there had been -** a schema change, on the first [sqlite3_step()] call following any change -** to the [sqlite3_bind_text | bindings] of that [parameter]. -** ^The specific value of WHERE-clause [parameter] might influence the -** choice of query plan if the parameter is the left-hand side of a [LIKE] -** or [GLOB] operator or if the parameter is compared to an indexed column -** and the [SQLITE_ENABLE_STAT3] compile-time option is enabled. -** the -**
    6. -**
    -*/ -SQLITE_API int sqlite3_prepare( - sqlite3 *db, /* Database handle */ - const char *zSql, /* SQL statement, UTF-8 encoded */ - int nByte, /* Maximum length of zSql in bytes. */ - sqlite3_stmt **ppStmt, /* OUT: Statement handle */ - const char **pzTail /* OUT: Pointer to unused portion of zSql */ -); -SQLITE_API int sqlite3_prepare_v2( - sqlite3 *db, /* Database handle */ - const char *zSql, /* SQL statement, UTF-8 encoded */ - int nByte, /* Maximum length of zSql in bytes. */ - sqlite3_stmt **ppStmt, /* OUT: Statement handle */ - const char **pzTail /* OUT: Pointer to unused portion of zSql */ -); -SQLITE_API int sqlite3_prepare16( - sqlite3 *db, /* Database handle */ - const void *zSql, /* SQL statement, UTF-16 encoded */ - int nByte, /* Maximum length of zSql in bytes. */ - sqlite3_stmt **ppStmt, /* OUT: Statement handle */ - const void **pzTail /* OUT: Pointer to unused portion of zSql */ -); -SQLITE_API int sqlite3_prepare16_v2( - sqlite3 *db, /* Database handle */ - const void *zSql, /* SQL statement, UTF-16 encoded */ - int nByte, /* Maximum length of zSql in bytes. */ - sqlite3_stmt **ppStmt, /* OUT: Statement handle */ - const void **pzTail /* OUT: Pointer to unused portion of zSql */ -); - -/* -** CAPI3REF: Retrieving Statement SQL -** -** ^This interface can be used to retrieve a saved copy of the original -** SQL text used to create a [prepared statement] if that statement was -** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()]. -*/ -SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt); - -/* -** CAPI3REF: Determine If An SQL Statement Writes The Database -** -** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if -** and only if the [prepared statement] X makes no direct changes to -** the content of the database file. -** -** Note that [application-defined SQL functions] or -** [virtual tables] might change the database indirectly as a side effect. -** ^(For example, if an application defines a function "eval()" that -** calls [sqlite3_exec()], then the following SQL statement would -** change the database file through side-effects: -** -**
    -**    SELECT eval('DELETE FROM t1') FROM t2;
    -** 
    -** -** But because the [SELECT] statement does not change the database file -** directly, sqlite3_stmt_readonly() would still return true.)^ -** -** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK], -** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true, -** since the statements themselves do not actually modify the database but -** rather they control the timing of when other statements modify the -** database. ^The [ATTACH] and [DETACH] statements also cause -** sqlite3_stmt_readonly() to return true since, while those statements -** change the configuration of a database connection, they do not make -** changes to the content of the database files on disk. -*/ -SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt); - -/* -** CAPI3REF: Determine If A Prepared Statement Has Been Reset -** -** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the -** [prepared statement] S has been stepped at least once using -** [sqlite3_step(S)] but has not run to completion and/or has not -** been reset using [sqlite3_reset(S)]. ^The sqlite3_stmt_busy(S) -** interface returns false if S is a NULL pointer. If S is not a -** NULL pointer and is not a pointer to a valid [prepared statement] -** object, then the behavior is undefined and probably undesirable. -** -** This interface can be used in combination [sqlite3_next_stmt()] -** to locate all prepared statements associated with a database -** connection that are in need of being reset. This can be used, -** for example, in diagnostic routines to search for prepared -** statements that are holding a transaction open. -*/ -SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*); - -/* -** CAPI3REF: Dynamically Typed Value Object -** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value} -** -** SQLite uses the sqlite3_value object to represent all values -** that can be stored in a database table. SQLite uses dynamic typing -** for the values it stores. ^Values stored in sqlite3_value objects -** can be integers, floating point values, strings, BLOBs, or NULL. -** -** An sqlite3_value object may be either "protected" or "unprotected". -** Some interfaces require a protected sqlite3_value. Other interfaces -** will accept either a protected or an unprotected sqlite3_value. -** Every interface that accepts sqlite3_value arguments specifies -** whether or not it requires a protected sqlite3_value. -** -** The terms "protected" and "unprotected" refer to whether or not -** a mutex is held. An internal mutex is held for a protected -** sqlite3_value object but no mutex is held for an unprotected -** sqlite3_value object. If SQLite is compiled to be single-threaded -** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0) -** or if SQLite is run in one of reduced mutex modes -** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD] -** then there is no distinction between protected and unprotected -** sqlite3_value objects and they can be used interchangeably. However, -** for maximum code portability it is recommended that applications -** still make the distinction between protected and unprotected -** sqlite3_value objects even when not strictly required. -** -** ^The sqlite3_value objects that are passed as parameters into the -** implementation of [application-defined SQL functions] are protected. -** ^The sqlite3_value object returned by -** [sqlite3_column_value()] is unprotected. -** Unprotected sqlite3_value objects may only be used with -** [sqlite3_result_value()] and [sqlite3_bind_value()]. -** The [sqlite3_value_blob | sqlite3_value_type()] family of -** interfaces require protected sqlite3_value objects. -*/ -typedef struct Mem sqlite3_value; - -/* -** CAPI3REF: SQL Function Context Object -** -** The context in which an SQL function executes is stored in an -** sqlite3_context object. ^A pointer to an sqlite3_context object -** is always first parameter to [application-defined SQL functions]. -** The application-defined SQL function implementation will pass this -** pointer through into calls to [sqlite3_result_int | sqlite3_result()], -** [sqlite3_aggregate_context()], [sqlite3_user_data()], -** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()], -** and/or [sqlite3_set_auxdata()]. -*/ -typedef struct sqlite3_context sqlite3_context; - -/* -** CAPI3REF: Binding Values To Prepared Statements -** KEYWORDS: {host parameter} {host parameters} {host parameter name} -** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding} -** -** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants, -** literals may be replaced by a [parameter] that matches one of following -** templates: -** -**
      -**
    • ? -**
    • ?NNN -**
    • :VVV -**
    • @VVV -**
    • $VVV -**
    -** -** In the templates above, NNN represents an integer literal, -** and VVV represents an alphanumeric identifier.)^ ^The values of these -** parameters (also called "host parameter names" or "SQL parameters") -** can be set using the sqlite3_bind_*() routines defined here. -** -** ^The first argument to the sqlite3_bind_*() routines is always -** a pointer to the [sqlite3_stmt] object returned from -** [sqlite3_prepare_v2()] or its variants. -** -** ^The second argument is the index of the SQL parameter to be set. -** ^The leftmost SQL parameter has an index of 1. ^When the same named -** SQL parameter is used more than once, second and subsequent -** occurrences have the same index as the first occurrence. -** ^The index for named parameters can be looked up using the -** [sqlite3_bind_parameter_index()] API if desired. ^The index -** for "?NNN" parameters is the value of NNN. -** ^The NNN value must be between 1 and the [sqlite3_limit()] -** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999). -** -** ^The third argument is the value to bind to the parameter. -** -** ^(In those routines that have a fourth argument, its value is the -** number of bytes in the parameter. To be clear: the value is the -** number of bytes in the value, not the number of characters.)^ -** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16() -** is negative, then the length of the string is -** the number of bytes up to the first zero terminator. -** If the fourth parameter to sqlite3_bind_blob() is negative, then -** the behavior is undefined. -** If a non-negative fourth parameter is provided to sqlite3_bind_text() -** or sqlite3_bind_text16() then that parameter must be the byte offset -** where the NUL terminator would occur assuming the string were NUL -** terminated. If any NUL characters occur at byte offsets less than -** the value of the fourth parameter then the resulting string value will -** contain embedded NULs. The result of expressions involving strings -** with embedded NULs is undefined. -** -** ^The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and -** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or -** string after SQLite has finished with it. ^The destructor is called -** to dispose of the BLOB or string even if the call to sqlite3_bind_blob(), -** sqlite3_bind_text(), or sqlite3_bind_text16() fails. -** ^If the fifth argument is -** the special value [SQLITE_STATIC], then SQLite assumes that the -** information is in static, unmanaged space and does not need to be freed. -** ^If the fifth argument has the value [SQLITE_TRANSIENT], then -** SQLite makes its own private copy of the data immediately, before -** the sqlite3_bind_*() routine returns. -** -** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that -** is filled with zeroes. ^A zeroblob uses a fixed amount of memory -** (just an integer to hold its size) while it is being processed. -** Zeroblobs are intended to serve as placeholders for BLOBs whose -** content is later written using -** [sqlite3_blob_open | incremental BLOB I/O] routines. -** ^A negative value for the zeroblob results in a zero-length BLOB. -** -** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer -** for the [prepared statement] or with a prepared statement for which -** [sqlite3_step()] has been called more recently than [sqlite3_reset()], -** then the call will return [SQLITE_MISUSE]. If any sqlite3_bind_() -** routine is passed a [prepared statement] that has been finalized, the -** result is undefined and probably harmful. -** -** ^Bindings are not cleared by the [sqlite3_reset()] routine. -** ^Unbound parameters are interpreted as NULL. -** -** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an -** [error code] if anything goes wrong. -** ^[SQLITE_RANGE] is returned if the parameter -** index is out of range. ^[SQLITE_NOMEM] is returned if malloc() fails. -** -** See also: [sqlite3_bind_parameter_count()], -** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()]. -*/ -SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*)); -SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double); -SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int); -SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64); -SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int); -SQLITE_API int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*)); -SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*)); -SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*); -SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n); - -/* -** CAPI3REF: Number Of SQL Parameters -** -** ^This routine can be used to find the number of [SQL parameters] -** in a [prepared statement]. SQL parameters are tokens of the -** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as -** placeholders for values that are [sqlite3_bind_blob | bound] -** to the parameters at a later time. -** -** ^(This routine actually returns the index of the largest (rightmost) -** parameter. For all forms except ?NNN, this will correspond to the -** number of unique parameters. If parameters of the ?NNN form are used, -** there may be gaps in the list.)^ -** -** See also: [sqlite3_bind_blob|sqlite3_bind()], -** [sqlite3_bind_parameter_name()], and -** [sqlite3_bind_parameter_index()]. -*/ -SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*); - -/* -** CAPI3REF: Name Of A Host Parameter -** -** ^The sqlite3_bind_parameter_name(P,N) interface returns -** the name of the N-th [SQL parameter] in the [prepared statement] P. -** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA" -** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA" -** respectively. -** In other words, the initial ":" or "$" or "@" or "?" -** is included as part of the name.)^ -** ^Parameters of the form "?" without a following integer have no name -** and are referred to as "nameless" or "anonymous parameters". -** -** ^The first host parameter has an index of 1, not 0. -** -** ^If the value N is out of range or if the N-th parameter is -** nameless, then NULL is returned. ^The returned string is -** always in UTF-8 encoding even if the named parameter was -** originally specified as UTF-16 in [sqlite3_prepare16()] or -** [sqlite3_prepare16_v2()]. -** -** See also: [sqlite3_bind_blob|sqlite3_bind()], -** [sqlite3_bind_parameter_count()], and -** [sqlite3_bind_parameter_index()]. -*/ -SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int); - -/* -** CAPI3REF: Index Of A Parameter With A Given Name -** -** ^Return the index of an SQL parameter given its name. ^The -** index value returned is suitable for use as the second -** parameter to [sqlite3_bind_blob|sqlite3_bind()]. ^A zero -** is returned if no matching parameter is found. ^The parameter -** name must be given in UTF-8 even if the original statement -** was prepared from UTF-16 text using [sqlite3_prepare16_v2()]. -** -** See also: [sqlite3_bind_blob|sqlite3_bind()], -** [sqlite3_bind_parameter_count()], and -** [sqlite3_bind_parameter_index()]. -*/ -SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName); - -/* -** CAPI3REF: Reset All Bindings On A Prepared Statement -** -** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset -** the [sqlite3_bind_blob | bindings] on a [prepared statement]. -** ^Use this routine to reset all host parameters to NULL. -*/ -SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*); - -/* -** CAPI3REF: Number Of Columns In A Result Set -** -** ^Return the number of columns in the result set returned by the -** [prepared statement]. ^This routine returns 0 if pStmt is an SQL -** statement that does not return data (for example an [UPDATE]). -** -** See also: [sqlite3_data_count()] -*/ -SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt); - -/* -** CAPI3REF: Column Names In A Result Set -** -** ^These routines return the name assigned to a particular column -** in the result set of a [SELECT] statement. ^The sqlite3_column_name() -** interface returns a pointer to a zero-terminated UTF-8 string -** and sqlite3_column_name16() returns a pointer to a zero-terminated -** UTF-16 string. ^The first parameter is the [prepared statement] -** that implements the [SELECT] statement. ^The second parameter is the -** column number. ^The leftmost column is number 0. -** -** ^The returned string pointer is valid until either the [prepared statement] -** is destroyed by [sqlite3_finalize()] or until the statement is automatically -** reprepared by the first call to [sqlite3_step()] for a particular run -** or until the next call to -** sqlite3_column_name() or sqlite3_column_name16() on the same column. -** -** ^If sqlite3_malloc() fails during the processing of either routine -** (for example during a conversion from UTF-8 to UTF-16) then a -** NULL pointer is returned. -** -** ^The name of a result column is the value of the "AS" clause for -** that column, if there is an AS clause. If there is no AS clause -** then the name of the column is unspecified and may change from -** one release of SQLite to the next. -*/ -SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N); -SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N); - -/* -** CAPI3REF: Source Of Data In A Query Result -** -** ^These routines provide a means to determine the database, table, and -** table column that is the origin of a particular result column in -** [SELECT] statement. -** ^The name of the database or table or column can be returned as -** either a UTF-8 or UTF-16 string. ^The _database_ routines return -** the database name, the _table_ routines return the table name, and -** the origin_ routines return the column name. -** ^The returned string is valid until the [prepared statement] is destroyed -** using [sqlite3_finalize()] or until the statement is automatically -** reprepared by the first call to [sqlite3_step()] for a particular run -** or until the same information is requested -** again in a different encoding. -** -** ^The names returned are the original un-aliased names of the -** database, table, and column. -** -** ^The first argument to these interfaces is a [prepared statement]. -** ^These functions return information about the Nth result column returned by -** the statement, where N is the second function argument. -** ^The left-most column is column 0 for these routines. -** -** ^If the Nth column returned by the statement is an expression or -** subquery and is not a column value, then all of these functions return -** NULL. ^These routine might also return NULL if a memory allocation error -** occurs. ^Otherwise, they return the name of the attached database, table, -** or column that query result column was extracted from. -** -** ^As with all other SQLite APIs, those whose names end with "16" return -** UTF-16 encoded strings and the other functions return UTF-8. -** -** ^These APIs are only available if the library was compiled with the -** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol. -** -** If two or more threads call one or more of these routines against the same -** prepared statement and column at the same time then the results are -** undefined. -** -** If two or more threads call one or more -** [sqlite3_column_database_name | column metadata interfaces] -** for the same [prepared statement] and result column -** at the same time then the results are undefined. -*/ -SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int); -SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int); -SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int); -SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int); -SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int); -SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int); - -/* -** CAPI3REF: Declared Datatype Of A Query Result -** -** ^(The first parameter is a [prepared statement]. -** If this statement is a [SELECT] statement and the Nth column of the -** returned result set of that [SELECT] is a table column (not an -** expression or subquery) then the declared type of the table -** column is returned.)^ ^If the Nth column of the result set is an -** expression or subquery, then a NULL pointer is returned. -** ^The returned string is always UTF-8 encoded. -** -** ^(For example, given the database schema: -** -** CREATE TABLE t1(c1 VARIANT); -** -** and the following statement to be compiled: -** -** SELECT c1 + 1, c1 FROM t1; -** -** this routine would return the string "VARIANT" for the second result -** column (i==1), and a NULL pointer for the first result column (i==0).)^ -** -** ^SQLite uses dynamic run-time typing. ^So just because a column -** is declared to contain a particular type does not mean that the -** data stored in that column is of the declared type. SQLite is -** strongly typed, but the typing is dynamic not static. ^Type -** is associated with individual values, not with the containers -** used to hold those values. -*/ -SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int); -SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int); - -/* -** CAPI3REF: Evaluate An SQL Statement -** -** After a [prepared statement] has been prepared using either -** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy -** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function -** must be called one or more times to evaluate the statement. -** -** The details of the behavior of the sqlite3_step() interface depend -** on whether the statement was prepared using the newer "v2" interface -** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy -** interface [sqlite3_prepare()] and [sqlite3_prepare16()]. The use of the -** new "v2" interface is recommended for new applications but the legacy -** interface will continue to be supported. -** -** ^In the legacy interface, the return value will be either [SQLITE_BUSY], -** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE]. -** ^With the "v2" interface, any of the other [result codes] or -** [extended result codes] might be returned as well. -** -** ^[SQLITE_BUSY] means that the database engine was unable to acquire the -** database locks it needs to do its job. ^If the statement is a [COMMIT] -** or occurs outside of an explicit transaction, then you can retry the -** statement. If the statement is not a [COMMIT] and occurs within an -** explicit transaction then you should rollback the transaction before -** continuing. -** -** ^[SQLITE_DONE] means that the statement has finished executing -** successfully. sqlite3_step() should not be called again on this virtual -** machine without first calling [sqlite3_reset()] to reset the virtual -** machine back to its initial state. -** -** ^If the SQL statement being executed returns any data, then [SQLITE_ROW] -** is returned each time a new row of data is ready for processing by the -** caller. The values may be accessed using the [column access functions]. -** sqlite3_step() is called again to retrieve the next row of data. -** -** ^[SQLITE_ERROR] means that a run-time error (such as a constraint -** violation) has occurred. sqlite3_step() should not be called again on -** the VM. More information may be found by calling [sqlite3_errmsg()]. -** ^With the legacy interface, a more specific error code (for example, -** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth) -** can be obtained by calling [sqlite3_reset()] on the -** [prepared statement]. ^In the "v2" interface, -** the more specific error code is returned directly by sqlite3_step(). -** -** [SQLITE_MISUSE] means that the this routine was called inappropriately. -** Perhaps it was called on a [prepared statement] that has -** already been [sqlite3_finalize | finalized] or on one that had -** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could -** be the case that the same database connection is being used by two or -** more threads at the same moment in time. -** -** For all versions of SQLite up to and including 3.6.23.1, a call to -** [sqlite3_reset()] was required after sqlite3_step() returned anything -** other than [SQLITE_ROW] before any subsequent invocation of -** sqlite3_step(). Failure to reset the prepared statement using -** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from -** sqlite3_step(). But after version 3.6.23.1, sqlite3_step() began -** calling [sqlite3_reset()] automatically in this circumstance rather -** than returning [SQLITE_MISUSE]. This is not considered a compatibility -** break because any application that ever receives an SQLITE_MISUSE error -** is broken by definition. The [SQLITE_OMIT_AUTORESET] compile-time option -** can be used to restore the legacy behavior. -** -** Goofy Interface Alert: In the legacy interface, the sqlite3_step() -** API always returns a generic error code, [SQLITE_ERROR], following any -** error other than [SQLITE_BUSY] and [SQLITE_MISUSE]. You must call -** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the -** specific [error codes] that better describes the error. -** We admit that this is a goofy design. The problem has been fixed -** with the "v2" interface. If you prepare all of your SQL statements -** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead -** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces, -** then the more specific [error codes] are returned directly -** by sqlite3_step(). The use of the "v2" interface is recommended. -*/ -SQLITE_API int sqlite3_step(sqlite3_stmt*); - -/* -** CAPI3REF: Number of columns in a result set -** -** ^The sqlite3_data_count(P) interface returns the number of columns in the -** current row of the result set of [prepared statement] P. -** ^If prepared statement P does not have results ready to return -** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of -** interfaces) then sqlite3_data_count(P) returns 0. -** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer. -** ^The sqlite3_data_count(P) routine returns 0 if the previous call to -** [sqlite3_step](P) returned [SQLITE_DONE]. ^The sqlite3_data_count(P) -** will return non-zero if previous call to [sqlite3_step](P) returned -** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum] -** where it always returns zero since each step of that multi-step -** pragma returns 0 columns of data. -** -** See also: [sqlite3_column_count()] -*/ -SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt); - -/* -** CAPI3REF: Fundamental Datatypes -** KEYWORDS: SQLITE_TEXT -** -** ^(Every value in SQLite has one of five fundamental datatypes: -** -**
      -**
    • 64-bit signed integer -**
    • 64-bit IEEE floating point number -**
    • string -**
    • BLOB -**
    • NULL -**
    )^ -** -** These constants are codes for each of those types. -** -** Note that the SQLITE_TEXT constant was also used in SQLite version 2 -** for a completely different meaning. Software that links against both -** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not -** SQLITE_TEXT. -*/ -#define SQLITE_INTEGER 1 -#define SQLITE_FLOAT 2 -#define SQLITE_BLOB 4 -#define SQLITE_NULL 5 -#ifdef SQLITE_TEXT -# undef SQLITE_TEXT -#else -# define SQLITE_TEXT 3 -#endif -#define SQLITE3_TEXT 3 - -/* -** CAPI3REF: Result Values From A Query -** KEYWORDS: {column access functions} -** -** These routines form the "result set" interface. -** -** ^These routines return information about a single column of the current -** result row of a query. ^In every case the first argument is a pointer -** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*] -** that was returned from [sqlite3_prepare_v2()] or one of its variants) -** and the second argument is the index of the column for which information -** should be returned. ^The leftmost column of the result set has the index 0. -** ^The number of columns in the result can be determined using -** [sqlite3_column_count()]. -** -** If the SQL statement does not currently point to a valid row, or if the -** column index is out of range, the result is undefined. -** These routines may only be called when the most recent call to -** [sqlite3_step()] has returned [SQLITE_ROW] and neither -** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently. -** If any of these routines are called after [sqlite3_reset()] or -** [sqlite3_finalize()] or after [sqlite3_step()] has returned -** something other than [SQLITE_ROW], the results are undefined. -** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()] -** are called from a different thread while any of these routines -** are pending, then the results are undefined. -** -** ^The sqlite3_column_type() routine returns the -** [SQLITE_INTEGER | datatype code] for the initial data type -** of the result column. ^The returned value is one of [SQLITE_INTEGER], -** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL]. The value -** returned by sqlite3_column_type() is only meaningful if no type -** conversions have occurred as described below. After a type conversion, -** the value returned by sqlite3_column_type() is undefined. Future -** versions of SQLite may change the behavior of sqlite3_column_type() -** following a type conversion. -** -** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes() -** routine returns the number of bytes in that BLOB or string. -** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts -** the string to UTF-8 and then returns the number of bytes. -** ^If the result is a numeric value then sqlite3_column_bytes() uses -** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns -** the number of bytes in that string. -** ^If the result is NULL, then sqlite3_column_bytes() returns zero. -** -** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16() -** routine returns the number of bytes in that BLOB or string. -** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts -** the string to UTF-16 and then returns the number of bytes. -** ^If the result is a numeric value then sqlite3_column_bytes16() uses -** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns -** the number of bytes in that string. -** ^If the result is NULL, then sqlite3_column_bytes16() returns zero. -** -** ^The values returned by [sqlite3_column_bytes()] and -** [sqlite3_column_bytes16()] do not include the zero terminators at the end -** of the string. ^For clarity: the values returned by -** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of -** bytes in the string, not the number of characters. -** -** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(), -** even empty strings, are always zero-terminated. ^The return -** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer. -** -** ^The object returned by [sqlite3_column_value()] is an -** [unprotected sqlite3_value] object. An unprotected sqlite3_value object -** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()]. -** If the [unprotected sqlite3_value] object returned by -** [sqlite3_column_value()] is used in any other way, including calls -** to routines like [sqlite3_value_int()], [sqlite3_value_text()], -** or [sqlite3_value_bytes()], then the behavior is undefined. -** -** These routines attempt to convert the value where appropriate. ^For -** example, if the internal representation is FLOAT and a text result -** is requested, [sqlite3_snprintf()] is used internally to perform the -** conversion automatically. ^(The following table details the conversions -** that are applied: -** -**
    -** -**
    Internal
    Type
    Requested
    Type
    Conversion -** -**
    NULL INTEGER Result is 0 -**
    NULL FLOAT Result is 0.0 -**
    NULL TEXT Result is NULL pointer -**
    NULL BLOB Result is NULL pointer -**
    INTEGER FLOAT Convert from integer to float -**
    INTEGER TEXT ASCII rendering of the integer -**
    INTEGER BLOB Same as INTEGER->TEXT -**
    FLOAT INTEGER Convert from float to integer -**
    FLOAT TEXT ASCII rendering of the float -**
    FLOAT BLOB Same as FLOAT->TEXT -**
    TEXT INTEGER Use atoi() -**
    TEXT FLOAT Use atof() -**
    TEXT BLOB No change -**
    BLOB INTEGER Convert to TEXT then use atoi() -**
    BLOB FLOAT Convert to TEXT then use atof() -**
    BLOB TEXT Add a zero terminator if needed -**
    -**
    )^ -** -** The table above makes reference to standard C library functions atoi() -** and atof(). SQLite does not really use these functions. It has its -** own equivalent internal routines. The atoi() and atof() names are -** used in the table for brevity and because they are familiar to most -** C programmers. -** -** Note that when type conversions occur, pointers returned by prior -** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or -** sqlite3_column_text16() may be invalidated. -** Type conversions and pointer invalidations might occur -** in the following cases: -** -**
      -**
    • The initial content is a BLOB and sqlite3_column_text() or -** sqlite3_column_text16() is called. A zero-terminator might -** need to be added to the string.
    • -**
    • The initial content is UTF-8 text and sqlite3_column_bytes16() or -** sqlite3_column_text16() is called. The content must be converted -** to UTF-16.
    • -**
    • The initial content is UTF-16 text and sqlite3_column_bytes() or -** sqlite3_column_text() is called. The content must be converted -** to UTF-8.
    • -**
    -** -** ^Conversions between UTF-16be and UTF-16le are always done in place and do -** not invalidate a prior pointer, though of course the content of the buffer -** that the prior pointer references will have been modified. Other kinds -** of conversion are done in place when it is possible, but sometimes they -** are not possible and in those cases prior pointers are invalidated. -** -** The safest and easiest to remember policy is to invoke these routines -** in one of the following ways: -** -**
      -**
    • sqlite3_column_text() followed by sqlite3_column_bytes()
    • -**
    • sqlite3_column_blob() followed by sqlite3_column_bytes()
    • -**
    • sqlite3_column_text16() followed by sqlite3_column_bytes16()
    • -**
    -** -** In other words, you should call sqlite3_column_text(), -** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result -** into the desired format, then invoke sqlite3_column_bytes() or -** sqlite3_column_bytes16() to find the size of the result. Do not mix calls -** to sqlite3_column_text() or sqlite3_column_blob() with calls to -** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16() -** with calls to sqlite3_column_bytes(). -** -** ^The pointers returned are valid until a type conversion occurs as -** described above, or until [sqlite3_step()] or [sqlite3_reset()] or -** [sqlite3_finalize()] is called. ^The memory space used to hold strings -** and BLOBs is freed automatically. Do not pass the pointers returned -** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into -** [sqlite3_free()]. -** -** ^(If a memory allocation error occurs during the evaluation of any -** of these routines, a default value is returned. The default value -** is either the integer 0, the floating point number 0.0, or a NULL -** pointer. Subsequent calls to [sqlite3_errcode()] will return -** [SQLITE_NOMEM].)^ -*/ -SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol); -SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol); -SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol); -SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol); -SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol); -SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol); -SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol); -SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol); -SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol); -SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol); - -/* -** CAPI3REF: Destroy A Prepared Statement Object -** -** ^The sqlite3_finalize() function is called to delete a [prepared statement]. -** ^If the most recent evaluation of the statement encountered no errors -** or if the statement is never been evaluated, then sqlite3_finalize() returns -** SQLITE_OK. ^If the most recent evaluation of statement S failed, then -** sqlite3_finalize(S) returns the appropriate [error code] or -** [extended error code]. -** -** ^The sqlite3_finalize(S) routine can be called at any point during -** the life cycle of [prepared statement] S: -** before statement S is ever evaluated, after -** one or more calls to [sqlite3_reset()], or after any call -** to [sqlite3_step()] regardless of whether or not the statement has -** completed execution. -** -** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op. -** -** The application must finalize every [prepared statement] in order to avoid -** resource leaks. It is a grievous error for the application to try to use -** a prepared statement after it has been finalized. Any use of a prepared -** statement after it has been finalized can result in undefined and -** undesirable behavior such as segfaults and heap corruption. -*/ -SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt); - -/* -** CAPI3REF: Reset A Prepared Statement Object -** -** The sqlite3_reset() function is called to reset a [prepared statement] -** object back to its initial state, ready to be re-executed. -** ^Any SQL statement variables that had values bound to them using -** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values. -** Use [sqlite3_clear_bindings()] to reset the bindings. -** -** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S -** back to the beginning of its program. -** -** ^If the most recent call to [sqlite3_step(S)] for the -** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE], -** or if [sqlite3_step(S)] has never before been called on S, -** then [sqlite3_reset(S)] returns [SQLITE_OK]. -** -** ^If the most recent call to [sqlite3_step(S)] for the -** [prepared statement] S indicated an error, then -** [sqlite3_reset(S)] returns an appropriate [error code]. -** -** ^The [sqlite3_reset(S)] interface does not change the values -** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S. -*/ -SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt); - -/* -** CAPI3REF: Create Or Redefine SQL Functions -** KEYWORDS: {function creation routines} -** KEYWORDS: {application-defined SQL function} -** KEYWORDS: {application-defined SQL functions} -** -** ^These functions (collectively known as "function creation routines") -** are used to add SQL functions or aggregates or to redefine the behavior -** of existing SQL functions or aggregates. The only differences between -** these routines are the text encoding expected for -** the second parameter (the name of the function being created) -** and the presence or absence of a destructor callback for -** the application data pointer. -** -** ^The first parameter is the [database connection] to which the SQL -** function is to be added. ^If an application uses more than one database -** connection then application-defined SQL functions must be added -** to each database connection separately. -** -** ^The second parameter is the name of the SQL function to be created or -** redefined. ^The length of the name is limited to 255 bytes in a UTF-8 -** representation, exclusive of the zero-terminator. ^Note that the name -** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes. -** ^Any attempt to create a function with a longer name -** will result in [SQLITE_MISUSE] being returned. -** -** ^The third parameter (nArg) -** is the number of arguments that the SQL function or -** aggregate takes. ^If this parameter is -1, then the SQL function or -** aggregate may take any number of arguments between 0 and the limit -** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]). If the third -** parameter is less than -1 or greater than 127 then the behavior is -** undefined. -** -** ^The fourth parameter, eTextRep, specifies what -** [SQLITE_UTF8 | text encoding] this SQL function prefers for -** its parameters. Every SQL function implementation must be able to work -** with UTF-8, UTF-16le, or UTF-16be. But some implementations may be -** more efficient with one encoding than another. ^An application may -** invoke sqlite3_create_function() or sqlite3_create_function16() multiple -** times with the same function but with different values of eTextRep. -** ^When multiple implementations of the same function are available, SQLite -** will pick the one that involves the least amount of data conversion. -** If there is only a single implementation which does not care what text -** encoding is used, then the fourth argument should be [SQLITE_ANY]. -** -** ^(The fifth parameter is an arbitrary pointer. The implementation of the -** function can gain access to this pointer using [sqlite3_user_data()].)^ -** -** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are -** pointers to C-language functions that implement the SQL function or -** aggregate. ^A scalar SQL function requires an implementation of the xFunc -** callback only; NULL pointers must be passed as the xStep and xFinal -** parameters. ^An aggregate SQL function requires an implementation of xStep -** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing -** SQL function or aggregate, pass NULL pointers for all three function -** callbacks. -** -** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL, -** then it is destructor for the application data pointer. -** The destructor is invoked when the function is deleted, either by being -** overloaded or when the database connection closes.)^ -** ^The destructor is also invoked if the call to -** sqlite3_create_function_v2() fails. -** ^When the destructor callback of the tenth parameter is invoked, it -** is passed a single argument which is a copy of the application data -** pointer which was the fifth parameter to sqlite3_create_function_v2(). -** -** ^It is permitted to register multiple implementations of the same -** functions with the same name but with either differing numbers of -** arguments or differing preferred text encodings. ^SQLite will use -** the implementation that most closely matches the way in which the -** SQL function is used. ^A function implementation with a non-negative -** nArg parameter is a better match than a function implementation with -** a negative nArg. ^A function where the preferred text encoding -** matches the database encoding is a better -** match than a function where the encoding is different. -** ^A function where the encoding difference is between UTF16le and UTF16be -** is a closer match than a function where the encoding difference is -** between UTF8 and UTF16. -** -** ^Built-in functions may be overloaded by new application-defined functions. -** -** ^An application-defined function is permitted to call other -** SQLite interfaces. However, such calls must not -** close the database connection nor finalize or reset the prepared -** statement in which the function is running. -*/ -SQLITE_API int sqlite3_create_function( - sqlite3 *db, - const char *zFunctionName, - int nArg, - int eTextRep, - void *pApp, - void (*xFunc)(sqlite3_context*,int,sqlite3_value**), - void (*xStep)(sqlite3_context*,int,sqlite3_value**), - void (*xFinal)(sqlite3_context*) -); -SQLITE_API int sqlite3_create_function16( - sqlite3 *db, - const void *zFunctionName, - int nArg, - int eTextRep, - void *pApp, - void (*xFunc)(sqlite3_context*,int,sqlite3_value**), - void (*xStep)(sqlite3_context*,int,sqlite3_value**), - void (*xFinal)(sqlite3_context*) -); -SQLITE_API int sqlite3_create_function_v2( - sqlite3 *db, - const char *zFunctionName, - int nArg, - int eTextRep, - void *pApp, - void (*xFunc)(sqlite3_context*,int,sqlite3_value**), - void (*xStep)(sqlite3_context*,int,sqlite3_value**), - void (*xFinal)(sqlite3_context*), - void(*xDestroy)(void*) -); - -/* -** CAPI3REF: Text Encodings -** -** These constant define integer codes that represent the various -** text encodings supported by SQLite. -*/ -#define SQLITE_UTF8 1 -#define SQLITE_UTF16LE 2 -#define SQLITE_UTF16BE 3 -#define SQLITE_UTF16 4 /* Use native byte order */ -#define SQLITE_ANY 5 /* sqlite3_create_function only */ -#define SQLITE_UTF16_ALIGNED 8 /* sqlite3_create_collation only */ - -/* -** CAPI3REF: Deprecated Functions -** DEPRECATED -** -** These functions are [deprecated]. In order to maintain -** backwards compatibility with older code, these functions continue -** to be supported. However, new applications should avoid -** the use of these functions. To help encourage people to avoid -** using these functions, we are not going to tell you what they do. -*/ -#ifndef SQLITE_OMIT_DEPRECATED -SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*); -SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*); -SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*); -SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void); -SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void); -SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int), - void*,sqlite3_int64); -#endif - -/* -** CAPI3REF: Obtaining SQL Function Parameter Values -** -** The C-language implementation of SQL functions and aggregates uses -** this set of interface routines to access the parameter values on -** the function or aggregate. -** -** The xFunc (for scalar functions) or xStep (for aggregates) parameters -** to [sqlite3_create_function()] and [sqlite3_create_function16()] -** define callbacks that implement the SQL functions and aggregates. -** The 3rd parameter to these callbacks is an array of pointers to -** [protected sqlite3_value] objects. There is one [sqlite3_value] object for -** each parameter to the SQL function. These routines are used to -** extract values from the [sqlite3_value] objects. -** -** These routines work only with [protected sqlite3_value] objects. -** Any attempt to use these routines on an [unprotected sqlite3_value] -** object results in undefined behavior. -** -** ^These routines work just like the corresponding [column access functions] -** except that these routines take a single [protected sqlite3_value] object -** pointer instead of a [sqlite3_stmt*] pointer and an integer column number. -** -** ^The sqlite3_value_text16() interface extracts a UTF-16 string -** in the native byte-order of the host machine. ^The -** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces -** extract UTF-16 strings as big-endian and little-endian respectively. -** -** ^(The sqlite3_value_numeric_type() interface attempts to apply -** numeric affinity to the value. This means that an attempt is -** made to convert the value to an integer or floating point. If -** such a conversion is possible without loss of information (in other -** words, if the value is a string that looks like a number) -** then the conversion is performed. Otherwise no conversion occurs. -** The [SQLITE_INTEGER | datatype] after conversion is returned.)^ -** -** Please pay particular attention to the fact that the pointer returned -** from [sqlite3_value_blob()], [sqlite3_value_text()], or -** [sqlite3_value_text16()] can be invalidated by a subsequent call to -** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()], -** or [sqlite3_value_text16()]. -** -** These routines must be called from the same thread as -** the SQL function that supplied the [sqlite3_value*] parameters. -*/ -SQLITE_API const void *sqlite3_value_blob(sqlite3_value*); -SQLITE_API int sqlite3_value_bytes(sqlite3_value*); -SQLITE_API int sqlite3_value_bytes16(sqlite3_value*); -SQLITE_API double sqlite3_value_double(sqlite3_value*); -SQLITE_API int sqlite3_value_int(sqlite3_value*); -SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*); -SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*); -SQLITE_API const void *sqlite3_value_text16(sqlite3_value*); -SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*); -SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*); -SQLITE_API int sqlite3_value_type(sqlite3_value*); -SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*); - -/* -** CAPI3REF: Obtain Aggregate Function Context -** -** Implementations of aggregate SQL functions use this -** routine to allocate memory for storing their state. -** -** ^The first time the sqlite3_aggregate_context(C,N) routine is called -** for a particular aggregate function, SQLite -** allocates N of memory, zeroes out that memory, and returns a pointer -** to the new memory. ^On second and subsequent calls to -** sqlite3_aggregate_context() for the same aggregate function instance, -** the same buffer is returned. Sqlite3_aggregate_context() is normally -** called once for each invocation of the xStep callback and then one -** last time when the xFinal callback is invoked. ^(When no rows match -** an aggregate query, the xStep() callback of the aggregate function -** implementation is never called and xFinal() is called exactly once. -** In those cases, sqlite3_aggregate_context() might be called for the -** first time from within xFinal().)^ -** -** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer -** when first called if N is less than or equal to zero or if a memory -** allocate error occurs. -** -** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is -** determined by the N parameter on first successful call. Changing the -** value of N in subsequent call to sqlite3_aggregate_context() within -** the same aggregate function instance will not resize the memory -** allocation.)^ Within the xFinal callback, it is customary to set -** N=0 in calls to sqlite3_aggregate_context(C,N) so that no -** pointless memory allocations occur. -** -** ^SQLite automatically frees the memory allocated by -** sqlite3_aggregate_context() when the aggregate query concludes. -** -** The first parameter must be a copy of the -** [sqlite3_context | SQL function context] that is the first parameter -** to the xStep or xFinal callback routine that implements the aggregate -** function. -** -** This routine must be called from the same thread in which -** the aggregate SQL function is running. -*/ -SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes); - -/* -** CAPI3REF: User Data For Functions -** -** ^The sqlite3_user_data() interface returns a copy of -** the pointer that was the pUserData parameter (the 5th parameter) -** of the [sqlite3_create_function()] -** and [sqlite3_create_function16()] routines that originally -** registered the application defined function. -** -** This routine must be called from the same thread in which -** the application-defined function is running. -*/ -SQLITE_API void *sqlite3_user_data(sqlite3_context*); - -/* -** CAPI3REF: Database Connection For Functions -** -** ^The sqlite3_context_db_handle() interface returns a copy of -** the pointer to the [database connection] (the 1st parameter) -** of the [sqlite3_create_function()] -** and [sqlite3_create_function16()] routines that originally -** registered the application defined function. -*/ -SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*); - -/* -** CAPI3REF: Function Auxiliary Data -** -** The following two functions may be used by scalar SQL functions to -** associate metadata with argument values. If the same value is passed to -** multiple invocations of the same SQL function during query execution, under -** some circumstances the associated metadata may be preserved. This may -** be used, for example, to add a regular-expression matching scalar -** function. The compiled version of the regular expression is stored as -** metadata associated with the SQL value passed as the regular expression -** pattern. The compiled regular expression can be reused on multiple -** invocations of the same function so that the original pattern string -** does not need to be recompiled on each invocation. -** -** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata -** associated by the sqlite3_set_auxdata() function with the Nth argument -** value to the application-defined function. ^If no metadata has been ever -** been set for the Nth argument of the function, or if the corresponding -** function parameter has changed since the meta-data was set, -** then sqlite3_get_auxdata() returns a NULL pointer. -** -** ^The sqlite3_set_auxdata() interface saves the metadata -** pointed to by its 3rd parameter as the metadata for the N-th -** argument of the application-defined function. Subsequent -** calls to sqlite3_get_auxdata() might return this data, if it has -** not been destroyed. -** ^If it is not NULL, SQLite will invoke the destructor -** function given by the 4th parameter to sqlite3_set_auxdata() on -** the metadata when the corresponding function parameter changes -** or when the SQL statement completes, whichever comes first. -** -** SQLite is free to call the destructor and drop metadata on any -** parameter of any function at any time. ^The only guarantee is that -** the destructor will be called before the metadata is dropped. -** -** ^(In practice, metadata is preserved between function calls for -** expressions that are constant at compile time. This includes literal -** values and [parameters].)^ -** -** These routines must be called from the same thread in which -** the SQL function is running. -*/ -SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N); -SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*)); - - -/* -** CAPI3REF: Constants Defining Special Destructor Behavior -** -** These are special values for the destructor that is passed in as the -** final argument to routines like [sqlite3_result_blob()]. ^If the destructor -** argument is SQLITE_STATIC, it means that the content pointer is constant -** and will never change. It does not need to be destroyed. ^The -** SQLITE_TRANSIENT value means that the content will likely change in -** the near future and that SQLite should make its own private copy of -** the content before returning. -** -** The typedef is necessary to work around problems in certain -** C++ compilers. See ticket #2191. -*/ -typedef void (*sqlite3_destructor_type)(void*); -#define SQLITE_STATIC ((sqlite3_destructor_type)0) -#define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1) - -/* -** CAPI3REF: Setting The Result Of An SQL Function -** -** These routines are used by the xFunc or xFinal callbacks that -** implement SQL functions and aggregates. See -** [sqlite3_create_function()] and [sqlite3_create_function16()] -** for additional information. -** -** These functions work very much like the [parameter binding] family of -** functions used to bind values to host parameters in prepared statements. -** Refer to the [SQL parameter] documentation for additional information. -** -** ^The sqlite3_result_blob() interface sets the result from -** an application-defined function to be the BLOB whose content is pointed -** to by the second parameter and which is N bytes long where N is the -** third parameter. -** -** ^The sqlite3_result_zeroblob() interfaces set the result of -** the application-defined function to be a BLOB containing all zero -** bytes and N bytes in size, where N is the value of the 2nd parameter. -** -** ^The sqlite3_result_double() interface sets the result from -** an application-defined function to be a floating point value specified -** by its 2nd argument. -** -** ^The sqlite3_result_error() and sqlite3_result_error16() functions -** cause the implemented SQL function to throw an exception. -** ^SQLite uses the string pointed to by the -** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16() -** as the text of an error message. ^SQLite interprets the error -** message string from sqlite3_result_error() as UTF-8. ^SQLite -** interprets the string from sqlite3_result_error16() as UTF-16 in native -** byte order. ^If the third parameter to sqlite3_result_error() -** or sqlite3_result_error16() is negative then SQLite takes as the error -** message all text up through the first zero character. -** ^If the third parameter to sqlite3_result_error() or -** sqlite3_result_error16() is non-negative then SQLite takes that many -** bytes (not characters) from the 2nd parameter as the error message. -** ^The sqlite3_result_error() and sqlite3_result_error16() -** routines make a private copy of the error message text before -** they return. Hence, the calling function can deallocate or -** modify the text after they return without harm. -** ^The sqlite3_result_error_code() function changes the error code -** returned by SQLite as a result of an error in a function. ^By default, -** the error code is SQLITE_ERROR. ^A subsequent call to sqlite3_result_error() -** or sqlite3_result_error16() resets the error code to SQLITE_ERROR. -** -** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an -** error indicating that a string or BLOB is too long to represent. -** -** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an -** error indicating that a memory allocation failed. -** -** ^The sqlite3_result_int() interface sets the return value -** of the application-defined function to be the 32-bit signed integer -** value given in the 2nd argument. -** ^The sqlite3_result_int64() interface sets the return value -** of the application-defined function to be the 64-bit signed integer -** value given in the 2nd argument. -** -** ^The sqlite3_result_null() interface sets the return value -** of the application-defined function to be NULL. -** -** ^The sqlite3_result_text(), sqlite3_result_text16(), -** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces -** set the return value of the application-defined function to be -** a text string which is represented as UTF-8, UTF-16 native byte order, -** UTF-16 little endian, or UTF-16 big endian, respectively. -** ^SQLite takes the text result from the application from -** the 2nd parameter of the sqlite3_result_text* interfaces. -** ^If the 3rd parameter to the sqlite3_result_text* interfaces -** is negative, then SQLite takes result text from the 2nd parameter -** through the first zero character. -** ^If the 3rd parameter to the sqlite3_result_text* interfaces -** is non-negative, then as many bytes (not characters) of the text -** pointed to by the 2nd parameter are taken as the application-defined -** function result. If the 3rd parameter is non-negative, then it -** must be the byte offset into the string where the NUL terminator would -** appear if the string where NUL terminated. If any NUL characters occur -** in the string at a byte offset that is less than the value of the 3rd -** parameter, then the resulting string will contain embedded NULs and the -** result of expressions operating on strings with embedded NULs is undefined. -** ^If the 4th parameter to the sqlite3_result_text* interfaces -** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that -** function as the destructor on the text or BLOB result when it has -** finished using that result. -** ^If the 4th parameter to the sqlite3_result_text* interfaces or to -** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite -** assumes that the text or BLOB result is in constant space and does not -** copy the content of the parameter nor call a destructor on the content -** when it has finished using that result. -** ^If the 4th parameter to the sqlite3_result_text* interfaces -** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT -** then SQLite makes a copy of the result into space obtained from -** from [sqlite3_malloc()] before it returns. -** -** ^The sqlite3_result_value() interface sets the result of -** the application-defined function to be a copy the -** [unprotected sqlite3_value] object specified by the 2nd parameter. ^The -** sqlite3_result_value() interface makes a copy of the [sqlite3_value] -** so that the [sqlite3_value] specified in the parameter may change or -** be deallocated after sqlite3_result_value() returns without harm. -** ^A [protected sqlite3_value] object may always be used where an -** [unprotected sqlite3_value] object is required, so either -** kind of [sqlite3_value] object can be used with this interface. -** -** If these routines are called from within the different thread -** than the one containing the application-defined function that received -** the [sqlite3_context] pointer, the results are undefined. -*/ -SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*)); -SQLITE_API void sqlite3_result_double(sqlite3_context*, double); -SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int); -SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int); -SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*); -SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*); -SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int); -SQLITE_API void sqlite3_result_int(sqlite3_context*, int); -SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64); -SQLITE_API void sqlite3_result_null(sqlite3_context*); -SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*)); -SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*)); -SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*)); -SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*)); -SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*); -SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n); - -/* -** CAPI3REF: Define New Collating Sequences -** -** ^These functions add, remove, or modify a [collation] associated -** with the [database connection] specified as the first argument. -** -** ^The name of the collation is a UTF-8 string -** for sqlite3_create_collation() and sqlite3_create_collation_v2() -** and a UTF-16 string in native byte order for sqlite3_create_collation16(). -** ^Collation names that compare equal according to [sqlite3_strnicmp()] are -** considered to be the same name. -** -** ^(The third argument (eTextRep) must be one of the constants: -**
      -**
    • [SQLITE_UTF8], -**
    • [SQLITE_UTF16LE], -**
    • [SQLITE_UTF16BE], -**
    • [SQLITE_UTF16], or -**
    • [SQLITE_UTF16_ALIGNED]. -**
    )^ -** ^The eTextRep argument determines the encoding of strings passed -** to the collating function callback, xCallback. -** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep -** force strings to be UTF16 with native byte order. -** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin -** on an even byte address. -** -** ^The fourth argument, pArg, is an application data pointer that is passed -** through as the first argument to the collating function callback. -** -** ^The fifth argument, xCallback, is a pointer to the collating function. -** ^Multiple collating functions can be registered using the same name but -** with different eTextRep parameters and SQLite will use whichever -** function requires the least amount of data transformation. -** ^If the xCallback argument is NULL then the collating function is -** deleted. ^When all collating functions having the same name are deleted, -** that collation is no longer usable. -** -** ^The collating function callback is invoked with a copy of the pArg -** application data pointer and with two strings in the encoding specified -** by the eTextRep argument. The collating function must return an -** integer that is negative, zero, or positive -** if the first string is less than, equal to, or greater than the second, -** respectively. A collating function must always return the same answer -** given the same inputs. If two or more collating functions are registered -** to the same collation name (using different eTextRep values) then all -** must give an equivalent answer when invoked with equivalent strings. -** The collating function must obey the following properties for all -** strings A, B, and C: -** -**
      -**
    1. If A==B then B==A. -**
    2. If A==B and B==C then A==C. -**
    3. If A<B THEN B>A. -**
    4. If A<B and B<C then A<C. -**
    -** -** If a collating function fails any of the above constraints and that -** collating function is registered and used, then the behavior of SQLite -** is undefined. -** -** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation() -** with the addition that the xDestroy callback is invoked on pArg when -** the collating function is deleted. -** ^Collating functions are deleted when they are overridden by later -** calls to the collation creation functions or when the -** [database connection] is closed using [sqlite3_close()]. -** -** ^The xDestroy callback is not called if the -** sqlite3_create_collation_v2() function fails. Applications that invoke -** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should -** check the return code and dispose of the application data pointer -** themselves rather than expecting SQLite to deal with it for them. -** This is different from every other SQLite interface. The inconsistency -** is unfortunate but cannot be changed without breaking backwards -** compatibility. -** -** See also: [sqlite3_collation_needed()] and [sqlite3_collation_needed16()]. -*/ -SQLITE_API int sqlite3_create_collation( - sqlite3*, - const char *zName, - int eTextRep, - void *pArg, - int(*xCompare)(void*,int,const void*,int,const void*) -); -SQLITE_API int sqlite3_create_collation_v2( - sqlite3*, - const char *zName, - int eTextRep, - void *pArg, - int(*xCompare)(void*,int,const void*,int,const void*), - void(*xDestroy)(void*) -); -SQLITE_API int sqlite3_create_collation16( - sqlite3*, - const void *zName, - int eTextRep, - void *pArg, - int(*xCompare)(void*,int,const void*,int,const void*) -); - -/* -** CAPI3REF: Collation Needed Callbacks -** -** ^To avoid having to register all collation sequences before a database -** can be used, a single callback function may be registered with the -** [database connection] to be invoked whenever an undefined collation -** sequence is required. -** -** ^If the function is registered using the sqlite3_collation_needed() API, -** then it is passed the names of undefined collation sequences as strings -** encoded in UTF-8. ^If sqlite3_collation_needed16() is used, -** the names are passed as UTF-16 in machine native byte order. -** ^A call to either function replaces the existing collation-needed callback. -** -** ^(When the callback is invoked, the first argument passed is a copy -** of the second argument to sqlite3_collation_needed() or -** sqlite3_collation_needed16(). The second argument is the database -** connection. The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE], -** or [SQLITE_UTF16LE], indicating the most desirable form of the collation -** sequence function required. The fourth parameter is the name of the -** required collation sequence.)^ -** -** The callback function should register the desired collation using -** [sqlite3_create_collation()], [sqlite3_create_collation16()], or -** [sqlite3_create_collation_v2()]. -*/ -SQLITE_API int sqlite3_collation_needed( - sqlite3*, - void*, - void(*)(void*,sqlite3*,int eTextRep,const char*) -); -SQLITE_API int sqlite3_collation_needed16( - sqlite3*, - void*, - void(*)(void*,sqlite3*,int eTextRep,const void*) -); - -#ifdef SQLITE_HAS_CODEC -/* -** Specify the key for an encrypted database. This routine should be -** called right after sqlite3_open(). -** -** The code to implement this API is not available in the public release -** of SQLite. -*/ -SQLITE_API int sqlite3_key( - sqlite3 *db, /* Database to be rekeyed */ - const void *pKey, int nKey /* The key */ -); - -/* -** Change the key on an open database. If the current database is not -** encrypted, this routine will encrypt it. If pNew==0 or nNew==0, the -** database is decrypted. -** -** The code to implement this API is not available in the public release -** of SQLite. -*/ -SQLITE_API int sqlite3_rekey( - sqlite3 *db, /* Database to be rekeyed */ - const void *pKey, int nKey /* The new key */ -); - -/* -** Specify the activation key for a SEE database. Unless -** activated, none of the SEE routines will work. -*/ -SQLITE_API void sqlite3_activate_see( - const char *zPassPhrase /* Activation phrase */ -); -#endif - -#ifdef SQLITE_ENABLE_CEROD -/* -** Specify the activation key for a CEROD database. Unless -** activated, none of the CEROD routines will work. -*/ -SQLITE_API void sqlite3_activate_cerod( - const char *zPassPhrase /* Activation phrase */ -); -#endif - -/* -** CAPI3REF: Suspend Execution For A Short Time -** -** The sqlite3_sleep() function causes the current thread to suspend execution -** for at least a number of milliseconds specified in its parameter. -** -** If the operating system does not support sleep requests with -** millisecond time resolution, then the time will be rounded up to -** the nearest second. The number of milliseconds of sleep actually -** requested from the operating system is returned. -** -** ^SQLite implements this interface by calling the xSleep() -** method of the default [sqlite3_vfs] object. If the xSleep() method -** of the default VFS is not implemented correctly, or not implemented at -** all, then the behavior of sqlite3_sleep() may deviate from the description -** in the previous paragraphs. -*/ -SQLITE_API int sqlite3_sleep(int); - -/* -** CAPI3REF: Name Of The Folder Holding Temporary Files -** -** ^(If this global variable is made to point to a string which is -** the name of a folder (a.k.a. directory), then all temporary files -** created by SQLite when using a built-in [sqlite3_vfs | VFS] -** will be placed in that directory.)^ ^If this variable -** is a NULL pointer, then SQLite performs a search for an appropriate -** temporary file directory. -** -** It is not safe to read or modify this variable in more than one -** thread at a time. It is not safe to read or modify this variable -** if a [database connection] is being used at the same time in a separate -** thread. -** It is intended that this variable be set once -** as part of process initialization and before any SQLite interface -** routines have been called and that this variable remain unchanged -** thereafter. -** -** ^The [temp_store_directory pragma] may modify this variable and cause -** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore, -** the [temp_store_directory pragma] always assumes that any string -** that this variable points to is held in memory obtained from -** [sqlite3_malloc] and the pragma may attempt to free that memory -** using [sqlite3_free]. -** Hence, if this variable is modified directly, either it should be -** made NULL or made to point to memory obtained from [sqlite3_malloc] -** or else the use of the [temp_store_directory pragma] should be avoided. -** -** Note to Windows Runtime users: The temporary directory must be set -** prior to calling [sqlite3_open] or [sqlite3_open_v2]. Otherwise, various -** features that require the use of temporary files may fail. Here is an -** example of how to do this using C++ with the Windows Runtime: -** -**
    -** LPCWSTR zPath = Windows::Storage::ApplicationData::Current->
    -**       TemporaryFolder->Path->Data();
    -** char zPathBuf[MAX_PATH + 1];
    -** memset(zPathBuf, 0, sizeof(zPathBuf));
    -** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf),
    -**       NULL, NULL);
    -** sqlite3_temp_directory = sqlite3_mprintf("%s", zPathBuf);
    -** 
    -*/ -SQLITE_API char *sqlite3_temp_directory; - -/* -** CAPI3REF: Name Of The Folder Holding Database Files -** -** ^(If this global variable is made to point to a string which is -** the name of a folder (a.k.a. directory), then all database files -** specified with a relative pathname and created or accessed by -** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed -** to be relative to that directory.)^ ^If this variable is a NULL -** pointer, then SQLite assumes that all database files specified -** with a relative pathname are relative to the current directory -** for the process. Only the windows VFS makes use of this global -** variable; it is ignored by the unix VFS. -** -** Changing the value of this variable while a database connection is -** open can result in a corrupt database. -** -** It is not safe to read or modify this variable in more than one -** thread at a time. It is not safe to read or modify this variable -** if a [database connection] is being used at the same time in a separate -** thread. -** It is intended that this variable be set once -** as part of process initialization and before any SQLite interface -** routines have been called and that this variable remain unchanged -** thereafter. -** -** ^The [data_store_directory pragma] may modify this variable and cause -** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore, -** the [data_store_directory pragma] always assumes that any string -** that this variable points to is held in memory obtained from -** [sqlite3_malloc] and the pragma may attempt to free that memory -** using [sqlite3_free]. -** Hence, if this variable is modified directly, either it should be -** made NULL or made to point to memory obtained from [sqlite3_malloc] -** or else the use of the [data_store_directory pragma] should be avoided. -*/ -SQLITE_API char *sqlite3_data_directory; - -/* -** CAPI3REF: Test For Auto-Commit Mode -** KEYWORDS: {autocommit mode} -** -** ^The sqlite3_get_autocommit() interface returns non-zero or -** zero if the given database connection is or is not in autocommit mode, -** respectively. ^Autocommit mode is on by default. -** ^Autocommit mode is disabled by a [BEGIN] statement. -** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK]. -** -** If certain kinds of errors occur on a statement within a multi-statement -** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR], -** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the -** transaction might be rolled back automatically. The only way to -** find out whether SQLite automatically rolled back the transaction after -** an error is to use this function. -** -** If another thread changes the autocommit status of the database -** connection while this routine is running, then the return value -** is undefined. -*/ -SQLITE_API int sqlite3_get_autocommit(sqlite3*); - -/* -** CAPI3REF: Find The Database Handle Of A Prepared Statement -** -** ^The sqlite3_db_handle interface returns the [database connection] handle -** to which a [prepared statement] belongs. ^The [database connection] -** returned by sqlite3_db_handle is the same [database connection] -** that was the first argument -** to the [sqlite3_prepare_v2()] call (or its variants) that was used to -** create the statement in the first place. -*/ -SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*); - -/* -** CAPI3REF: Return The Filename For A Database Connection -** -** ^The sqlite3_db_filename(D,N) interface returns a pointer to a filename -** associated with database N of connection D. ^The main database file -** has the name "main". If there is no attached database N on the database -** connection D, or if database N is a temporary or in-memory database, then -** a NULL pointer is returned. -** -** ^The filename returned by this function is the output of the -** xFullPathname method of the [VFS]. ^In other words, the filename -** will be an absolute pathname, even if the filename used -** to open the database originally was a URI or relative pathname. -*/ -SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName); - -/* -** CAPI3REF: Determine if a database is read-only -** -** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N -** of connection D is read-only, 0 if it is read/write, or -1 if N is not -** the name of a database on connection D. -*/ -SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName); - -/* -** CAPI3REF: Find the next prepared statement -** -** ^This interface returns a pointer to the next [prepared statement] after -** pStmt associated with the [database connection] pDb. ^If pStmt is NULL -** then this interface returns a pointer to the first prepared statement -** associated with the database connection pDb. ^If no prepared statement -** satisfies the conditions of this routine, it returns NULL. -** -** The [database connection] pointer D in a call to -** [sqlite3_next_stmt(D,S)] must refer to an open database -** connection and in particular must not be a NULL pointer. -*/ -SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt); - -/* -** CAPI3REF: Commit And Rollback Notification Callbacks -** -** ^The sqlite3_commit_hook() interface registers a callback -** function to be invoked whenever a transaction is [COMMIT | committed]. -** ^Any callback set by a previous call to sqlite3_commit_hook() -** for the same database connection is overridden. -** ^The sqlite3_rollback_hook() interface registers a callback -** function to be invoked whenever a transaction is [ROLLBACK | rolled back]. -** ^Any callback set by a previous call to sqlite3_rollback_hook() -** for the same database connection is overridden. -** ^The pArg argument is passed through to the callback. -** ^If the callback on a commit hook function returns non-zero, -** then the commit is converted into a rollback. -** -** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions -** return the P argument from the previous call of the same function -** on the same [database connection] D, or NULL for -** the first call for each function on D. -** -** The commit and rollback hook callbacks are not reentrant. -** The callback implementation must not do anything that will modify -** the database connection that invoked the callback. Any actions -** to modify the database connection must be deferred until after the -** completion of the [sqlite3_step()] call that triggered the commit -** or rollback hook in the first place. -** Note that running any other SQL statements, including SELECT statements, -** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify -** the database connections for the meaning of "modify" in this paragraph. -** -** ^Registering a NULL function disables the callback. -** -** ^When the commit hook callback routine returns zero, the [COMMIT] -** operation is allowed to continue normally. ^If the commit hook -** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK]. -** ^The rollback hook is invoked on a rollback that results from a commit -** hook returning non-zero, just as it would be with any other rollback. -** -** ^For the purposes of this API, a transaction is said to have been -** rolled back if an explicit "ROLLBACK" statement is executed, or -** an error or constraint causes an implicit rollback to occur. -** ^The rollback callback is not invoked if a transaction is -** automatically rolled back because the database connection is closed. -** -** See also the [sqlite3_update_hook()] interface. -*/ -SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*); -SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*); - -/* -** CAPI3REF: Data Change Notification Callbacks -** -** ^The sqlite3_update_hook() interface registers a callback function -** with the [database connection] identified by the first argument -** to be invoked whenever a row is updated, inserted or deleted. -** ^Any callback set by a previous call to this function -** for the same database connection is overridden. -** -** ^The second argument is a pointer to the function to invoke when a -** row is updated, inserted or deleted. -** ^The first argument to the callback is a copy of the third argument -** to sqlite3_update_hook(). -** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE], -** or [SQLITE_UPDATE], depending on the operation that caused the callback -** to be invoked. -** ^The third and fourth arguments to the callback contain pointers to the -** database and table name containing the affected row. -** ^The final callback parameter is the [rowid] of the row. -** ^In the case of an update, this is the [rowid] after the update takes place. -** -** ^(The update hook is not invoked when internal system tables are -** modified (i.e. sqlite_master and sqlite_sequence).)^ -** -** ^In the current implementation, the update hook -** is not invoked when duplication rows are deleted because of an -** [ON CONFLICT | ON CONFLICT REPLACE] clause. ^Nor is the update hook -** invoked when rows are deleted using the [truncate optimization]. -** The exceptions defined in this paragraph might change in a future -** release of SQLite. -** -** The update hook implementation must not do anything that will modify -** the database connection that invoked the update hook. Any actions -** to modify the database connection must be deferred until after the -** completion of the [sqlite3_step()] call that triggered the update hook. -** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their -** database connections for the meaning of "modify" in this paragraph. -** -** ^The sqlite3_update_hook(D,C,P) function -** returns the P argument from the previous call -** on the same [database connection] D, or NULL for -** the first call on D. -** -** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()] -** interfaces. -*/ -SQLITE_API void *sqlite3_update_hook( - sqlite3*, - void(*)(void *,int ,char const *,char const *,sqlite3_int64), - void* -); - -/* -** CAPI3REF: Enable Or Disable Shared Pager Cache -** -** ^(This routine enables or disables the sharing of the database cache -** and schema data structures between [database connection | connections] -** to the same database. Sharing is enabled if the argument is true -** and disabled if the argument is false.)^ -** -** ^Cache sharing is enabled and disabled for an entire process. -** This is a change as of SQLite version 3.5.0. In prior versions of SQLite, -** sharing was enabled or disabled for each thread separately. -** -** ^(The cache sharing mode set by this interface effects all subsequent -** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()]. -** Existing database connections continue use the sharing mode -** that was in effect at the time they were opened.)^ -** -** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled -** successfully. An [error code] is returned otherwise.)^ -** -** ^Shared cache is disabled by default. But this might change in -** future releases of SQLite. Applications that care about shared -** cache setting should set it explicitly. -** -** This interface is threadsafe on processors where writing a -** 32-bit integer is atomic. -** -** See Also: [SQLite Shared-Cache Mode] -*/ -SQLITE_API int sqlite3_enable_shared_cache(int); - -/* -** CAPI3REF: Attempt To Free Heap Memory -** -** ^The sqlite3_release_memory() interface attempts to free N bytes -** of heap memory by deallocating non-essential memory allocations -** held by the database library. Memory used to cache database -** pages to improve performance is an example of non-essential memory. -** ^sqlite3_release_memory() returns the number of bytes actually freed, -** which might be more or less than the amount requested. -** ^The sqlite3_release_memory() routine is a no-op returning zero -** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT]. -** -** See also: [sqlite3_db_release_memory()] -*/ -SQLITE_API int sqlite3_release_memory(int); - -/* -** CAPI3REF: Free Memory Used By A Database Connection -** -** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap -** memory as possible from database connection D. Unlike the -** [sqlite3_release_memory()] interface, this interface is effect even -** when then [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is -** omitted. -** -** See also: [sqlite3_release_memory()] -*/ -SQLITE_API int sqlite3_db_release_memory(sqlite3*); - -/* -** CAPI3REF: Impose A Limit On Heap Size -** -** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the -** soft limit on the amount of heap memory that may be allocated by SQLite. -** ^SQLite strives to keep heap memory utilization below the soft heap -** limit by reducing the number of pages held in the page cache -** as heap memory usages approaches the limit. -** ^The soft heap limit is "soft" because even though SQLite strives to stay -** below the limit, it will exceed the limit rather than generate -** an [SQLITE_NOMEM] error. In other words, the soft heap limit -** is advisory only. -** -** ^The return value from sqlite3_soft_heap_limit64() is the size of -** the soft heap limit prior to the call, or negative in the case of an -** error. ^If the argument N is negative -** then no change is made to the soft heap limit. Hence, the current -** size of the soft heap limit can be determined by invoking -** sqlite3_soft_heap_limit64() with a negative argument. -** -** ^If the argument N is zero then the soft heap limit is disabled. -** -** ^(The soft heap limit is not enforced in the current implementation -** if one or more of following conditions are true: -** -**
      -**
    • The soft heap limit is set to zero. -**
    • Memory accounting is disabled using a combination of the -** [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and -** the [SQLITE_DEFAULT_MEMSTATUS] compile-time option. -**
    • An alternative page cache implementation is specified using -** [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...). -**
    • The page cache allocates from its own memory pool supplied -** by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than -** from the heap. -**
    )^ -** -** Beginning with SQLite version 3.7.3, the soft heap limit is enforced -** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT] -** compile-time option is invoked. With [SQLITE_ENABLE_MEMORY_MANAGEMENT], -** the soft heap limit is enforced on every memory allocation. Without -** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced -** when memory is allocated by the page cache. Testing suggests that because -** the page cache is the predominate memory user in SQLite, most -** applications will achieve adequate soft heap limit enforcement without -** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT]. -** -** The circumstances under which SQLite will enforce the soft heap limit may -** changes in future releases of SQLite. -*/ -SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N); - -/* -** CAPI3REF: Deprecated Soft Heap Limit Interface -** DEPRECATED -** -** This is a deprecated version of the [sqlite3_soft_heap_limit64()] -** interface. This routine is provided for historical compatibility -** only. All new applications should use the -** [sqlite3_soft_heap_limit64()] interface rather than this one. -*/ -SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N); - - -/* -** CAPI3REF: Extract Metadata About A Column Of A Table -** -** ^This routine returns metadata about a specific column of a specific -** database table accessible using the [database connection] handle -** passed as the first function argument. -** -** ^The column is identified by the second, third and fourth parameters to -** this function. ^The second parameter is either the name of the database -** (i.e. "main", "temp", or an attached database) containing the specified -** table or NULL. ^If it is NULL, then all attached databases are searched -** for the table using the same algorithm used by the database engine to -** resolve unqualified table references. -** -** ^The third and fourth parameters to this function are the table and column -** name of the desired column, respectively. Neither of these parameters -** may be NULL. -** -** ^Metadata is returned by writing to the memory locations passed as the 5th -** and subsequent parameters to this function. ^Any of these arguments may be -** NULL, in which case the corresponding element of metadata is omitted. -** -** ^(
    -** -**
    Parameter Output
    Type
    Description -** -**
    5th const char* Data type -**
    6th const char* Name of default collation sequence -**
    7th int True if column has a NOT NULL constraint -**
    8th int True if column is part of the PRIMARY KEY -**
    9th int True if column is [AUTOINCREMENT] -**
    -**
    )^ -** -** ^The memory pointed to by the character pointers returned for the -** declaration type and collation sequence is valid only until the next -** call to any SQLite API function. -** -** ^If the specified table is actually a view, an [error code] is returned. -** -** ^If the specified column is "rowid", "oid" or "_rowid_" and an -** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output -** parameters are set for the explicitly declared column. ^(If there is no -** explicitly declared [INTEGER PRIMARY KEY] column, then the output -** parameters are set as follows: -** -**
    -**     data type: "INTEGER"
    -**     collation sequence: "BINARY"
    -**     not null: 0
    -**     primary key: 1
    -**     auto increment: 0
    -** 
    )^ -** -** ^(This function may load one or more schemas from database files. If an -** error occurs during this process, or if the requested table or column -** cannot be found, an [error code] is returned and an error message left -** in the [database connection] (to be retrieved using sqlite3_errmsg()).)^ -** -** ^This API is only available if the library was compiled with the -** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined. -*/ -SQLITE_API int sqlite3_table_column_metadata( - sqlite3 *db, /* Connection handle */ - const char *zDbName, /* Database name or NULL */ - const char *zTableName, /* Table name */ - const char *zColumnName, /* Column name */ - char const **pzDataType, /* OUTPUT: Declared data type */ - char const **pzCollSeq, /* OUTPUT: Collation sequence name */ - int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */ - int *pPrimaryKey, /* OUTPUT: True if column part of PK */ - int *pAutoinc /* OUTPUT: True if column is auto-increment */ -); - -/* -** CAPI3REF: Load An Extension -** -** ^This interface loads an SQLite extension library from the named file. -** -** ^The sqlite3_load_extension() interface attempts to load an -** SQLite extension library contained in the file zFile. -** -** ^The entry point is zProc. -** ^zProc may be 0, in which case the name of the entry point -** defaults to "sqlite3_extension_init". -** ^The sqlite3_load_extension() interface returns -** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong. -** ^If an error occurs and pzErrMsg is not 0, then the -** [sqlite3_load_extension()] interface shall attempt to -** fill *pzErrMsg with error message text stored in memory -** obtained from [sqlite3_malloc()]. The calling function -** should free this memory by calling [sqlite3_free()]. -** -** ^Extension loading must be enabled using -** [sqlite3_enable_load_extension()] prior to calling this API, -** otherwise an error will be returned. -** -** See also the [load_extension() SQL function]. -*/ -SQLITE_API int sqlite3_load_extension( - sqlite3 *db, /* Load the extension into this database connection */ - const char *zFile, /* Name of the shared library containing extension */ - const char *zProc, /* Entry point. Derived from zFile if 0 */ - char **pzErrMsg /* Put error message here if not 0 */ -); - -/* -** CAPI3REF: Enable Or Disable Extension Loading -** -** ^So as not to open security holes in older applications that are -** unprepared to deal with extension loading, and as a means of disabling -** extension loading while evaluating user-entered SQL, the following API -** is provided to turn the [sqlite3_load_extension()] mechanism on and off. -** -** ^Extension loading is off by default. See ticket #1863. -** ^Call the sqlite3_enable_load_extension() routine with onoff==1 -** to turn extension loading on and call it with onoff==0 to turn -** it back off again. -*/ -SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff); - -/* -** CAPI3REF: Automatically Load Statically Linked Extensions -** -** ^This interface causes the xEntryPoint() function to be invoked for -** each new [database connection] that is created. The idea here is that -** xEntryPoint() is the entry point for a statically linked SQLite extension -** that is to be automatically loaded into all new database connections. -** -** ^(Even though the function prototype shows that xEntryPoint() takes -** no arguments and returns void, SQLite invokes xEntryPoint() with three -** arguments and expects and integer result as if the signature of the -** entry point where as follows: -** -**
    -**    int xEntryPoint(
    -**      sqlite3 *db,
    -**      const char **pzErrMsg,
    -**      const struct sqlite3_api_routines *pThunk
    -**    );
    -** 
    )^ -** -** If the xEntryPoint routine encounters an error, it should make *pzErrMsg -** point to an appropriate error message (obtained from [sqlite3_mprintf()]) -** and return an appropriate [error code]. ^SQLite ensures that *pzErrMsg -** is NULL before calling the xEntryPoint(). ^SQLite will invoke -** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns. ^If any -** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()], -** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail. -** -** ^Calling sqlite3_auto_extension(X) with an entry point X that is already -** on the list of automatic extensions is a harmless no-op. ^No entry point -** will be called more than once for each database connection that is opened. -** -** See also: [sqlite3_reset_auto_extension()]. -*/ -SQLITE_API int sqlite3_auto_extension(void (*xEntryPoint)(void)); - -/* -** CAPI3REF: Reset Automatic Extension Loading -** -** ^This interface disables all automatic extensions previously -** registered using [sqlite3_auto_extension()]. -*/ -SQLITE_API void sqlite3_reset_auto_extension(void); - -/* -** The interface to the virtual-table mechanism is currently considered -** to be experimental. The interface might change in incompatible ways. -** If this is a problem for you, do not use the interface at this time. -** -** When the virtual-table mechanism stabilizes, we will declare the -** interface fixed, support it indefinitely, and remove this comment. -*/ - -/* -** Structures used by the virtual table interface -*/ -typedef struct sqlite3_vtab sqlite3_vtab; -typedef struct sqlite3_index_info sqlite3_index_info; -typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor; -typedef struct sqlite3_module sqlite3_module; - -/* -** CAPI3REF: Virtual Table Object -** KEYWORDS: sqlite3_module {virtual table module} -** -** This structure, sometimes called a "virtual table module", -** defines the implementation of a [virtual tables]. -** This structure consists mostly of methods for the module. -** -** ^A virtual table module is created by filling in a persistent -** instance of this structure and passing a pointer to that instance -** to [sqlite3_create_module()] or [sqlite3_create_module_v2()]. -** ^The registration remains valid until it is replaced by a different -** module or until the [database connection] closes. The content -** of this structure must not change while it is registered with -** any database connection. -*/ -struct sqlite3_module { - int iVersion; - int (*xCreate)(sqlite3*, void *pAux, - int argc, const char *const*argv, - sqlite3_vtab **ppVTab, char**); - int (*xConnect)(sqlite3*, void *pAux, - int argc, const char *const*argv, - sqlite3_vtab **ppVTab, char**); - int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*); - int (*xDisconnect)(sqlite3_vtab *pVTab); - int (*xDestroy)(sqlite3_vtab *pVTab); - int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor); - int (*xClose)(sqlite3_vtab_cursor*); - int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr, - int argc, sqlite3_value **argv); - int (*xNext)(sqlite3_vtab_cursor*); - int (*xEof)(sqlite3_vtab_cursor*); - int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int); - int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid); - int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *); - int (*xBegin)(sqlite3_vtab *pVTab); - int (*xSync)(sqlite3_vtab *pVTab); - int (*xCommit)(sqlite3_vtab *pVTab); - int (*xRollback)(sqlite3_vtab *pVTab); - int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName, - void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), - void **ppArg); - int (*xRename)(sqlite3_vtab *pVtab, const char *zNew); - /* The methods above are in version 1 of the sqlite_module object. Those - ** below are for version 2 and greater. */ - int (*xSavepoint)(sqlite3_vtab *pVTab, int); - int (*xRelease)(sqlite3_vtab *pVTab, int); - int (*xRollbackTo)(sqlite3_vtab *pVTab, int); -}; - -/* -** CAPI3REF: Virtual Table Indexing Information -** KEYWORDS: sqlite3_index_info -** -** The sqlite3_index_info structure and its substructures is used as part -** of the [virtual table] interface to -** pass information into and receive the reply from the [xBestIndex] -** method of a [virtual table module]. The fields under **Inputs** are the -** inputs to xBestIndex and are read-only. xBestIndex inserts its -** results into the **Outputs** fields. -** -** ^(The aConstraint[] array records WHERE clause constraints of the form: -** -**
    column OP expr
    -** -** where OP is =, <, <=, >, or >=.)^ ^(The particular operator is -** stored in aConstraint[].op using one of the -** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^ -** ^(The index of the column is stored in -** aConstraint[].iColumn.)^ ^(aConstraint[].usable is TRUE if the -** expr on the right-hand side can be evaluated (and thus the constraint -** is usable) and false if it cannot.)^ -** -** ^The optimizer automatically inverts terms of the form "expr OP column" -** and makes other simplifications to the WHERE clause in an attempt to -** get as many WHERE clause terms into the form shown above as possible. -** ^The aConstraint[] array only reports WHERE clause terms that are -** relevant to the particular virtual table being queried. -** -** ^Information about the ORDER BY clause is stored in aOrderBy[]. -** ^Each term of aOrderBy records a column of the ORDER BY clause. -** -** The [xBestIndex] method must fill aConstraintUsage[] with information -** about what parameters to pass to xFilter. ^If argvIndex>0 then -** the right-hand side of the corresponding aConstraint[] is evaluated -** and becomes the argvIndex-th entry in argv. ^(If aConstraintUsage[].omit -** is true, then the constraint is assumed to be fully handled by the -** virtual table and is not checked again by SQLite.)^ -** -** ^The idxNum and idxPtr values are recorded and passed into the -** [xFilter] method. -** ^[sqlite3_free()] is used to free idxPtr if and only if -** needToFreeIdxPtr is true. -** -** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in -** the correct order to satisfy the ORDER BY clause so that no separate -** sorting step is required. -** -** ^The estimatedCost value is an estimate of the cost of doing the -** particular lookup. A full scan of a table with N entries should have -** a cost of N. A binary search of a table of N entries should have a -** cost of approximately log(N). -*/ -struct sqlite3_index_info { - /* Inputs */ - int nConstraint; /* Number of entries in aConstraint */ - struct sqlite3_index_constraint { - int iColumn; /* Column on left-hand side of constraint */ - unsigned char op; /* Constraint operator */ - unsigned char usable; /* True if this constraint is usable */ - int iTermOffset; /* Used internally - xBestIndex should ignore */ - } *aConstraint; /* Table of WHERE clause constraints */ - int nOrderBy; /* Number of terms in the ORDER BY clause */ - struct sqlite3_index_orderby { - int iColumn; /* Column number */ - unsigned char desc; /* True for DESC. False for ASC. */ - } *aOrderBy; /* The ORDER BY clause */ - /* Outputs */ - struct sqlite3_index_constraint_usage { - int argvIndex; /* if >0, constraint is part of argv to xFilter */ - unsigned char omit; /* Do not code a test for this constraint */ - } *aConstraintUsage; - int idxNum; /* Number used to identify the index */ - char *idxStr; /* String, possibly obtained from sqlite3_malloc */ - int needToFreeIdxStr; /* Free idxStr using sqlite3_free() if true */ - int orderByConsumed; /* True if output is already ordered */ - double estimatedCost; /* Estimated cost of using this index */ -}; - -/* -** CAPI3REF: Virtual Table Constraint Operator Codes -** -** These macros defined the allowed values for the -** [sqlite3_index_info].aConstraint[].op field. Each value represents -** an operator that is part of a constraint term in the wHERE clause of -** a query that uses a [virtual table]. -*/ -#define SQLITE_INDEX_CONSTRAINT_EQ 2 -#define SQLITE_INDEX_CONSTRAINT_GT 4 -#define SQLITE_INDEX_CONSTRAINT_LE 8 -#define SQLITE_INDEX_CONSTRAINT_LT 16 -#define SQLITE_INDEX_CONSTRAINT_GE 32 -#define SQLITE_INDEX_CONSTRAINT_MATCH 64 - -/* -** CAPI3REF: Register A Virtual Table Implementation -** -** ^These routines are used to register a new [virtual table module] name. -** ^Module names must be registered before -** creating a new [virtual table] using the module and before using a -** preexisting [virtual table] for the module. -** -** ^The module name is registered on the [database connection] specified -** by the first parameter. ^The name of the module is given by the -** second parameter. ^The third parameter is a pointer to -** the implementation of the [virtual table module]. ^The fourth -** parameter is an arbitrary client data pointer that is passed through -** into the [xCreate] and [xConnect] methods of the virtual table module -** when a new virtual table is be being created or reinitialized. -** -** ^The sqlite3_create_module_v2() interface has a fifth parameter which -** is a pointer to a destructor for the pClientData. ^SQLite will -** invoke the destructor function (if it is not NULL) when SQLite -** no longer needs the pClientData pointer. ^The destructor will also -** be invoked if the call to sqlite3_create_module_v2() fails. -** ^The sqlite3_create_module() -** interface is equivalent to sqlite3_create_module_v2() with a NULL -** destructor. -*/ -SQLITE_API int sqlite3_create_module( - sqlite3 *db, /* SQLite connection to register module with */ - const char *zName, /* Name of the module */ - const sqlite3_module *p, /* Methods for the module */ - void *pClientData /* Client data for xCreate/xConnect */ -); -SQLITE_API int sqlite3_create_module_v2( - sqlite3 *db, /* SQLite connection to register module with */ - const char *zName, /* Name of the module */ - const sqlite3_module *p, /* Methods for the module */ - void *pClientData, /* Client data for xCreate/xConnect */ - void(*xDestroy)(void*) /* Module destructor function */ -); - -/* -** CAPI3REF: Virtual Table Instance Object -** KEYWORDS: sqlite3_vtab -** -** Every [virtual table module] implementation uses a subclass -** of this object to describe a particular instance -** of the [virtual table]. Each subclass will -** be tailored to the specific needs of the module implementation. -** The purpose of this superclass is to define certain fields that are -** common to all module implementations. -** -** ^Virtual tables methods can set an error message by assigning a -** string obtained from [sqlite3_mprintf()] to zErrMsg. The method should -** take care that any prior string is freed by a call to [sqlite3_free()] -** prior to assigning a new string to zErrMsg. ^After the error message -** is delivered up to the client application, the string will be automatically -** freed by sqlite3_free() and the zErrMsg field will be zeroed. -*/ -struct sqlite3_vtab { - const sqlite3_module *pModule; /* The module for this virtual table */ - int nRef; /* NO LONGER USED */ - char *zErrMsg; /* Error message from sqlite3_mprintf() */ - /* Virtual table implementations will typically add additional fields */ -}; - -/* -** CAPI3REF: Virtual Table Cursor Object -** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor} -** -** Every [virtual table module] implementation uses a subclass of the -** following structure to describe cursors that point into the -** [virtual table] and are used -** to loop through the virtual table. Cursors are created using the -** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed -** by the [sqlite3_module.xClose | xClose] method. Cursors are used -** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods -** of the module. Each module implementation will define -** the content of a cursor structure to suit its own needs. -** -** This superclass exists in order to define fields of the cursor that -** are common to all implementations. -*/ -struct sqlite3_vtab_cursor { - sqlite3_vtab *pVtab; /* Virtual table of this cursor */ - /* Virtual table implementations will typically add additional fields */ -}; - -/* -** CAPI3REF: Declare The Schema Of A Virtual Table -** -** ^The [xCreate] and [xConnect] methods of a -** [virtual table module] call this interface -** to declare the format (the names and datatypes of the columns) of -** the virtual tables they implement. -*/ -SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL); - -/* -** CAPI3REF: Overload A Function For A Virtual Table -** -** ^(Virtual tables can provide alternative implementations of functions -** using the [xFindFunction] method of the [virtual table module]. -** But global versions of those functions -** must exist in order to be overloaded.)^ -** -** ^(This API makes sure a global version of a function with a particular -** name and number of parameters exists. If no such function exists -** before this API is called, a new function is created.)^ ^The implementation -** of the new function always causes an exception to be thrown. So -** the new function is not good for anything by itself. Its only -** purpose is to be a placeholder function that can be overloaded -** by a [virtual table]. -*/ -SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg); - -/* -** The interface to the virtual-table mechanism defined above (back up -** to a comment remarkably similar to this one) is currently considered -** to be experimental. The interface might change in incompatible ways. -** If this is a problem for you, do not use the interface at this time. -** -** When the virtual-table mechanism stabilizes, we will declare the -** interface fixed, support it indefinitely, and remove this comment. -*/ - -/* -** CAPI3REF: A Handle To An Open BLOB -** KEYWORDS: {BLOB handle} {BLOB handles} -** -** An instance of this object represents an open BLOB on which -** [sqlite3_blob_open | incremental BLOB I/O] can be performed. -** ^Objects of this type are created by [sqlite3_blob_open()] -** and destroyed by [sqlite3_blob_close()]. -** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces -** can be used to read or write small subsections of the BLOB. -** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes. -*/ -typedef struct sqlite3_blob sqlite3_blob; - -/* -** CAPI3REF: Open A BLOB For Incremental I/O -** -** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located -** in row iRow, column zColumn, table zTable in database zDb; -** in other words, the same BLOB that would be selected by: -** -**
    -**     SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
    -** 
    )^ -** -** ^If the flags parameter is non-zero, then the BLOB is opened for read -** and write access. ^If it is zero, the BLOB is opened for read access. -** ^It is not possible to open a column that is part of an index or primary -** key for writing. ^If [foreign key constraints] are enabled, it is -** not possible to open a column that is part of a [child key] for writing. -** -** ^Note that the database name is not the filename that contains -** the database but rather the symbolic name of the database that -** appears after the AS keyword when the database is connected using [ATTACH]. -** ^For the main database file, the database name is "main". -** ^For TEMP tables, the database name is "temp". -** -** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is written -** to *ppBlob. Otherwise an [error code] is returned and *ppBlob is set -** to be a null pointer.)^ -** ^This function sets the [database connection] error code and message -** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()] and related -** functions. ^Note that the *ppBlob variable is always initialized in a -** way that makes it safe to invoke [sqlite3_blob_close()] on *ppBlob -** regardless of the success or failure of this routine. -** -** ^(If the row that a BLOB handle points to is modified by an -** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects -** then the BLOB handle is marked as "expired". -** This is true if any column of the row is changed, even a column -** other than the one the BLOB handle is open on.)^ -** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for -** an expired BLOB handle fail with a return code of [SQLITE_ABORT]. -** ^(Changes written into a BLOB prior to the BLOB expiring are not -** rolled back by the expiration of the BLOB. Such changes will eventually -** commit if the transaction continues to completion.)^ -** -** ^Use the [sqlite3_blob_bytes()] interface to determine the size of -** the opened blob. ^The size of a blob may not be changed by this -** interface. Use the [UPDATE] SQL command to change the size of a -** blob. -** -** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces -** and the built-in [zeroblob] SQL function can be used, if desired, -** to create an empty, zero-filled blob in which to read or write using -** this interface. -** -** To avoid a resource leak, every open [BLOB handle] should eventually -** be released by a call to [sqlite3_blob_close()]. -*/ -SQLITE_API int sqlite3_blob_open( - sqlite3*, - const char *zDb, - const char *zTable, - const char *zColumn, - sqlite3_int64 iRow, - int flags, - sqlite3_blob **ppBlob -); - -/* -** CAPI3REF: Move a BLOB Handle to a New Row -** -** ^This function is used to move an existing blob handle so that it points -** to a different row of the same database table. ^The new row is identified -** by the rowid value passed as the second argument. Only the row can be -** changed. ^The database, table and column on which the blob handle is open -** remain the same. Moving an existing blob handle to a new row can be -** faster than closing the existing handle and opening a new one. -** -** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] - -** it must exist and there must be either a blob or text value stored in -** the nominated column.)^ ^If the new row is not present in the table, or if -** it does not contain a blob or text value, or if another error occurs, an -** SQLite error code is returned and the blob handle is considered aborted. -** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or -** [sqlite3_blob_reopen()] on an aborted blob handle immediately return -** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle -** always returns zero. -** -** ^This function sets the database handle error code and message. -*/ -SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64); - -/* -** CAPI3REF: Close A BLOB Handle -** -** ^Closes an open [BLOB handle]. -** -** ^Closing a BLOB shall cause the current transaction to commit -** if there are no other BLOBs, no pending prepared statements, and the -** database connection is in [autocommit mode]. -** ^If any writes were made to the BLOB, they might be held in cache -** until the close operation if they will fit. -** -** ^(Closing the BLOB often forces the changes -** out to disk and so if any I/O errors occur, they will likely occur -** at the time when the BLOB is closed. Any errors that occur during -** closing are reported as a non-zero return value.)^ -** -** ^(The BLOB is closed unconditionally. Even if this routine returns -** an error code, the BLOB is still closed.)^ -** -** ^Calling this routine with a null pointer (such as would be returned -** by a failed call to [sqlite3_blob_open()]) is a harmless no-op. -*/ -SQLITE_API int sqlite3_blob_close(sqlite3_blob *); - -/* -** CAPI3REF: Return The Size Of An Open BLOB -** -** ^Returns the size in bytes of the BLOB accessible via the -** successfully opened [BLOB handle] in its only argument. ^The -** incremental blob I/O routines can only read or overwriting existing -** blob content; they cannot change the size of a blob. -** -** This routine only works on a [BLOB handle] which has been created -** by a prior successful call to [sqlite3_blob_open()] and which has not -** been closed by [sqlite3_blob_close()]. Passing any other pointer in -** to this routine results in undefined and probably undesirable behavior. -*/ -SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *); - -/* -** CAPI3REF: Read Data From A BLOB Incrementally -** -** ^(This function is used to read data from an open [BLOB handle] into a -** caller-supplied buffer. N bytes of data are copied into buffer Z -** from the open BLOB, starting at offset iOffset.)^ -** -** ^If offset iOffset is less than N bytes from the end of the BLOB, -** [SQLITE_ERROR] is returned and no data is read. ^If N or iOffset is -** less than zero, [SQLITE_ERROR] is returned and no data is read. -** ^The size of the blob (and hence the maximum value of N+iOffset) -** can be determined using the [sqlite3_blob_bytes()] interface. -** -** ^An attempt to read from an expired [BLOB handle] fails with an -** error code of [SQLITE_ABORT]. -** -** ^(On success, sqlite3_blob_read() returns SQLITE_OK. -** Otherwise, an [error code] or an [extended error code] is returned.)^ -** -** This routine only works on a [BLOB handle] which has been created -** by a prior successful call to [sqlite3_blob_open()] and which has not -** been closed by [sqlite3_blob_close()]. Passing any other pointer in -** to this routine results in undefined and probably undesirable behavior. -** -** See also: [sqlite3_blob_write()]. -*/ -SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset); - -/* -** CAPI3REF: Write Data Into A BLOB Incrementally -** -** ^This function is used to write data into an open [BLOB handle] from a -** caller-supplied buffer. ^N bytes of data are copied from the buffer Z -** into the open BLOB, starting at offset iOffset. -** -** ^If the [BLOB handle] passed as the first argument was not opened for -** writing (the flags parameter to [sqlite3_blob_open()] was zero), -** this function returns [SQLITE_READONLY]. -** -** ^This function may only modify the contents of the BLOB; it is -** not possible to increase the size of a BLOB using this API. -** ^If offset iOffset is less than N bytes from the end of the BLOB, -** [SQLITE_ERROR] is returned and no data is written. ^If N is -** less than zero [SQLITE_ERROR] is returned and no data is written. -** The size of the BLOB (and hence the maximum value of N+iOffset) -** can be determined using the [sqlite3_blob_bytes()] interface. -** -** ^An attempt to write to an expired [BLOB handle] fails with an -** error code of [SQLITE_ABORT]. ^Writes to the BLOB that occurred -** before the [BLOB handle] expired are not rolled back by the -** expiration of the handle, though of course those changes might -** have been overwritten by the statement that expired the BLOB handle -** or by other independent statements. -** -** ^(On success, sqlite3_blob_write() returns SQLITE_OK. -** Otherwise, an [error code] or an [extended error code] is returned.)^ -** -** This routine only works on a [BLOB handle] which has been created -** by a prior successful call to [sqlite3_blob_open()] and which has not -** been closed by [sqlite3_blob_close()]. Passing any other pointer in -** to this routine results in undefined and probably undesirable behavior. -** -** See also: [sqlite3_blob_read()]. -*/ -SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset); - -/* -** CAPI3REF: Virtual File System Objects -** -** A virtual filesystem (VFS) is an [sqlite3_vfs] object -** that SQLite uses to interact -** with the underlying operating system. Most SQLite builds come with a -** single default VFS that is appropriate for the host computer. -** New VFSes can be registered and existing VFSes can be unregistered. -** The following interfaces are provided. -** -** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name. -** ^Names are case sensitive. -** ^Names are zero-terminated UTF-8 strings. -** ^If there is no match, a NULL pointer is returned. -** ^If zVfsName is NULL then the default VFS is returned. -** -** ^New VFSes are registered with sqlite3_vfs_register(). -** ^Each new VFS becomes the default VFS if the makeDflt flag is set. -** ^The same VFS can be registered multiple times without injury. -** ^To make an existing VFS into the default VFS, register it again -** with the makeDflt flag set. If two different VFSes with the -** same name are registered, the behavior is undefined. If a -** VFS is registered with a name that is NULL or an empty string, -** then the behavior is undefined. -** -** ^Unregister a VFS with the sqlite3_vfs_unregister() interface. -** ^(If the default VFS is unregistered, another VFS is chosen as -** the default. The choice for the new VFS is arbitrary.)^ -*/ -SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName); -SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt); -SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*); - -/* -** CAPI3REF: Mutexes -** -** The SQLite core uses these routines for thread -** synchronization. Though they are intended for internal -** use by SQLite, code that links against SQLite is -** permitted to use any of these routines. -** -** The SQLite source code contains multiple implementations -** of these mutex routines. An appropriate implementation -** is selected automatically at compile-time. ^(The following -** implementations are available in the SQLite core: -** -**
      -**
    • SQLITE_MUTEX_PTHREADS -**
    • SQLITE_MUTEX_W32 -**
    • SQLITE_MUTEX_NOOP -**
    )^ -** -** ^The SQLITE_MUTEX_NOOP implementation is a set of routines -** that does no real locking and is appropriate for use in -** a single-threaded application. ^The SQLITE_MUTEX_PTHREADS and -** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix -** and Windows. -** -** ^(If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor -** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex -** implementation is included with the library. In this case the -** application must supply a custom mutex implementation using the -** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function -** before calling sqlite3_initialize() or any other public sqlite3_ -** function that calls sqlite3_initialize().)^ -** -** ^The sqlite3_mutex_alloc() routine allocates a new -** mutex and returns a pointer to it. ^If it returns NULL -** that means that a mutex could not be allocated. ^SQLite -** will unwind its stack and return an error. ^(The argument -** to sqlite3_mutex_alloc() is one of these integer constants: -** -**
      -**
    • SQLITE_MUTEX_FAST -**
    • SQLITE_MUTEX_RECURSIVE -**
    • SQLITE_MUTEX_STATIC_MASTER -**
    • SQLITE_MUTEX_STATIC_MEM -**
    • SQLITE_MUTEX_STATIC_MEM2 -**
    • SQLITE_MUTEX_STATIC_PRNG -**
    • SQLITE_MUTEX_STATIC_LRU -**
    • SQLITE_MUTEX_STATIC_LRU2 -**
    )^ -** -** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) -** cause sqlite3_mutex_alloc() to create -** a new mutex. ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE -** is used but not necessarily so when SQLITE_MUTEX_FAST is used. -** The mutex implementation does not need to make a distinction -** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does -** not want to. ^SQLite will only request a recursive mutex in -** cases where it really needs one. ^If a faster non-recursive mutex -** implementation is available on the host platform, the mutex subsystem -** might return such a mutex in response to SQLITE_MUTEX_FAST. -** -** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other -** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return -** a pointer to a static preexisting mutex. ^Six static mutexes are -** used by the current version of SQLite. Future versions of SQLite -** may add additional static mutexes. Static mutexes are for internal -** use by SQLite only. Applications that use SQLite mutexes should -** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or -** SQLITE_MUTEX_RECURSIVE. -** -** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST -** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc() -** returns a different mutex on every call. ^But for the static -** mutex types, the same mutex is returned on every call that has -** the same type number. -** -** ^The sqlite3_mutex_free() routine deallocates a previously -** allocated dynamic mutex. ^SQLite is careful to deallocate every -** dynamic mutex that it allocates. The dynamic mutexes must not be in -** use when they are deallocated. Attempting to deallocate a static -** mutex results in undefined behavior. ^SQLite never deallocates -** a static mutex. -** -** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt -** to enter a mutex. ^If another thread is already within the mutex, -** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return -** SQLITE_BUSY. ^The sqlite3_mutex_try() interface returns [SQLITE_OK] -** upon successful entry. ^(Mutexes created using -** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread. -** In such cases the, -** mutex must be exited an equal number of times before another thread -** can enter.)^ ^(If the same thread tries to enter any other -** kind of mutex more than once, the behavior is undefined. -** SQLite will never exhibit -** such behavior in its own use of mutexes.)^ -** -** ^(Some systems (for example, Windows 95) do not support the operation -** implemented by sqlite3_mutex_try(). On those systems, sqlite3_mutex_try() -** will always return SQLITE_BUSY. The SQLite core only ever uses -** sqlite3_mutex_try() as an optimization so this is acceptable behavior.)^ -** -** ^The sqlite3_mutex_leave() routine exits a mutex that was -** previously entered by the same thread. ^(The behavior -** is undefined if the mutex is not currently entered by the -** calling thread or is not currently allocated. SQLite will -** never do either.)^ -** -** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or -** sqlite3_mutex_leave() is a NULL pointer, then all three routines -** behave as no-ops. -** -** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()]. -*/ -SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int); -SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*); -SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*); -SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*); -SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*); - -/* -** CAPI3REF: Mutex Methods Object -** -** An instance of this structure defines the low-level routines -** used to allocate and use mutexes. -** -** Usually, the default mutex implementations provided by SQLite are -** sufficient, however the user has the option of substituting a custom -** implementation for specialized deployments or systems for which SQLite -** does not provide a suitable implementation. In this case, the user -** creates and populates an instance of this structure to pass -** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option. -** Additionally, an instance of this structure can be used as an -** output variable when querying the system for the current mutex -** implementation, using the [SQLITE_CONFIG_GETMUTEX] option. -** -** ^The xMutexInit method defined by this structure is invoked as -** part of system initialization by the sqlite3_initialize() function. -** ^The xMutexInit routine is called by SQLite exactly once for each -** effective call to [sqlite3_initialize()]. -** -** ^The xMutexEnd method defined by this structure is invoked as -** part of system shutdown by the sqlite3_shutdown() function. The -** implementation of this method is expected to release all outstanding -** resources obtained by the mutex methods implementation, especially -** those obtained by the xMutexInit method. ^The xMutexEnd() -** interface is invoked exactly once for each call to [sqlite3_shutdown()]. -** -** ^(The remaining seven methods defined by this structure (xMutexAlloc, -** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and -** xMutexNotheld) implement the following interfaces (respectively): -** -**
      -**
    • [sqlite3_mutex_alloc()]
    • -**
    • [sqlite3_mutex_free()]
    • -**
    • [sqlite3_mutex_enter()]
    • -**
    • [sqlite3_mutex_try()]
    • -**
    • [sqlite3_mutex_leave()]
    • -**
    • [sqlite3_mutex_held()]
    • -**
    • [sqlite3_mutex_notheld()]
    • -**
    )^ -** -** The only difference is that the public sqlite3_XXX functions enumerated -** above silently ignore any invocations that pass a NULL pointer instead -** of a valid mutex handle. The implementations of the methods defined -** by this structure are not required to handle this case, the results -** of passing a NULL pointer instead of a valid mutex handle are undefined -** (i.e. it is acceptable to provide an implementation that segfaults if -** it is passed a NULL pointer). -** -** The xMutexInit() method must be threadsafe. ^It must be harmless to -** invoke xMutexInit() multiple times within the same process and without -** intervening calls to xMutexEnd(). Second and subsequent calls to -** xMutexInit() must be no-ops. -** -** ^xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()] -** and its associates). ^Similarly, xMutexAlloc() must not use SQLite memory -** allocation for a static mutex. ^However xMutexAlloc() may use SQLite -** memory allocation for a fast or recursive mutex. -** -** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is -** called, but only if the prior call to xMutexInit returned SQLITE_OK. -** If xMutexInit fails in any way, it is expected to clean up after itself -** prior to returning. -*/ -typedef struct sqlite3_mutex_methods sqlite3_mutex_methods; -struct sqlite3_mutex_methods { - int (*xMutexInit)(void); - int (*xMutexEnd)(void); - sqlite3_mutex *(*xMutexAlloc)(int); - void (*xMutexFree)(sqlite3_mutex *); - void (*xMutexEnter)(sqlite3_mutex *); - int (*xMutexTry)(sqlite3_mutex *); - void (*xMutexLeave)(sqlite3_mutex *); - int (*xMutexHeld)(sqlite3_mutex *); - int (*xMutexNotheld)(sqlite3_mutex *); -}; - -/* -** CAPI3REF: Mutex Verification Routines -** -** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines -** are intended for use inside assert() statements. ^The SQLite core -** never uses these routines except inside an assert() and applications -** are advised to follow the lead of the core. ^The SQLite core only -** provides implementations for these routines when it is compiled -** with the SQLITE_DEBUG flag. ^External mutex implementations -** are only required to provide these routines if SQLITE_DEBUG is -** defined and if NDEBUG is not defined. -** -** ^These routines should return true if the mutex in their argument -** is held or not held, respectively, by the calling thread. -** -** ^The implementation is not required to provide versions of these -** routines that actually work. If the implementation does not provide working -** versions of these routines, it should at least provide stubs that always -** return true so that one does not get spurious assertion failures. -** -** ^If the argument to sqlite3_mutex_held() is a NULL pointer then -** the routine should return 1. This seems counter-intuitive since -** clearly the mutex cannot be held if it does not exist. But -** the reason the mutex does not exist is because the build is not -** using mutexes. And we do not want the assert() containing the -** call to sqlite3_mutex_held() to fail, so a non-zero return is -** the appropriate thing to do. ^The sqlite3_mutex_notheld() -** interface should also return 1 when given a NULL pointer. -*/ -#ifndef NDEBUG -SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*); -SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*); -#endif - -/* -** CAPI3REF: Mutex Types -** -** The [sqlite3_mutex_alloc()] interface takes a single argument -** which is one of these integer constants. -** -** The set of static mutexes may change from one SQLite release to the -** next. Applications that override the built-in mutex logic must be -** prepared to accommodate additional static mutexes. -*/ -#define SQLITE_MUTEX_FAST 0 -#define SQLITE_MUTEX_RECURSIVE 1 -#define SQLITE_MUTEX_STATIC_MASTER 2 -#define SQLITE_MUTEX_STATIC_MEM 3 /* sqlite3_malloc() */ -#define SQLITE_MUTEX_STATIC_MEM2 4 /* NOT USED */ -#define SQLITE_MUTEX_STATIC_OPEN 4 /* sqlite3BtreeOpen() */ -#define SQLITE_MUTEX_STATIC_PRNG 5 /* sqlite3_random() */ -#define SQLITE_MUTEX_STATIC_LRU 6 /* lru page list */ -#define SQLITE_MUTEX_STATIC_LRU2 7 /* NOT USED */ -#define SQLITE_MUTEX_STATIC_PMEM 7 /* sqlite3PageMalloc() */ - -/* -** CAPI3REF: Retrieve the mutex for a database connection -** -** ^This interface returns a pointer the [sqlite3_mutex] object that -** serializes access to the [database connection] given in the argument -** when the [threading mode] is Serialized. -** ^If the [threading mode] is Single-thread or Multi-thread then this -** routine returns a NULL pointer. -*/ -SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*); - -/* -** CAPI3REF: Low-Level Control Of Database Files -** -** ^The [sqlite3_file_control()] interface makes a direct call to the -** xFileControl method for the [sqlite3_io_methods] object associated -** with a particular database identified by the second argument. ^The -** name of the database is "main" for the main database or "temp" for the -** TEMP database, or the name that appears after the AS keyword for -** databases that are added using the [ATTACH] SQL command. -** ^A NULL pointer can be used in place of "main" to refer to the -** main database file. -** ^The third and fourth parameters to this routine -** are passed directly through to the second and third parameters of -** the xFileControl method. ^The return value of the xFileControl -** method becomes the return value of this routine. -** -** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes -** a pointer to the underlying [sqlite3_file] object to be written into -** the space pointed to by the 4th parameter. ^The SQLITE_FCNTL_FILE_POINTER -** case is a short-circuit path which does not actually invoke the -** underlying sqlite3_io_methods.xFileControl method. -** -** ^If the second parameter (zDbName) does not match the name of any -** open database file, then SQLITE_ERROR is returned. ^This error -** code is not remembered and will not be recalled by [sqlite3_errcode()] -** or [sqlite3_errmsg()]. The underlying xFileControl method might -** also return SQLITE_ERROR. There is no way to distinguish between -** an incorrect zDbName and an SQLITE_ERROR return from the underlying -** xFileControl method. -** -** See also: [SQLITE_FCNTL_LOCKSTATE] -*/ -SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*); - -/* -** CAPI3REF: Testing Interface -** -** ^The sqlite3_test_control() interface is used to read out internal -** state of SQLite and to inject faults into SQLite for testing -** purposes. ^The first parameter is an operation code that determines -** the number, meaning, and operation of all subsequent parameters. -** -** This interface is not for use by applications. It exists solely -** for verifying the correct operation of the SQLite library. Depending -** on how the SQLite library is compiled, this interface might not exist. -** -** The details of the operation codes, their meanings, the parameters -** they take, and what they do are all subject to change without notice. -** Unlike most of the SQLite API, this function is not guaranteed to -** operate consistently from one release to the next. -*/ -SQLITE_API int sqlite3_test_control(int op, ...); - -/* -** CAPI3REF: Testing Interface Operation Codes -** -** These constants are the valid operation code parameters used -** as the first argument to [sqlite3_test_control()]. -** -** These parameters and their meanings are subject to change -** without notice. These values are for testing purposes only. -** Applications should not use any of these parameters or the -** [sqlite3_test_control()] interface. -*/ -#define SQLITE_TESTCTRL_FIRST 5 -#define SQLITE_TESTCTRL_PRNG_SAVE 5 -#define SQLITE_TESTCTRL_PRNG_RESTORE 6 -#define SQLITE_TESTCTRL_PRNG_RESET 7 -#define SQLITE_TESTCTRL_BITVEC_TEST 8 -#define SQLITE_TESTCTRL_FAULT_INSTALL 9 -#define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS 10 -#define SQLITE_TESTCTRL_PENDING_BYTE 11 -#define SQLITE_TESTCTRL_ASSERT 12 -#define SQLITE_TESTCTRL_ALWAYS 13 -#define SQLITE_TESTCTRL_RESERVE 14 -#define SQLITE_TESTCTRL_OPTIMIZATIONS 15 -#define SQLITE_TESTCTRL_ISKEYWORD 16 -#define SQLITE_TESTCTRL_SCRATCHMALLOC 17 -#define SQLITE_TESTCTRL_LOCALTIME_FAULT 18 -#define SQLITE_TESTCTRL_EXPLAIN_STMT 19 -#define SQLITE_TESTCTRL_LAST 19 - -/* -** CAPI3REF: SQLite Runtime Status -** -** ^This interface is used to retrieve runtime status information -** about the performance of SQLite, and optionally to reset various -** highwater marks. ^The first argument is an integer code for -** the specific parameter to measure. ^(Recognized integer codes -** are of the form [status parameters | SQLITE_STATUS_...].)^ -** ^The current value of the parameter is returned into *pCurrent. -** ^The highest recorded value is returned in *pHighwater. ^If the -** resetFlag is true, then the highest record value is reset after -** *pHighwater is written. ^(Some parameters do not record the highest -** value. For those parameters -** nothing is written into *pHighwater and the resetFlag is ignored.)^ -** ^(Other parameters record only the highwater mark and not the current -** value. For these latter parameters nothing is written into *pCurrent.)^ -** -** ^The sqlite3_status() routine returns SQLITE_OK on success and a -** non-zero [error code] on failure. -** -** This routine is threadsafe but is not atomic. This routine can be -** called while other threads are running the same or different SQLite -** interfaces. However the values returned in *pCurrent and -** *pHighwater reflect the status of SQLite at different points in time -** and it is possible that another thread might change the parameter -** in between the times when *pCurrent and *pHighwater are written. -** -** See also: [sqlite3_db_status()] -*/ -SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag); - - -/* -** CAPI3REF: Status Parameters -** KEYWORDS: {status parameters} -** -** These integer constants designate various run-time status parameters -** that can be returned by [sqlite3_status()]. -** -**
    -** [[SQLITE_STATUS_MEMORY_USED]] ^(
    SQLITE_STATUS_MEMORY_USED
    -**
    This parameter is the current amount of memory checked out -** using [sqlite3_malloc()], either directly or indirectly. The -** figure includes calls made to [sqlite3_malloc()] by the application -** and internal memory usage by the SQLite library. Scratch memory -** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache -** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in -** this parameter. The amount returned is the sum of the allocation -** sizes as reported by the xSize method in [sqlite3_mem_methods].
    )^ -** -** [[SQLITE_STATUS_MALLOC_SIZE]] ^(
    SQLITE_STATUS_MALLOC_SIZE
    -**
    This parameter records the largest memory allocation request -** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their -** internal equivalents). Only the value returned in the -** *pHighwater parameter to [sqlite3_status()] is of interest. -** The value written into the *pCurrent parameter is undefined.
    )^ -** -** [[SQLITE_STATUS_MALLOC_COUNT]] ^(
    SQLITE_STATUS_MALLOC_COUNT
    -**
    This parameter records the number of separate memory allocations -** currently checked out.
    )^ -** -** [[SQLITE_STATUS_PAGECACHE_USED]] ^(
    SQLITE_STATUS_PAGECACHE_USED
    -**
    This parameter returns the number of pages used out of the -** [pagecache memory allocator] that was configured using -** [SQLITE_CONFIG_PAGECACHE]. The -** value returned is in pages, not in bytes.
    )^ -** -** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]] -** ^(
    SQLITE_STATUS_PAGECACHE_OVERFLOW
    -**
    This parameter returns the number of bytes of page cache -** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE] -** buffer and where forced to overflow to [sqlite3_malloc()]. The -** returned value includes allocations that overflowed because they -** where too large (they were larger than the "sz" parameter to -** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because -** no space was left in the page cache.
    )^ -** -** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(
    SQLITE_STATUS_PAGECACHE_SIZE
    -**
    This parameter records the largest memory allocation request -** handed to [pagecache memory allocator]. Only the value returned in the -** *pHighwater parameter to [sqlite3_status()] is of interest. -** The value written into the *pCurrent parameter is undefined.
    )^ -** -** [[SQLITE_STATUS_SCRATCH_USED]] ^(
    SQLITE_STATUS_SCRATCH_USED
    -**
    This parameter returns the number of allocations used out of the -** [scratch memory allocator] configured using -** [SQLITE_CONFIG_SCRATCH]. The value returned is in allocations, not -** in bytes. Since a single thread may only have one scratch allocation -** outstanding at time, this parameter also reports the number of threads -** using scratch memory at the same time.
    )^ -** -** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(
    SQLITE_STATUS_SCRATCH_OVERFLOW
    -**
    This parameter returns the number of bytes of scratch memory -** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH] -** buffer and where forced to overflow to [sqlite3_malloc()]. The values -** returned include overflows because the requested allocation was too -** larger (that is, because the requested allocation was larger than the -** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer -** slots were available. -**
    )^ -** -** [[SQLITE_STATUS_SCRATCH_SIZE]] ^(
    SQLITE_STATUS_SCRATCH_SIZE
    -**
    This parameter records the largest memory allocation request -** handed to [scratch memory allocator]. Only the value returned in the -** *pHighwater parameter to [sqlite3_status()] is of interest. -** The value written into the *pCurrent parameter is undefined.
    )^ -** -** [[SQLITE_STATUS_PARSER_STACK]] ^(
    SQLITE_STATUS_PARSER_STACK
    -**
    This parameter records the deepest parser stack. It is only -** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].
    )^ -**
    -** -** New status parameters may be added from time to time. -*/ -#define SQLITE_STATUS_MEMORY_USED 0 -#define SQLITE_STATUS_PAGECACHE_USED 1 -#define SQLITE_STATUS_PAGECACHE_OVERFLOW 2 -#define SQLITE_STATUS_SCRATCH_USED 3 -#define SQLITE_STATUS_SCRATCH_OVERFLOW 4 -#define SQLITE_STATUS_MALLOC_SIZE 5 -#define SQLITE_STATUS_PARSER_STACK 6 -#define SQLITE_STATUS_PAGECACHE_SIZE 7 -#define SQLITE_STATUS_SCRATCH_SIZE 8 -#define SQLITE_STATUS_MALLOC_COUNT 9 - -/* -** CAPI3REF: Database Connection Status -** -** ^This interface is used to retrieve runtime status information -** about a single [database connection]. ^The first argument is the -** database connection object to be interrogated. ^The second argument -** is an integer constant, taken from the set of -** [SQLITE_DBSTATUS options], that -** determines the parameter to interrogate. The set of -** [SQLITE_DBSTATUS options] is likely -** to grow in future releases of SQLite. -** -** ^The current value of the requested parameter is written into *pCur -** and the highest instantaneous value is written into *pHiwtr. ^If -** the resetFlg is true, then the highest instantaneous value is -** reset back down to the current value. -** -** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a -** non-zero [error code] on failure. -** -** See also: [sqlite3_status()] and [sqlite3_stmt_status()]. -*/ -SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg); - -/* -** CAPI3REF: Status Parameters for database connections -** KEYWORDS: {SQLITE_DBSTATUS options} -** -** These constants are the available integer "verbs" that can be passed as -** the second argument to the [sqlite3_db_status()] interface. -** -** New verbs may be added in future releases of SQLite. Existing verbs -** might be discontinued. Applications should check the return code from -** [sqlite3_db_status()] to make sure that the call worked. -** The [sqlite3_db_status()] interface will return a non-zero error code -** if a discontinued or unsupported verb is invoked. -** -**
    -** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(
    SQLITE_DBSTATUS_LOOKASIDE_USED
    -**
    This parameter returns the number of lookaside memory slots currently -** checked out.
    )^ -** -** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(
    SQLITE_DBSTATUS_LOOKASIDE_HIT
    -**
    This parameter returns the number malloc attempts that were -** satisfied using lookaside memory. Only the high-water value is meaningful; -** the current value is always zero.)^ -** -** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]] -** ^(
    SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE
    -**
    This parameter returns the number malloc attempts that might have -** been satisfied using lookaside memory but failed due to the amount of -** memory requested being larger than the lookaside slot size. -** Only the high-water value is meaningful; -** the current value is always zero.)^ -** -** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]] -** ^(
    SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL
    -**
    This parameter returns the number malloc attempts that might have -** been satisfied using lookaside memory but failed due to all lookaside -** memory already being in use. -** Only the high-water value is meaningful; -** the current value is always zero.)^ -** -** [[SQLITE_DBSTATUS_CACHE_USED]] ^(
    SQLITE_DBSTATUS_CACHE_USED
    -**
    This parameter returns the approximate number of of bytes of heap -** memory used by all pager caches associated with the database connection.)^ -** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0. -** -** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(
    SQLITE_DBSTATUS_SCHEMA_USED
    -**
    This parameter returns the approximate number of of bytes of heap -** memory used to store the schema for all databases associated -** with the connection - main, temp, and any [ATTACH]-ed databases.)^ -** ^The full amount of memory used by the schemas is reported, even if the -** schema memory is shared with other database connections due to -** [shared cache mode] being enabled. -** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0. -** -** [[SQLITE_DBSTATUS_STMT_USED]] ^(
    SQLITE_DBSTATUS_STMT_USED
    -**
    This parameter returns the approximate number of of bytes of heap -** and lookaside memory used by all prepared statements associated with -** the database connection.)^ -** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0. -**
    -** -** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(
    SQLITE_DBSTATUS_CACHE_HIT
    -**
    This parameter returns the number of pager cache hits that have -** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT -** is always 0. -**
    -** -** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(
    SQLITE_DBSTATUS_CACHE_MISS
    -**
    This parameter returns the number of pager cache misses that have -** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS -** is always 0. -**
    -** -** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(
    SQLITE_DBSTATUS_CACHE_WRITE
    -**
    This parameter returns the number of dirty cache entries that have -** been written to disk. Specifically, the number of pages written to the -** wal file in wal mode databases, or the number of pages written to the -** database file in rollback mode databases. Any pages written as part of -** transaction rollback or database recovery operations are not included. -** If an IO or other error occurs while writing a page to disk, the effect -** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The -** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0. -**
    -**
    -*/ -#define SQLITE_DBSTATUS_LOOKASIDE_USED 0 -#define SQLITE_DBSTATUS_CACHE_USED 1 -#define SQLITE_DBSTATUS_SCHEMA_USED 2 -#define SQLITE_DBSTATUS_STMT_USED 3 -#define SQLITE_DBSTATUS_LOOKASIDE_HIT 4 -#define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE 5 -#define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL 6 -#define SQLITE_DBSTATUS_CACHE_HIT 7 -#define SQLITE_DBSTATUS_CACHE_MISS 8 -#define SQLITE_DBSTATUS_CACHE_WRITE 9 -#define SQLITE_DBSTATUS_MAX 9 /* Largest defined DBSTATUS */ - - -/* -** CAPI3REF: Prepared Statement Status -** -** ^(Each prepared statement maintains various -** [SQLITE_STMTSTATUS counters] that measure the number -** of times it has performed specific operations.)^ These counters can -** be used to monitor the performance characteristics of the prepared -** statements. For example, if the number of table steps greatly exceeds -** the number of table searches or result rows, that would tend to indicate -** that the prepared statement is using a full table scan rather than -** an index. -** -** ^(This interface is used to retrieve and reset counter values from -** a [prepared statement]. The first argument is the prepared statement -** object to be interrogated. The second argument -** is an integer code for a specific [SQLITE_STMTSTATUS counter] -** to be interrogated.)^ -** ^The current value of the requested counter is returned. -** ^If the resetFlg is true, then the counter is reset to zero after this -** interface call returns. -** -** See also: [sqlite3_status()] and [sqlite3_db_status()]. -*/ -SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg); - -/* -** CAPI3REF: Status Parameters for prepared statements -** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters} -** -** These preprocessor macros define integer codes that name counter -** values associated with the [sqlite3_stmt_status()] interface. -** The meanings of the various counters are as follows: -** -**
    -** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]]
    SQLITE_STMTSTATUS_FULLSCAN_STEP
    -**
    ^This is the number of times that SQLite has stepped forward in -** a table as part of a full table scan. Large numbers for this counter -** may indicate opportunities for performance improvement through -** careful use of indices.
    -** -** [[SQLITE_STMTSTATUS_SORT]]
    SQLITE_STMTSTATUS_SORT
    -**
    ^This is the number of sort operations that have occurred. -** A non-zero value in this counter may indicate an opportunity to -** improvement performance through careful use of indices.
    -** -** [[SQLITE_STMTSTATUS_AUTOINDEX]]
    SQLITE_STMTSTATUS_AUTOINDEX
    -**
    ^This is the number of rows inserted into transient indices that -** were created automatically in order to help joins run faster. -** A non-zero value in this counter may indicate an opportunity to -** improvement performance by adding permanent indices that do not -** need to be reinitialized each time the statement is run.
    -**
    -*/ -#define SQLITE_STMTSTATUS_FULLSCAN_STEP 1 -#define SQLITE_STMTSTATUS_SORT 2 -#define SQLITE_STMTSTATUS_AUTOINDEX 3 - -/* -** CAPI3REF: Custom Page Cache Object -** -** The sqlite3_pcache type is opaque. It is implemented by -** the pluggable module. The SQLite core has no knowledge of -** its size or internal structure and never deals with the -** sqlite3_pcache object except by holding and passing pointers -** to the object. -** -** See [sqlite3_pcache_methods2] for additional information. -*/ -typedef struct sqlite3_pcache sqlite3_pcache; - -/* -** CAPI3REF: Custom Page Cache Object -** -** The sqlite3_pcache_page object represents a single page in the -** page cache. The page cache will allocate instances of this -** object. Various methods of the page cache use pointers to instances -** of this object as parameters or as their return value. -** -** See [sqlite3_pcache_methods2] for additional information. -*/ -typedef struct sqlite3_pcache_page sqlite3_pcache_page; -struct sqlite3_pcache_page { - void *pBuf; /* The content of the page */ - void *pExtra; /* Extra information associated with the page */ -}; - -/* -** CAPI3REF: Application Defined Page Cache. -** KEYWORDS: {page cache} -** -** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can -** register an alternative page cache implementation by passing in an -** instance of the sqlite3_pcache_methods2 structure.)^ -** In many applications, most of the heap memory allocated by -** SQLite is used for the page cache. -** By implementing a -** custom page cache using this API, an application can better control -** the amount of memory consumed by SQLite, the way in which -** that memory is allocated and released, and the policies used to -** determine exactly which parts of a database file are cached and for -** how long. -** -** The alternative page cache mechanism is an -** extreme measure that is only needed by the most demanding applications. -** The built-in page cache is recommended for most uses. -** -** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an -** internal buffer by SQLite within the call to [sqlite3_config]. Hence -** the application may discard the parameter after the call to -** [sqlite3_config()] returns.)^ -** -** [[the xInit() page cache method]] -** ^(The xInit() method is called once for each effective -** call to [sqlite3_initialize()])^ -** (usually only once during the lifetime of the process). ^(The xInit() -** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^ -** The intent of the xInit() method is to set up global data structures -** required by the custom page cache implementation. -** ^(If the xInit() method is NULL, then the -** built-in default page cache is used instead of the application defined -** page cache.)^ -** -** [[the xShutdown() page cache method]] -** ^The xShutdown() method is called by [sqlite3_shutdown()]. -** It can be used to clean up -** any outstanding resources before process shutdown, if required. -** ^The xShutdown() method may be NULL. -** -** ^SQLite automatically serializes calls to the xInit method, -** so the xInit method need not be threadsafe. ^The -** xShutdown method is only called from [sqlite3_shutdown()] so it does -** not need to be threadsafe either. All other methods must be threadsafe -** in multithreaded applications. -** -** ^SQLite will never invoke xInit() more than once without an intervening -** call to xShutdown(). -** -** [[the xCreate() page cache methods]] -** ^SQLite invokes the xCreate() method to construct a new cache instance. -** SQLite will typically create one cache instance for each open database file, -** though this is not guaranteed. ^The -** first parameter, szPage, is the size in bytes of the pages that must -** be allocated by the cache. ^szPage will always a power of two. ^The -** second parameter szExtra is a number of bytes of extra storage -** associated with each page cache entry. ^The szExtra parameter will -** a number less than 250. SQLite will use the -** extra szExtra bytes on each page to store metadata about the underlying -** database page on disk. The value passed into szExtra depends -** on the SQLite version, the target platform, and how SQLite was compiled. -** ^The third argument to xCreate(), bPurgeable, is true if the cache being -** created will be used to cache database pages of a file stored on disk, or -** false if it is used for an in-memory database. The cache implementation -** does not have to do anything special based with the value of bPurgeable; -** it is purely advisory. ^On a cache where bPurgeable is false, SQLite will -** never invoke xUnpin() except to deliberately delete a page. -** ^In other words, calls to xUnpin() on a cache with bPurgeable set to -** false will always have the "discard" flag set to true. -** ^Hence, a cache created with bPurgeable false will -** never contain any unpinned pages. -** -** [[the xCachesize() page cache method]] -** ^(The xCachesize() method may be called at any time by SQLite to set the -** suggested maximum cache-size (number of pages stored by) the cache -** instance passed as the first argument. This is the value configured using -** the SQLite "[PRAGMA cache_size]" command.)^ As with the bPurgeable -** parameter, the implementation is not required to do anything with this -** value; it is advisory only. -** -** [[the xPagecount() page cache methods]] -** The xPagecount() method must return the number of pages currently -** stored in the cache, both pinned and unpinned. -** -** [[the xFetch() page cache methods]] -** The xFetch() method locates a page in the cache and returns a pointer to -** an sqlite3_pcache_page object associated with that page, or a NULL pointer. -** The pBuf element of the returned sqlite3_pcache_page object will be a -** pointer to a buffer of szPage bytes used to store the content of a -** single database page. The pExtra element of sqlite3_pcache_page will be -** a pointer to the szExtra bytes of extra storage that SQLite has requested -** for each entry in the page cache. -** -** The page to be fetched is determined by the key. ^The minimum key value -** is 1. After it has been retrieved using xFetch, the page is considered -** to be "pinned". -** -** If the requested page is already in the page cache, then the page cache -** implementation must return a pointer to the page buffer with its content -** intact. If the requested page is not already in the cache, then the -** cache implementation should use the value of the createFlag -** parameter to help it determined what action to take: -** -** -**
    createFlag Behavior when page is not already in cache -**
    0 Do not allocate a new page. Return NULL. -**
    1 Allocate a new page if it easy and convenient to do so. -** Otherwise return NULL. -**
    2 Make every effort to allocate a new page. Only return -** NULL if allocating a new page is effectively impossible. -**
    -** -** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1. SQLite -** will only use a createFlag of 2 after a prior call with a createFlag of 1 -** failed.)^ In between the to xFetch() calls, SQLite may -** attempt to unpin one or more cache pages by spilling the content of -** pinned pages to disk and synching the operating system disk cache. -** -** [[the xUnpin() page cache method]] -** ^xUnpin() is called by SQLite with a pointer to a currently pinned page -** as its second argument. If the third parameter, discard, is non-zero, -** then the page must be evicted from the cache. -** ^If the discard parameter is -** zero, then the page may be discarded or retained at the discretion of -** page cache implementation. ^The page cache implementation -** may choose to evict unpinned pages at any time. -** -** The cache must not perform any reference counting. A single -** call to xUnpin() unpins the page regardless of the number of prior calls -** to xFetch(). -** -** [[the xRekey() page cache methods]] -** The xRekey() method is used to change the key value associated with the -** page passed as the second argument. If the cache -** previously contains an entry associated with newKey, it must be -** discarded. ^Any prior cache entry associated with newKey is guaranteed not -** to be pinned. -** -** When SQLite calls the xTruncate() method, the cache must discard all -** existing cache entries with page numbers (keys) greater than or equal -** to the value of the iLimit parameter passed to xTruncate(). If any -** of these pages are pinned, they are implicitly unpinned, meaning that -** they can be safely discarded. -** -** [[the xDestroy() page cache method]] -** ^The xDestroy() method is used to delete a cache allocated by xCreate(). -** All resources associated with the specified cache should be freed. ^After -** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*] -** handle invalid, and will not use it with any other sqlite3_pcache_methods2 -** functions. -** -** [[the xShrink() page cache method]] -** ^SQLite invokes the xShrink() method when it wants the page cache to -** free up as much of heap memory as possible. The page cache implementation -** is not obligated to free any memory, but well-behaved implementations should -** do their best. -*/ -typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2; -struct sqlite3_pcache_methods2 { - int iVersion; - void *pArg; - int (*xInit)(void*); - void (*xShutdown)(void*); - sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable); - void (*xCachesize)(sqlite3_pcache*, int nCachesize); - int (*xPagecount)(sqlite3_pcache*); - sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag); - void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard); - void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*, - unsigned oldKey, unsigned newKey); - void (*xTruncate)(sqlite3_pcache*, unsigned iLimit); - void (*xDestroy)(sqlite3_pcache*); - void (*xShrink)(sqlite3_pcache*); -}; - -/* -** This is the obsolete pcache_methods object that has now been replaced -** by sqlite3_pcache_methods2. This object is not used by SQLite. It is -** retained in the header file for backwards compatibility only. -*/ -typedef struct sqlite3_pcache_methods sqlite3_pcache_methods; -struct sqlite3_pcache_methods { - void *pArg; - int (*xInit)(void*); - void (*xShutdown)(void*); - sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable); - void (*xCachesize)(sqlite3_pcache*, int nCachesize); - int (*xPagecount)(sqlite3_pcache*); - void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag); - void (*xUnpin)(sqlite3_pcache*, void*, int discard); - void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey); - void (*xTruncate)(sqlite3_pcache*, unsigned iLimit); - void (*xDestroy)(sqlite3_pcache*); -}; - - -/* -** CAPI3REF: Online Backup Object -** -** The sqlite3_backup object records state information about an ongoing -** online backup operation. ^The sqlite3_backup object is created by -** a call to [sqlite3_backup_init()] and is destroyed by a call to -** [sqlite3_backup_finish()]. -** -** See Also: [Using the SQLite Online Backup API] -*/ -typedef struct sqlite3_backup sqlite3_backup; - -/* -** CAPI3REF: Online Backup API. -** -** The backup API copies the content of one database into another. -** It is useful either for creating backups of databases or -** for copying in-memory databases to or from persistent files. -** -** See Also: [Using the SQLite Online Backup API] -** -** ^SQLite holds a write transaction open on the destination database file -** for the duration of the backup operation. -** ^The source database is read-locked only while it is being read; -** it is not locked continuously for the entire backup operation. -** ^Thus, the backup may be performed on a live source database without -** preventing other database connections from -** reading or writing to the source database while the backup is underway. -** -** ^(To perform a backup operation: -**
      -**
    1. sqlite3_backup_init() is called once to initialize the -** backup, -**
    2. sqlite3_backup_step() is called one or more times to transfer -** the data between the two databases, and finally -**
    3. sqlite3_backup_finish() is called to release all resources -** associated with the backup operation. -**
    )^ -** There should be exactly one call to sqlite3_backup_finish() for each -** successful call to sqlite3_backup_init(). -** -** [[sqlite3_backup_init()]] sqlite3_backup_init() -** -** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the -** [database connection] associated with the destination database -** and the database name, respectively. -** ^The database name is "main" for the main database, "temp" for the -** temporary database, or the name specified after the AS keyword in -** an [ATTACH] statement for an attached database. -** ^The S and M arguments passed to -** sqlite3_backup_init(D,N,S,M) identify the [database connection] -** and database name of the source database, respectively. -** ^The source and destination [database connections] (parameters S and D) -** must be different or else sqlite3_backup_init(D,N,S,M) will fail with -** an error. -** -** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is -** returned and an error code and error message are stored in the -** destination [database connection] D. -** ^The error code and message for the failed call to sqlite3_backup_init() -** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or -** [sqlite3_errmsg16()] functions. -** ^A successful call to sqlite3_backup_init() returns a pointer to an -** [sqlite3_backup] object. -** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and -** sqlite3_backup_finish() functions to perform the specified backup -** operation. -** -** [[sqlite3_backup_step()]] sqlite3_backup_step() -** -** ^Function sqlite3_backup_step(B,N) will copy up to N pages between -** the source and destination databases specified by [sqlite3_backup] object B. -** ^If N is negative, all remaining source pages are copied. -** ^If sqlite3_backup_step(B,N) successfully copies N pages and there -** are still more pages to be copied, then the function returns [SQLITE_OK]. -** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages -** from source to destination, then it returns [SQLITE_DONE]. -** ^If an error occurs while running sqlite3_backup_step(B,N), -** then an [error code] is returned. ^As well as [SQLITE_OK] and -** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY], -** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an -** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code. -** -** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if -**
      -**
    1. the destination database was opened read-only, or -**
    2. the destination database is using write-ahead-log journaling -** and the destination and source page sizes differ, or -**
    3. the destination database is an in-memory database and the -** destination and source page sizes differ. -**
    )^ -** -** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then -** the [sqlite3_busy_handler | busy-handler function] -** is invoked (if one is specified). ^If the -** busy-handler returns non-zero before the lock is available, then -** [SQLITE_BUSY] is returned to the caller. ^In this case the call to -** sqlite3_backup_step() can be retried later. ^If the source -** [database connection] -** is being used to write to the source database when sqlite3_backup_step() -** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this -** case the call to sqlite3_backup_step() can be retried later on. ^(If -** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or -** [SQLITE_READONLY] is returned, then -** there is no point in retrying the call to sqlite3_backup_step(). These -** errors are considered fatal.)^ The application must accept -** that the backup operation has failed and pass the backup operation handle -** to the sqlite3_backup_finish() to release associated resources. -** -** ^The first call to sqlite3_backup_step() obtains an exclusive lock -** on the destination file. ^The exclusive lock is not released until either -** sqlite3_backup_finish() is called or the backup operation is complete -** and sqlite3_backup_step() returns [SQLITE_DONE]. ^Every call to -** sqlite3_backup_step() obtains a [shared lock] on the source database that -** lasts for the duration of the sqlite3_backup_step() call. -** ^Because the source database is not locked between calls to -** sqlite3_backup_step(), the source database may be modified mid-way -** through the backup process. ^If the source database is modified by an -** external process or via a database connection other than the one being -** used by the backup operation, then the backup will be automatically -** restarted by the next call to sqlite3_backup_step(). ^If the source -** database is modified by the using the same database connection as is used -** by the backup operation, then the backup database is automatically -** updated at the same time. -** -** [[sqlite3_backup_finish()]] sqlite3_backup_finish() -** -** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the -** application wishes to abandon the backup operation, the application -** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish(). -** ^The sqlite3_backup_finish() interfaces releases all -** resources associated with the [sqlite3_backup] object. -** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any -** active write-transaction on the destination database is rolled back. -** The [sqlite3_backup] object is invalid -** and may not be used following a call to sqlite3_backup_finish(). -** -** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no -** sqlite3_backup_step() errors occurred, regardless or whether or not -** sqlite3_backup_step() completed. -** ^If an out-of-memory condition or IO error occurred during any prior -** sqlite3_backup_step() call on the same [sqlite3_backup] object, then -** sqlite3_backup_finish() returns the corresponding [error code]. -** -** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step() -** is not a permanent error and does not affect the return value of -** sqlite3_backup_finish(). -** -** [[sqlite3_backup__remaining()]] [[sqlite3_backup_pagecount()]] -** sqlite3_backup_remaining() and sqlite3_backup_pagecount() -** -** ^Each call to sqlite3_backup_step() sets two values inside -** the [sqlite3_backup] object: the number of pages still to be backed -** up and the total number of pages in the source database file. -** The sqlite3_backup_remaining() and sqlite3_backup_pagecount() interfaces -** retrieve these two values, respectively. -** -** ^The values returned by these functions are only updated by -** sqlite3_backup_step(). ^If the source database is modified during a backup -** operation, then the values are not updated to account for any extra -** pages that need to be updated or the size of the source database file -** changing. -** -** Concurrent Usage of Database Handles -** -** ^The source [database connection] may be used by the application for other -** purposes while a backup operation is underway or being initialized. -** ^If SQLite is compiled and configured to support threadsafe database -** connections, then the source database connection may be used concurrently -** from within other threads. -** -** However, the application must guarantee that the destination -** [database connection] is not passed to any other API (by any thread) after -** sqlite3_backup_init() is called and before the corresponding call to -** sqlite3_backup_finish(). SQLite does not currently check to see -** if the application incorrectly accesses the destination [database connection] -** and so no error code is reported, but the operations may malfunction -** nevertheless. Use of the destination database connection while a -** backup is in progress might also also cause a mutex deadlock. -** -** If running in [shared cache mode], the application must -** guarantee that the shared cache used by the destination database -** is not accessed while the backup is running. In practice this means -** that the application must guarantee that the disk file being -** backed up to is not accessed by any connection within the process, -** not just the specific connection that was passed to sqlite3_backup_init(). -** -** The [sqlite3_backup] object itself is partially threadsafe. Multiple -** threads may safely make multiple concurrent calls to sqlite3_backup_step(). -** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount() -** APIs are not strictly speaking threadsafe. If they are invoked at the -** same time as another thread is invoking sqlite3_backup_step() it is -** possible that they return invalid values. -*/ -SQLITE_API sqlite3_backup *sqlite3_backup_init( - sqlite3 *pDest, /* Destination database handle */ - const char *zDestName, /* Destination database name */ - sqlite3 *pSource, /* Source database handle */ - const char *zSourceName /* Source database name */ -); -SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage); -SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p); -SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p); -SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p); - -/* -** CAPI3REF: Unlock Notification -** -** ^When running in shared-cache mode, a database operation may fail with -** an [SQLITE_LOCKED] error if the required locks on the shared-cache or -** individual tables within the shared-cache cannot be obtained. See -** [SQLite Shared-Cache Mode] for a description of shared-cache locking. -** ^This API may be used to register a callback that SQLite will invoke -** when the connection currently holding the required lock relinquishes it. -** ^This API is only available if the library was compiled with the -** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined. -** -** See Also: [Using the SQLite Unlock Notification Feature]. -** -** ^Shared-cache locks are released when a database connection concludes -** its current transaction, either by committing it or rolling it back. -** -** ^When a connection (known as the blocked connection) fails to obtain a -** shared-cache lock and SQLITE_LOCKED is returned to the caller, the -** identity of the database connection (the blocking connection) that -** has locked the required resource is stored internally. ^After an -** application receives an SQLITE_LOCKED error, it may call the -** sqlite3_unlock_notify() method with the blocked connection handle as -** the first argument to register for a callback that will be invoked -** when the blocking connections current transaction is concluded. ^The -** callback is invoked from within the [sqlite3_step] or [sqlite3_close] -** call that concludes the blocking connections transaction. -** -** ^(If sqlite3_unlock_notify() is called in a multi-threaded application, -** there is a chance that the blocking connection will have already -** concluded its transaction by the time sqlite3_unlock_notify() is invoked. -** If this happens, then the specified callback is invoked immediately, -** from within the call to sqlite3_unlock_notify().)^ -** -** ^If the blocked connection is attempting to obtain a write-lock on a -** shared-cache table, and more than one other connection currently holds -** a read-lock on the same table, then SQLite arbitrarily selects one of -** the other connections to use as the blocking connection. -** -** ^(There may be at most one unlock-notify callback registered by a -** blocked connection. If sqlite3_unlock_notify() is called when the -** blocked connection already has a registered unlock-notify callback, -** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is -** called with a NULL pointer as its second argument, then any existing -** unlock-notify callback is canceled. ^The blocked connections -** unlock-notify callback may also be canceled by closing the blocked -** connection using [sqlite3_close()]. -** -** The unlock-notify callback is not reentrant. If an application invokes -** any sqlite3_xxx API functions from within an unlock-notify callback, a -** crash or deadlock may be the result. -** -** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always -** returns SQLITE_OK. -** -** Callback Invocation Details -** -** When an unlock-notify callback is registered, the application provides a -** single void* pointer that is passed to the callback when it is invoked. -** However, the signature of the callback function allows SQLite to pass -** it an array of void* context pointers. The first argument passed to -** an unlock-notify callback is a pointer to an array of void* pointers, -** and the second is the number of entries in the array. -** -** When a blocking connections transaction is concluded, there may be -** more than one blocked connection that has registered for an unlock-notify -** callback. ^If two or more such blocked connections have specified the -** same callback function, then instead of invoking the callback function -** multiple times, it is invoked once with the set of void* context pointers -** specified by the blocked connections bundled together into an array. -** This gives the application an opportunity to prioritize any actions -** related to the set of unblocked database connections. -** -** Deadlock Detection -** -** Assuming that after registering for an unlock-notify callback a -** database waits for the callback to be issued before taking any further -** action (a reasonable assumption), then using this API may cause the -** application to deadlock. For example, if connection X is waiting for -** connection Y's transaction to be concluded, and similarly connection -** Y is waiting on connection X's transaction, then neither connection -** will proceed and the system may remain deadlocked indefinitely. -** -** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock -** detection. ^If a given call to sqlite3_unlock_notify() would put the -** system in a deadlocked state, then SQLITE_LOCKED is returned and no -** unlock-notify callback is registered. The system is said to be in -** a deadlocked state if connection A has registered for an unlock-notify -** callback on the conclusion of connection B's transaction, and connection -** B has itself registered for an unlock-notify callback when connection -** A's transaction is concluded. ^Indirect deadlock is also detected, so -** the system is also considered to be deadlocked if connection B has -** registered for an unlock-notify callback on the conclusion of connection -** C's transaction, where connection C is waiting on connection A. ^Any -** number of levels of indirection are allowed. -** -** The "DROP TABLE" Exception -** -** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost -** always appropriate to call sqlite3_unlock_notify(). There is however, -** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement, -** SQLite checks if there are any currently executing SELECT statements -** that belong to the same connection. If there are, SQLITE_LOCKED is -** returned. In this case there is no "blocking connection", so invoking -** sqlite3_unlock_notify() results in the unlock-notify callback being -** invoked immediately. If the application then re-attempts the "DROP TABLE" -** or "DROP INDEX" query, an infinite loop might be the result. -** -** One way around this problem is to check the extended error code returned -** by an sqlite3_step() call. ^(If there is a blocking connection, then the -** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in -** the special "DROP TABLE/INDEX" case, the extended error code is just -** SQLITE_LOCKED.)^ -*/ -SQLITE_API int sqlite3_unlock_notify( - sqlite3 *pBlocked, /* Waiting connection */ - void (*xNotify)(void **apArg, int nArg), /* Callback function to invoke */ - void *pNotifyArg /* Argument to pass to xNotify */ -); - - -/* -** CAPI3REF: String Comparison -** -** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications -** and extensions to compare the contents of two buffers containing UTF-8 -** strings in a case-independent fashion, using the same definition of "case -** independence" that SQLite uses internally when comparing identifiers. -*/ -SQLITE_API int sqlite3_stricmp(const char *, const char *); -SQLITE_API int sqlite3_strnicmp(const char *, const char *, int); - -/* -** CAPI3REF: Error Logging Interface -** -** ^The [sqlite3_log()] interface writes a message into the error log -** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()]. -** ^If logging is enabled, the zFormat string and subsequent arguments are -** used with [sqlite3_snprintf()] to generate the final output string. -** -** The sqlite3_log() interface is intended for use by extensions such as -** virtual tables, collating functions, and SQL functions. While there is -** nothing to prevent an application from calling sqlite3_log(), doing so -** is considered bad form. -** -** The zFormat string must not be NULL. -** -** To avoid deadlocks and other threading problems, the sqlite3_log() routine -** will not use dynamically allocated memory. The log message is stored in -** a fixed-length buffer on the stack. If the log message is longer than -** a few hundred characters, it will be truncated to the length of the -** buffer. -*/ -SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...); - -/* -** CAPI3REF: Write-Ahead Log Commit Hook -** -** ^The [sqlite3_wal_hook()] function is used to register a callback that -** will be invoked each time a database connection commits data to a -** [write-ahead log] (i.e. whenever a transaction is committed in -** [journal_mode | journal_mode=WAL mode]). -** -** ^The callback is invoked by SQLite after the commit has taken place and -** the associated write-lock on the database released, so the implementation -** may read, write or [checkpoint] the database as required. -** -** ^The first parameter passed to the callback function when it is invoked -** is a copy of the third parameter passed to sqlite3_wal_hook() when -** registering the callback. ^The second is a copy of the database handle. -** ^The third parameter is the name of the database that was written to - -** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter -** is the number of pages currently in the write-ahead log file, -** including those that were just committed. -** -** The callback function should normally return [SQLITE_OK]. ^If an error -** code is returned, that error will propagate back up through the -** SQLite code base to cause the statement that provoked the callback -** to report an error, though the commit will have still occurred. If the -** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value -** that does not correspond to any valid SQLite error code, the results -** are undefined. -** -** A single database handle may have at most a single write-ahead log callback -** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any -** previously registered write-ahead log callback. ^Note that the -** [sqlite3_wal_autocheckpoint()] interface and the -** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will -** those overwrite any prior [sqlite3_wal_hook()] settings. -*/ -SQLITE_API void *sqlite3_wal_hook( - sqlite3*, - int(*)(void *,sqlite3*,const char*,int), - void* -); - -/* -** CAPI3REF: Configure an auto-checkpoint -** -** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around -** [sqlite3_wal_hook()] that causes any database on [database connection] D -** to automatically [checkpoint] -** after committing a transaction if there are N or -** more frames in the [write-ahead log] file. ^Passing zero or -** a negative value as the nFrame parameter disables automatic -** checkpoints entirely. -** -** ^The callback registered by this function replaces any existing callback -** registered using [sqlite3_wal_hook()]. ^Likewise, registering a callback -** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism -** configured by this function. -** -** ^The [wal_autocheckpoint pragma] can be used to invoke this interface -** from SQL. -** -** ^Every new [database connection] defaults to having the auto-checkpoint -** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT] -** pages. The use of this interface -** is only necessary if the default setting is found to be suboptimal -** for a particular application. -*/ -SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N); - -/* -** CAPI3REF: Checkpoint a database -** -** ^The [sqlite3_wal_checkpoint(D,X)] interface causes database named X -** on [database connection] D to be [checkpointed]. ^If X is NULL or an -** empty string, then a checkpoint is run on all databases of -** connection D. ^If the database connection D is not in -** [WAL | write-ahead log mode] then this interface is a harmless no-op. -** -** ^The [wal_checkpoint pragma] can be used to invoke this interface -** from SQL. ^The [sqlite3_wal_autocheckpoint()] interface and the -** [wal_autocheckpoint pragma] can be used to cause this interface to be -** run whenever the WAL reaches a certain size threshold. -** -** See also: [sqlite3_wal_checkpoint_v2()] -*/ -SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb); - -/* -** CAPI3REF: Checkpoint a database -** -** Run a checkpoint operation on WAL database zDb attached to database -** handle db. The specific operation is determined by the value of the -** eMode parameter: -** -**
    -**
    SQLITE_CHECKPOINT_PASSIVE
    -** Checkpoint as many frames as possible without waiting for any database -** readers or writers to finish. Sync the db file if all frames in the log -** are checkpointed. This mode is the same as calling -** sqlite3_wal_checkpoint(). The busy-handler callback is never invoked. -** -**
    SQLITE_CHECKPOINT_FULL
    -** This mode blocks (calls the busy-handler callback) until there is no -** database writer and all readers are reading from the most recent database -** snapshot. It then checkpoints all frames in the log file and syncs the -** database file. This call blocks database writers while it is running, -** but not database readers. -** -**
    SQLITE_CHECKPOINT_RESTART
    -** This mode works the same way as SQLITE_CHECKPOINT_FULL, except after -** checkpointing the log file it blocks (calls the busy-handler callback) -** until all readers are reading from the database file only. This ensures -** that the next client to write to the database file restarts the log file -** from the beginning. This call blocks database writers while it is running, -** but not database readers. -**
    -** -** If pnLog is not NULL, then *pnLog is set to the total number of frames in -** the log file before returning. If pnCkpt is not NULL, then *pnCkpt is set to -** the total number of checkpointed frames (including any that were already -** checkpointed when this function is called). *pnLog and *pnCkpt may be -** populated even if sqlite3_wal_checkpoint_v2() returns other than SQLITE_OK. -** If no values are available because of an error, they are both set to -1 -** before returning to communicate this to the caller. -** -** All calls obtain an exclusive "checkpoint" lock on the database file. If -** any other process is running a checkpoint operation at the same time, the -** lock cannot be obtained and SQLITE_BUSY is returned. Even if there is a -** busy-handler configured, it will not be invoked in this case. -** -** The SQLITE_CHECKPOINT_FULL and RESTART modes also obtain the exclusive -** "writer" lock on the database file. If the writer lock cannot be obtained -** immediately, and a busy-handler is configured, it is invoked and the writer -** lock retried until either the busy-handler returns 0 or the lock is -** successfully obtained. The busy-handler is also invoked while waiting for -** database readers as described above. If the busy-handler returns 0 before -** the writer lock is obtained or while waiting for database readers, the -** checkpoint operation proceeds from that point in the same way as -** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible -** without blocking any further. SQLITE_BUSY is returned in this case. -** -** If parameter zDb is NULL or points to a zero length string, then the -** specified operation is attempted on all WAL databases. In this case the -** values written to output parameters *pnLog and *pnCkpt are undefined. If -** an SQLITE_BUSY error is encountered when processing one or more of the -** attached WAL databases, the operation is still attempted on any remaining -** attached databases and SQLITE_BUSY is returned to the caller. If any other -** error occurs while processing an attached database, processing is abandoned -** and the error code returned to the caller immediately. If no error -** (SQLITE_BUSY or otherwise) is encountered while processing the attached -** databases, SQLITE_OK is returned. -** -** If database zDb is the name of an attached database that is not in WAL -** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. If -** zDb is not NULL (or a zero length string) and is not the name of any -** attached database, SQLITE_ERROR is returned to the caller. -*/ -SQLITE_API int sqlite3_wal_checkpoint_v2( - sqlite3 *db, /* Database handle */ - const char *zDb, /* Name of attached database (or NULL) */ - int eMode, /* SQLITE_CHECKPOINT_* value */ - int *pnLog, /* OUT: Size of WAL log in frames */ - int *pnCkpt /* OUT: Total number of frames checkpointed */ -); - -/* -** CAPI3REF: Checkpoint operation parameters -** -** These constants can be used as the 3rd parameter to -** [sqlite3_wal_checkpoint_v2()]. See the [sqlite3_wal_checkpoint_v2()] -** documentation for additional information about the meaning and use of -** each of these values. -*/ -#define SQLITE_CHECKPOINT_PASSIVE 0 -#define SQLITE_CHECKPOINT_FULL 1 -#define SQLITE_CHECKPOINT_RESTART 2 - -/* -** CAPI3REF: Virtual Table Interface Configuration -** -** This function may be called by either the [xConnect] or [xCreate] method -** of a [virtual table] implementation to configure -** various facets of the virtual table interface. -** -** If this interface is invoked outside the context of an xConnect or -** xCreate virtual table method then the behavior is undefined. -** -** At present, there is only one option that may be configured using -** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].) Further options -** may be added in the future. -*/ -SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...); - -/* -** CAPI3REF: Virtual Table Configuration Options -** -** These macros define the various options to the -** [sqlite3_vtab_config()] interface that [virtual table] implementations -** can use to customize and optimize their behavior. -** -**
    -**
    SQLITE_VTAB_CONSTRAINT_SUPPORT -**
    Calls of the form -** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported, -** where X is an integer. If X is zero, then the [virtual table] whose -** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not -** support constraints. In this configuration (which is the default) if -** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire -** statement is rolled back as if [ON CONFLICT | OR ABORT] had been -** specified as part of the users SQL statement, regardless of the actual -** ON CONFLICT mode specified. -** -** If X is non-zero, then the virtual table implementation guarantees -** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before -** any modifications to internal or persistent data structures have been made. -** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite -** is able to roll back a statement or database transaction, and abandon -** or continue processing the current SQL statement as appropriate. -** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns -** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode -** had been ABORT. -** -** Virtual table implementations that are required to handle OR REPLACE -** must do so within the [xUpdate] method. If a call to the -** [sqlite3_vtab_on_conflict()] function indicates that the current ON -** CONFLICT policy is REPLACE, the virtual table implementation should -** silently replace the appropriate rows within the xUpdate callback and -** return SQLITE_OK. Or, if this is not possible, it may return -** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT -** constraint handling. -**
    -*/ -#define SQLITE_VTAB_CONSTRAINT_SUPPORT 1 - -/* -** CAPI3REF: Determine The Virtual Table Conflict Policy -** -** This function may only be called from within a call to the [xUpdate] method -** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The -** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL], -** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode -** of the SQL statement that triggered the call to the [xUpdate] method of the -** [virtual table]. -*/ -SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *); - -/* -** CAPI3REF: Conflict resolution modes -** -** These constants are returned by [sqlite3_vtab_on_conflict()] to -** inform a [virtual table] implementation what the [ON CONFLICT] mode -** is for the SQL statement being evaluated. -** -** Note that the [SQLITE_IGNORE] constant is also used as a potential -** return value from the [sqlite3_set_authorizer()] callback and that -** [SQLITE_ABORT] is also a [result code]. -*/ -#define SQLITE_ROLLBACK 1 -/* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */ -#define SQLITE_FAIL 3 -/* #define SQLITE_ABORT 4 // Also an error code */ -#define SQLITE_REPLACE 5 - - - -/* -** Undo the hack that converts floating point types to integer for -** builds on processors without floating point support. -*/ -#ifdef SQLITE_OMIT_FLOATING_POINT -# undef double -#endif - -#if 0 -} /* End of the 'extern "C"' block */ -#endif -#endif - -/* -** 2010 August 30 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -*/ - -#ifndef _SQLITE3RTREE_H_ -#define _SQLITE3RTREE_H_ - - -#if 0 -extern "C" { -#endif - -typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry; - -/* -** Register a geometry callback named zGeom that can be used as part of an -** R-Tree geometry query as follows: -** -** SELECT ... FROM WHERE MATCH $zGeom(... params ...) -*/ -SQLITE_API int sqlite3_rtree_geometry_callback( - sqlite3 *db, - const char *zGeom, -#ifdef SQLITE_RTREE_INT_ONLY - int (*xGeom)(sqlite3_rtree_geometry*, int n, sqlite3_int64 *a, int *pRes), -#else - int (*xGeom)(sqlite3_rtree_geometry*, int n, double *a, int *pRes), -#endif - void *pContext -); - - -/* -** A pointer to a structure of the following type is passed as the first -** argument to callbacks registered using rtree_geometry_callback(). -*/ -struct sqlite3_rtree_geometry { - void *pContext; /* Copy of pContext passed to s_r_g_c() */ - int nParam; /* Size of array aParam[] */ - double *aParam; /* Parameters passed to SQL geom function */ - void *pUser; /* Callback implementation user data */ - void (*xDelUser)(void *); /* Called by SQLite to clean up pUser */ -}; - - -#if 0 -} /* end of the 'extern "C"' block */ -#endif - -#endif /* ifndef _SQLITE3RTREE_H_ */ - - -/************** End of sqlite3.h *********************************************/ -/************** Continuing where we left off in sqliteInt.h ******************/ -/************** Include hash.h in the middle of sqliteInt.h ******************/ -/************** Begin file hash.h ********************************************/ -/* -** 2001 September 22 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** This is the header file for the generic hash-table implementation -** used in SQLite. -*/ -#ifndef _SQLITE_HASH_H_ -#define _SQLITE_HASH_H_ - -/* Forward declarations of structures. */ -typedef struct Hash Hash; -typedef struct HashElem HashElem; - -/* A complete hash table is an instance of the following structure. -** The internals of this structure are intended to be opaque -- client -** code should not attempt to access or modify the fields of this structure -** directly. Change this structure only by using the routines below. -** However, some of the "procedures" and "functions" for modifying and -** accessing this structure are really macros, so we can't really make -** this structure opaque. -** -** All elements of the hash table are on a single doubly-linked list. -** Hash.first points to the head of this list. -** -** There are Hash.htsize buckets. Each bucket points to a spot in -** the global doubly-linked list. The contents of the bucket are the -** element pointed to plus the next _ht.count-1 elements in the list. -** -** Hash.htsize and Hash.ht may be zero. In that case lookup is done -** by a linear search of the global list. For small tables, the -** Hash.ht table is never allocated because if there are few elements -** in the table, it is faster to do a linear search than to manage -** the hash table. -*/ -struct Hash { - unsigned int htsize; /* Number of buckets in the hash table */ - unsigned int count; /* Number of entries in this table */ - HashElem *first; /* The first element of the array */ - struct _ht { /* the hash table */ - int count; /* Number of entries with this hash */ - HashElem *chain; /* Pointer to first entry with this hash */ - } *ht; -}; - -/* Each element in the hash table is an instance of the following -** structure. All elements are stored on a single doubly-linked list. -** -** Again, this structure is intended to be opaque, but it can't really -** be opaque because it is used by macros. -*/ -struct HashElem { - HashElem *next, *prev; /* Next and previous elements in the table */ - void *data; /* Data associated with this element */ - const char *pKey; int nKey; /* Key associated with this element */ -}; - -/* -** Access routines. To delete, insert a NULL pointer. -*/ -SQLITE_PRIVATE void sqlite3HashInit(Hash*); -SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, int nKey, void *pData); -SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey, int nKey); -SQLITE_PRIVATE void sqlite3HashClear(Hash*); - -/* -** Macros for looping over all elements of a hash table. The idiom is -** like this: -** -** Hash h; -** HashElem *p; -** ... -** for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){ -** SomeStructure *pData = sqliteHashData(p); -** // do something with pData -** } -*/ -#define sqliteHashFirst(H) ((H)->first) -#define sqliteHashNext(E) ((E)->next) -#define sqliteHashData(E) ((E)->data) -/* #define sqliteHashKey(E) ((E)->pKey) // NOT USED */ -/* #define sqliteHashKeysize(E) ((E)->nKey) // NOT USED */ - -/* -** Number of entries in a hash table -*/ -/* #define sqliteHashCount(H) ((H)->count) // NOT USED */ - -#endif /* _SQLITE_HASH_H_ */ - -/************** End of hash.h ************************************************/ -/************** Continuing where we left off in sqliteInt.h ******************/ -/************** Include parse.h in the middle of sqliteInt.h *****************/ -/************** Begin file parse.h *******************************************/ -#define TK_SEMI 1 -#define TK_EXPLAIN 2 -#define TK_QUERY 3 -#define TK_PLAN 4 -#define TK_BEGIN 5 -#define TK_TRANSACTION 6 -#define TK_DEFERRED 7 -#define TK_IMMEDIATE 8 -#define TK_EXCLUSIVE 9 -#define TK_COMMIT 10 -#define TK_END 11 -#define TK_ROLLBACK 12 -#define TK_SAVEPOINT 13 -#define TK_RELEASE 14 -#define TK_TO 15 -#define TK_TABLE 16 -#define TK_CREATE 17 -#define TK_IF 18 -#define TK_NOT 19 -#define TK_EXISTS 20 -#define TK_TEMP 21 -#define TK_LP 22 -#define TK_RP 23 -#define TK_AS 24 -#define TK_COMMA 25 -#define TK_ID 26 -#define TK_INDEXED 27 -#define TK_ABORT 28 -#define TK_ACTION 29 -#define TK_AFTER 30 -#define TK_ANALYZE 31 -#define TK_ASC 32 -#define TK_ATTACH 33 -#define TK_BEFORE 34 -#define TK_BY 35 -#define TK_CASCADE 36 -#define TK_CAST 37 -#define TK_COLUMNKW 38 -#define TK_CONFLICT 39 -#define TK_DATABASE 40 -#define TK_DESC 41 -#define TK_DETACH 42 -#define TK_EACH 43 -#define TK_FAIL 44 -#define TK_FOR 45 -#define TK_IGNORE 46 -#define TK_INITIALLY 47 -#define TK_INSTEAD 48 -#define TK_LIKE_KW 49 -#define TK_MATCH 50 -#define TK_NO 51 -#define TK_KEY 52 -#define TK_OF 53 -#define TK_OFFSET 54 -#define TK_PRAGMA 55 -#define TK_RAISE 56 -#define TK_REPLACE 57 -#define TK_RESTRICT 58 -#define TK_ROW 59 -#define TK_TRIGGER 60 -#define TK_VACUUM 61 -#define TK_VIEW 62 -#define TK_VIRTUAL 63 -#define TK_REINDEX 64 -#define TK_RENAME 65 -#define TK_CTIME_KW 66 -#define TK_ANY 67 -#define TK_OR 68 -#define TK_AND 69 -#define TK_IS 70 -#define TK_BETWEEN 71 -#define TK_IN 72 -#define TK_ISNULL 73 -#define TK_NOTNULL 74 -#define TK_NE 75 -#define TK_EQ 76 -#define TK_GT 77 -#define TK_LE 78 -#define TK_LT 79 -#define TK_GE 80 -#define TK_ESCAPE 81 -#define TK_BITAND 82 -#define TK_BITOR 83 -#define TK_LSHIFT 84 -#define TK_RSHIFT 85 -#define TK_PLUS 86 -#define TK_MINUS 87 -#define TK_STAR 88 -#define TK_SLASH 89 -#define TK_REM 90 -#define TK_CONCAT 91 -#define TK_COLLATE 92 -#define TK_BITNOT 93 -#define TK_STRING 94 -#define TK_JOIN_KW 95 -#define TK_CONSTRAINT 96 -#define TK_DEFAULT 97 -#define TK_NULL 98 -#define TK_PRIMARY 99 -#define TK_UNIQUE 100 -#define TK_CHECK 101 -#define TK_REFERENCES 102 -#define TK_AUTOINCR 103 -#define TK_ON 104 -#define TK_INSERT 105 -#define TK_DELETE 106 -#define TK_UPDATE 107 -#define TK_SET 108 -#define TK_DEFERRABLE 109 -#define TK_FOREIGN 110 -#define TK_DROP 111 -#define TK_UNION 112 -#define TK_ALL 113 -#define TK_EXCEPT 114 -#define TK_INTERSECT 115 -#define TK_SELECT 116 -#define TK_DISTINCT 117 -#define TK_DOT 118 -#define TK_FROM 119 -#define TK_JOIN 120 -#define TK_USING 121 -#define TK_ORDER 122 -#define TK_GROUP 123 -#define TK_HAVING 124 -#define TK_LIMIT 125 -#define TK_WHERE 126 -#define TK_INTO 127 -#define TK_VALUES 128 -#define TK_INTEGER 129 -#define TK_FLOAT 130 -#define TK_BLOB 131 -#define TK_REGISTER 132 -#define TK_VARIABLE 133 -#define TK_CASE 134 -#define TK_WHEN 135 -#define TK_THEN 136 -#define TK_ELSE 137 -#define TK_INDEX 138 -#define TK_ALTER 139 -#define TK_ADD 140 -#define TK_TO_TEXT 141 -#define TK_TO_BLOB 142 -#define TK_TO_NUMERIC 143 -#define TK_TO_INT 144 -#define TK_TO_REAL 145 -#define TK_ISNOT 146 -#define TK_END_OF_FILE 147 -#define TK_ILLEGAL 148 -#define TK_SPACE 149 -#define TK_UNCLOSED_STRING 150 -#define TK_FUNCTION 151 -#define TK_COLUMN 152 -#define TK_AGG_FUNCTION 153 -#define TK_AGG_COLUMN 154 -#define TK_CONST_FUNC 155 -#define TK_UMINUS 156 -#define TK_UPLUS 157 - -/************** End of parse.h ***********************************************/ -/************** Continuing where we left off in sqliteInt.h ******************/ -#include -#include -#include -#include -#include - -/* -** If compiling for a processor that lacks floating point support, -** substitute integer for floating-point -*/ -#ifdef SQLITE_OMIT_FLOATING_POINT -# define double sqlite_int64 -# define float sqlite_int64 -# define LONGDOUBLE_TYPE sqlite_int64 -# ifndef SQLITE_BIG_DBL -# define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50) -# endif -# define SQLITE_OMIT_DATETIME_FUNCS 1 -# define SQLITE_OMIT_TRACE 1 -# undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT -# undef SQLITE_HAVE_ISNAN -#endif -#ifndef SQLITE_BIG_DBL -# define SQLITE_BIG_DBL (1e99) -#endif - -/* -** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0 -** afterward. Having this macro allows us to cause the C compiler -** to omit code used by TEMP tables without messy #ifndef statements. -*/ -#ifdef SQLITE_OMIT_TEMPDB -#define OMIT_TEMPDB 1 -#else -#define OMIT_TEMPDB 0 -#endif - -/* -** The "file format" number is an integer that is incremented whenever -** the VDBE-level file format changes. The following macros define the -** the default file format for new databases and the maximum file format -** that the library can read. -*/ -#define SQLITE_MAX_FILE_FORMAT 4 -#ifndef SQLITE_DEFAULT_FILE_FORMAT -# define SQLITE_DEFAULT_FILE_FORMAT 4 -#endif - -/* -** Determine whether triggers are recursive by default. This can be -** changed at run-time using a pragma. -*/ -#ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS -# define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0 -#endif - -/* -** Provide a default value for SQLITE_TEMP_STORE in case it is not specified -** on the command-line -*/ -#ifndef SQLITE_TEMP_STORE -# define SQLITE_TEMP_STORE 1 -#endif - -/* -** GCC does not define the offsetof() macro so we'll have to do it -** ourselves. -*/ -#ifndef offsetof -#define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD)) -#endif - -/* -** Check to see if this machine uses EBCDIC. (Yes, believe it or -** not, there are still machines out there that use EBCDIC.) -*/ -#if 'A' == '\301' -# define SQLITE_EBCDIC 1 -#else -# define SQLITE_ASCII 1 -#endif - -/* -** Integers of known sizes. These typedefs might change for architectures -** where the sizes very. Preprocessor macros are available so that the -** types can be conveniently redefined at compile-type. Like this: -** -** cc '-DUINTPTR_TYPE=long long int' ... -*/ -#ifndef UINT32_TYPE -# ifdef HAVE_UINT32_T -# define UINT32_TYPE uint32_t -# else -# define UINT32_TYPE unsigned int -# endif -#endif -#ifndef UINT16_TYPE -# ifdef HAVE_UINT16_T -# define UINT16_TYPE uint16_t -# else -# define UINT16_TYPE unsigned short int -# endif -#endif -#ifndef INT16_TYPE -# ifdef HAVE_INT16_T -# define INT16_TYPE int16_t -# else -# define INT16_TYPE short int -# endif -#endif -#ifndef UINT8_TYPE -# ifdef HAVE_UINT8_T -# define UINT8_TYPE uint8_t -# else -# define UINT8_TYPE unsigned char -# endif -#endif -#ifndef INT8_TYPE -# ifdef HAVE_INT8_T -# define INT8_TYPE int8_t -# else -# define INT8_TYPE signed char -# endif -#endif -#ifndef LONGDOUBLE_TYPE -# define LONGDOUBLE_TYPE long double -#endif -typedef sqlite_int64 i64; /* 8-byte signed integer */ -typedef sqlite_uint64 u64; /* 8-byte unsigned integer */ -typedef UINT32_TYPE u32; /* 4-byte unsigned integer */ -typedef UINT16_TYPE u16; /* 2-byte unsigned integer */ -typedef INT16_TYPE i16; /* 2-byte signed integer */ -typedef UINT8_TYPE u8; /* 1-byte unsigned integer */ -typedef INT8_TYPE i8; /* 1-byte signed integer */ - -/* -** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value -** that can be stored in a u32 without loss of data. The value -** is 0x00000000ffffffff. But because of quirks of some compilers, we -** have to specify the value in the less intuitive manner shown: -*/ -#define SQLITE_MAX_U32 ((((u64)1)<<32)-1) - -/* -** The datatype used to store estimates of the number of rows in a -** table or index. This is an unsigned integer type. For 99.9% of -** the world, a 32-bit integer is sufficient. But a 64-bit integer -** can be used at compile-time if desired. -*/ -#ifdef SQLITE_64BIT_STATS - typedef u64 tRowcnt; /* 64-bit only if requested at compile-time */ -#else - typedef u32 tRowcnt; /* 32-bit is the default */ -#endif - -/* -** Macros to determine whether the machine is big or little endian, -** evaluated at runtime. -*/ -#ifdef SQLITE_AMALGAMATION -SQLITE_PRIVATE const int sqlite3one = 1; -#else -SQLITE_PRIVATE const int sqlite3one; -#endif -#if defined(i386) || defined(__i386__) || defined(_M_IX86)\ - || defined(__x86_64) || defined(__x86_64__) -# define SQLITE_BIGENDIAN 0 -# define SQLITE_LITTLEENDIAN 1 -# define SQLITE_UTF16NATIVE SQLITE_UTF16LE -#else -# define SQLITE_BIGENDIAN (*(char *)(&sqlite3one)==0) -# define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1) -# define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE) -#endif - -/* -** Constants for the largest and smallest possible 64-bit signed integers. -** These macros are designed to work correctly on both 32-bit and 64-bit -** compilers. -*/ -#define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32)) -#define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64) - -/* -** Round up a number to the next larger multiple of 8. This is used -** to force 8-byte alignment on 64-bit architectures. -*/ -#define ROUND8(x) (((x)+7)&~7) - -/* -** Round down to the nearest multiple of 8 -*/ -#define ROUNDDOWN8(x) ((x)&~7) - -/* -** Assert that the pointer X is aligned to an 8-byte boundary. This -** macro is used only within assert() to verify that the code gets -** all alignment restrictions correct. -** -** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the -** underlying malloc() implemention might return us 4-byte aligned -** pointers. In that case, only verify 4-byte alignment. -*/ -#ifdef SQLITE_4_BYTE_ALIGNED_MALLOC -# define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&3)==0) -#else -# define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&7)==0) -#endif - - -/* -** An instance of the following structure is used to store the busy-handler -** callback for a given sqlite handle. -** -** The sqlite.busyHandler member of the sqlite struct contains the busy -** callback for the database handle. Each pager opened via the sqlite -** handle is passed a pointer to sqlite.busyHandler. The busy-handler -** callback is currently invoked only from within pager.c. -*/ -typedef struct BusyHandler BusyHandler; -struct BusyHandler { - int (*xFunc)(void *,int); /* The busy callback */ - void *pArg; /* First arg to busy callback */ - int nBusy; /* Incremented with each busy call */ -}; - -/* -** Name of the master database table. The master database table -** is a special table that holds the names and attributes of all -** user tables and indices. -*/ -#define MASTER_NAME "sqlite_master" -#define TEMP_MASTER_NAME "sqlite_temp_master" - -/* -** The root-page of the master database table. -*/ -#define MASTER_ROOT 1 - -/* -** The name of the schema table. -*/ -#define SCHEMA_TABLE(x) ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME) - -/* -** A convenience macro that returns the number of elements in -** an array. -*/ -#define ArraySize(X) ((int)(sizeof(X)/sizeof(X[0]))) - -/* -** Determine if the argument is a power of two -*/ -#define IsPowerOfTwo(X) (((X)&((X)-1))==0) - -/* -** The following value as a destructor means to use sqlite3DbFree(). -** The sqlite3DbFree() routine requires two parameters instead of the -** one parameter that destructors normally want. So we have to introduce -** this magic value that the code knows to handle differently. Any -** pointer will work here as long as it is distinct from SQLITE_STATIC -** and SQLITE_TRANSIENT. -*/ -#define SQLITE_DYNAMIC ((sqlite3_destructor_type)sqlite3MallocSize) - -/* -** When SQLITE_OMIT_WSD is defined, it means that the target platform does -** not support Writable Static Data (WSD) such as global and static variables. -** All variables must either be on the stack or dynamically allocated from -** the heap. When WSD is unsupported, the variable declarations scattered -** throughout the SQLite code must become constants instead. The SQLITE_WSD -** macro is used for this purpose. And instead of referencing the variable -** directly, we use its constant as a key to lookup the run-time allocated -** buffer that holds real variable. The constant is also the initializer -** for the run-time allocated buffer. -** -** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL -** macros become no-ops and have zero performance impact. -*/ -#ifdef SQLITE_OMIT_WSD - #define SQLITE_WSD const - #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v))) - #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config) -SQLITE_API int sqlite3_wsd_init(int N, int J); -SQLITE_API void *sqlite3_wsd_find(void *K, int L); -#else - #define SQLITE_WSD - #define GLOBAL(t,v) v - #define sqlite3GlobalConfig sqlite3Config -#endif - -/* -** The following macros are used to suppress compiler warnings and to -** make it clear to human readers when a function parameter is deliberately -** left unused within the body of a function. This usually happens when -** a function is called via a function pointer. For example the -** implementation of an SQL aggregate step callback may not use the -** parameter indicating the number of arguments passed to the aggregate, -** if it knows that this is enforced elsewhere. -** -** When a function parameter is not used at all within the body of a function, -** it is generally named "NotUsed" or "NotUsed2" to make things even clearer. -** However, these macros may also be used to suppress warnings related to -** parameters that may or may not be used depending on compilation options. -** For example those parameters only used in assert() statements. In these -** cases the parameters are named as per the usual conventions. -*/ -#define UNUSED_PARAMETER(x) (void)(x) -#define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y) - -/* -** Forward references to structures -*/ -typedef struct AggInfo AggInfo; -typedef struct AuthContext AuthContext; -typedef struct AutoincInfo AutoincInfo; -typedef struct Bitvec Bitvec; -typedef struct CollSeq CollSeq; -typedef struct Column Column; -typedef struct Db Db; -typedef struct Schema Schema; -typedef struct Expr Expr; -typedef struct ExprList ExprList; -typedef struct ExprSpan ExprSpan; -typedef struct FKey FKey; -typedef struct FuncDestructor FuncDestructor; -typedef struct FuncDef FuncDef; -typedef struct FuncDefHash FuncDefHash; -typedef struct IdList IdList; -typedef struct Index Index; -typedef struct IndexSample IndexSample; -typedef struct KeyClass KeyClass; -typedef struct KeyInfo KeyInfo; -typedef struct Lookaside Lookaside; -typedef struct LookasideSlot LookasideSlot; -typedef struct Module Module; -typedef struct NameContext NameContext; -typedef struct Parse Parse; -typedef struct RowSet RowSet; -typedef struct Savepoint Savepoint; -typedef struct Select Select; -typedef struct SelectDest SelectDest; -typedef struct SrcList SrcList; -typedef struct StrAccum StrAccum; -typedef struct Table Table; -typedef struct TableLock TableLock; -typedef struct Token Token; -typedef struct Trigger Trigger; -typedef struct TriggerPrg TriggerPrg; -typedef struct TriggerStep TriggerStep; -typedef struct UnpackedRecord UnpackedRecord; -typedef struct VTable VTable; -typedef struct VtabCtx VtabCtx; -typedef struct Walker Walker; -typedef struct WherePlan WherePlan; -typedef struct WhereInfo WhereInfo; -typedef struct WhereLevel WhereLevel; - -/* -** Defer sourcing vdbe.h and btree.h until after the "u8" and -** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque -** pointer types (i.e. FuncDef) defined above. -*/ -/************** Include btree.h in the middle of sqliteInt.h *****************/ -/************** Begin file btree.h *******************************************/ -/* -** 2001 September 15 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** This header file defines the interface that the sqlite B-Tree file -** subsystem. See comments in the source code for a detailed description -** of what each interface routine does. -*/ -#ifndef _BTREE_H_ -#define _BTREE_H_ - -/* TODO: This definition is just included so other modules compile. It -** needs to be revisited. -*/ -#define SQLITE_N_BTREE_META 10 - -/* -** If defined as non-zero, auto-vacuum is enabled by default. Otherwise -** it must be turned on for each database using "PRAGMA auto_vacuum = 1". -*/ -#ifndef SQLITE_DEFAULT_AUTOVACUUM - #define SQLITE_DEFAULT_AUTOVACUUM 0 -#endif - -#define BTREE_AUTOVACUUM_NONE 0 /* Do not do auto-vacuum */ -#define BTREE_AUTOVACUUM_FULL 1 /* Do full auto-vacuum */ -#define BTREE_AUTOVACUUM_INCR 2 /* Incremental vacuum */ - -/* -** Forward declarations of structure -*/ -typedef struct Btree Btree; -typedef struct BtCursor BtCursor; -typedef struct BtShared BtShared; - - -SQLITE_PRIVATE int sqlite3BtreeOpen( - sqlite3_vfs *pVfs, /* VFS to use with this b-tree */ - const char *zFilename, /* Name of database file to open */ - sqlite3 *db, /* Associated database connection */ - Btree **ppBtree, /* Return open Btree* here */ - int flags, /* Flags */ - int vfsFlags /* Flags passed through to VFS open */ -); - -/* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the -** following values. -** -** NOTE: These values must match the corresponding PAGER_ values in -** pager.h. -*/ -#define BTREE_OMIT_JOURNAL 1 /* Do not create or use a rollback journal */ -#define BTREE_MEMORY 2 /* This is an in-memory DB */ -#define BTREE_SINGLE 4 /* The file contains at most 1 b-tree */ -#define BTREE_UNORDERED 8 /* Use of a hash implementation is OK */ - -SQLITE_PRIVATE int sqlite3BtreeClose(Btree*); -SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int); -SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree*,int,int,int); -SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*); -SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix); -SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*); -SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int); -SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*); -SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int); -SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*); -#if defined(SQLITE_HAS_CODEC) || defined(SQLITE_DEBUG) -SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p); -#endif -SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int); -SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *); -SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int); -SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster); -SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int); -SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*); -SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*,int); -SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int); -SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags); -SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*); -SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*); -SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*); -SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *)); -SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree); -SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock); -SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int); - -SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *); -SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *); -SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *); - -SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *); - -/* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR -** of the flags shown below. -** -** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set. -** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data -** is stored in the leaves. (BTREE_INTKEY is used for SQL tables.) With -** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored -** anywhere - the key is the content. (BTREE_BLOBKEY is used for SQL -** indices.) -*/ -#define BTREE_INTKEY 1 /* Table has only 64-bit signed integer keys */ -#define BTREE_BLOBKEY 2 /* Table has keys only - no data */ - -SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*); -SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*); -SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree*, int); - -SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue); -SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value); - -SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p); - -/* -** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta -** should be one of the following values. The integer values are assigned -** to constants so that the offset of the corresponding field in an -** SQLite database header may be found using the following formula: -** -** offset = 36 + (idx * 4) -** -** For example, the free-page-count field is located at byte offset 36 of -** the database file header. The incr-vacuum-flag field is located at -** byte offset 64 (== 36+4*7). -*/ -#define BTREE_FREE_PAGE_COUNT 0 -#define BTREE_SCHEMA_VERSION 1 -#define BTREE_FILE_FORMAT 2 -#define BTREE_DEFAULT_CACHE_SIZE 3 -#define BTREE_LARGEST_ROOT_PAGE 4 -#define BTREE_TEXT_ENCODING 5 -#define BTREE_USER_VERSION 6 -#define BTREE_INCR_VACUUM 7 - -/* -** Values that may be OR'd together to form the second argument of an -** sqlite3BtreeCursorHints() call. -*/ -#define BTREE_BULKLOAD 0x00000001 - -SQLITE_PRIVATE int sqlite3BtreeCursor( - Btree*, /* BTree containing table to open */ - int iTable, /* Index of root page */ - int wrFlag, /* 1 for writing. 0 for read-only */ - struct KeyInfo*, /* First argument to compare function */ - BtCursor *pCursor /* Space to write cursor structure */ -); -SQLITE_PRIVATE int sqlite3BtreeCursorSize(void); -SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*); - -SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*); -SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked( - BtCursor*, - UnpackedRecord *pUnKey, - i64 intKey, - int bias, - int *pRes -); -SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*, int*); -SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*); -SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey, - const void *pData, int nData, - int nZero, int bias, int seekResult); -SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes); -SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes); -SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes); -SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*); -SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes); -SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize); -SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*); -SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, int *pAmt); -SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, int *pAmt); -SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize); -SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*); -SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor*, sqlite3_int64); -SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor*); - -SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*); -SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*); - -SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*); -SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *); -SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *); -SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion); -SQLITE_PRIVATE void sqlite3BtreeCursorHints(BtCursor *, unsigned int mask); - -#ifndef NDEBUG -SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*); -#endif - -#ifndef SQLITE_OMIT_BTREECOUNT -SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *); -#endif - -#ifdef SQLITE_TEST -SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int); -SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*); -#endif - -#ifndef SQLITE_OMIT_WAL -SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree*, int, int *, int *); -#endif - -/* -** If we are not using shared cache, then there is no need to -** use mutexes to access the BtShared structures. So make the -** Enter and Leave procedures no-ops. -*/ -#ifndef SQLITE_OMIT_SHARED_CACHE -SQLITE_PRIVATE void sqlite3BtreeEnter(Btree*); -SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3*); -#else -# define sqlite3BtreeEnter(X) -# define sqlite3BtreeEnterAll(X) -#endif - -#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE -SQLITE_PRIVATE int sqlite3BtreeSharable(Btree*); -SQLITE_PRIVATE void sqlite3BtreeLeave(Btree*); -SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor*); -SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor*); -SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3*); -#ifndef NDEBUG - /* These routines are used inside assert() statements only. */ -SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree*); -SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3*); -SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*); -#endif -#else - -# define sqlite3BtreeSharable(X) 0 -# define sqlite3BtreeLeave(X) -# define sqlite3BtreeEnterCursor(X) -# define sqlite3BtreeLeaveCursor(X) -# define sqlite3BtreeLeaveAll(X) - -# define sqlite3BtreeHoldsMutex(X) 1 -# define sqlite3BtreeHoldsAllMutexes(X) 1 -# define sqlite3SchemaMutexHeld(X,Y,Z) 1 -#endif - - -#endif /* _BTREE_H_ */ - -/************** End of btree.h ***********************************************/ -/************** Continuing where we left off in sqliteInt.h ******************/ -/************** Include vdbe.h in the middle of sqliteInt.h ******************/ -/************** Begin file vdbe.h ********************************************/ -/* -** 2001 September 15 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** Header file for the Virtual DataBase Engine (VDBE) -** -** This header defines the interface to the virtual database engine -** or VDBE. The VDBE implements an abstract machine that runs a -** simple program to access and modify the underlying database. -*/ -#ifndef _SQLITE_VDBE_H_ -#define _SQLITE_VDBE_H_ -/* #include */ - -/* -** A single VDBE is an opaque structure named "Vdbe". Only routines -** in the source file sqliteVdbe.c are allowed to see the insides -** of this structure. -*/ -typedef struct Vdbe Vdbe; - -/* -** The names of the following types declared in vdbeInt.h are required -** for the VdbeOp definition. -*/ -typedef struct VdbeFunc VdbeFunc; -typedef struct Mem Mem; -typedef struct SubProgram SubProgram; - -/* -** A single instruction of the virtual machine has an opcode -** and as many as three operands. The instruction is recorded -** as an instance of the following structure: -*/ -struct VdbeOp { - u8 opcode; /* What operation to perform */ - signed char p4type; /* One of the P4_xxx constants for p4 */ - u8 opflags; /* Mask of the OPFLG_* flags in opcodes.h */ - u8 p5; /* Fifth parameter is an unsigned character */ - int p1; /* First operand */ - int p2; /* Second parameter (often the jump destination) */ - int p3; /* The third parameter */ - union { /* fourth parameter */ - int i; /* Integer value if p4type==P4_INT32 */ - void *p; /* Generic pointer */ - char *z; /* Pointer to data for string (char array) types */ - i64 *pI64; /* Used when p4type is P4_INT64 */ - double *pReal; /* Used when p4type is P4_REAL */ - FuncDef *pFunc; /* Used when p4type is P4_FUNCDEF */ - VdbeFunc *pVdbeFunc; /* Used when p4type is P4_VDBEFUNC */ - CollSeq *pColl; /* Used when p4type is P4_COLLSEQ */ - Mem *pMem; /* Used when p4type is P4_MEM */ - VTable *pVtab; /* Used when p4type is P4_VTAB */ - KeyInfo *pKeyInfo; /* Used when p4type is P4_KEYINFO */ - int *ai; /* Used when p4type is P4_INTARRAY */ - SubProgram *pProgram; /* Used when p4type is P4_SUBPROGRAM */ - int (*xAdvance)(BtCursor *, int *); - } p4; -#ifdef SQLITE_DEBUG - char *zComment; /* Comment to improve readability */ -#endif -#ifdef VDBE_PROFILE - int cnt; /* Number of times this instruction was executed */ - u64 cycles; /* Total time spent executing this instruction */ -#endif -}; -typedef struct VdbeOp VdbeOp; - - -/* -** A sub-routine used to implement a trigger program. -*/ -struct SubProgram { - VdbeOp *aOp; /* Array of opcodes for sub-program */ - int nOp; /* Elements in aOp[] */ - int nMem; /* Number of memory cells required */ - int nCsr; /* Number of cursors required */ - int nOnce; /* Number of OP_Once instructions */ - void *token; /* id that may be used to recursive triggers */ - SubProgram *pNext; /* Next sub-program already visited */ -}; - -/* -** A smaller version of VdbeOp used for the VdbeAddOpList() function because -** it takes up less space. -*/ -struct VdbeOpList { - u8 opcode; /* What operation to perform */ - signed char p1; /* First operand */ - signed char p2; /* Second parameter (often the jump destination) */ - signed char p3; /* Third parameter */ -}; -typedef struct VdbeOpList VdbeOpList; - -/* -** Allowed values of VdbeOp.p4type -*/ -#define P4_NOTUSED 0 /* The P4 parameter is not used */ -#define P4_DYNAMIC (-1) /* Pointer to a string obtained from sqliteMalloc() */ -#define P4_STATIC (-2) /* Pointer to a static string */ -#define P4_COLLSEQ (-4) /* P4 is a pointer to a CollSeq structure */ -#define P4_FUNCDEF (-5) /* P4 is a pointer to a FuncDef structure */ -#define P4_KEYINFO (-6) /* P4 is a pointer to a KeyInfo structure */ -#define P4_VDBEFUNC (-7) /* P4 is a pointer to a VdbeFunc structure */ -#define P4_MEM (-8) /* P4 is a pointer to a Mem* structure */ -#define P4_TRANSIENT 0 /* P4 is a pointer to a transient string */ -#define P4_VTAB (-10) /* P4 is a pointer to an sqlite3_vtab structure */ -#define P4_MPRINTF (-11) /* P4 is a string obtained from sqlite3_mprintf() */ -#define P4_REAL (-12) /* P4 is a 64-bit floating point value */ -#define P4_INT64 (-13) /* P4 is a 64-bit signed integer */ -#define P4_INT32 (-14) /* P4 is a 32-bit signed integer */ -#define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */ -#define P4_SUBPROGRAM (-18) /* P4 is a pointer to a SubProgram structure */ -#define P4_ADVANCE (-19) /* P4 is a pointer to BtreeNext() or BtreePrev() */ - -/* When adding a P4 argument using P4_KEYINFO, a copy of the KeyInfo structure -** is made. That copy is freed when the Vdbe is finalized. But if the -** argument is P4_KEYINFO_HANDOFF, the passed in pointer is used. It still -** gets freed when the Vdbe is finalized so it still should be obtained -** from a single sqliteMalloc(). But no copy is made and the calling -** function should *not* try to free the KeyInfo. -*/ -#define P4_KEYINFO_HANDOFF (-16) -#define P4_KEYINFO_STATIC (-17) - -/* -** The Vdbe.aColName array contains 5n Mem structures, where n is the -** number of columns of data returned by the statement. -*/ -#define COLNAME_NAME 0 -#define COLNAME_DECLTYPE 1 -#define COLNAME_DATABASE 2 -#define COLNAME_TABLE 3 -#define COLNAME_COLUMN 4 -#ifdef SQLITE_ENABLE_COLUMN_METADATA -# define COLNAME_N 5 /* Number of COLNAME_xxx symbols */ -#else -# ifdef SQLITE_OMIT_DECLTYPE -# define COLNAME_N 1 /* Store only the name */ -# else -# define COLNAME_N 2 /* Store the name and decltype */ -# endif -#endif - -/* -** The following macro converts a relative address in the p2 field -** of a VdbeOp structure into a negative number so that -** sqlite3VdbeAddOpList() knows that the address is relative. Calling -** the macro again restores the address. -*/ -#define ADDR(X) (-1-(X)) - -/* -** The makefile scans the vdbe.c source file and creates the "opcodes.h" -** header file that defines a number for each opcode used by the VDBE. -*/ -/************** Include opcodes.h in the middle of vdbe.h ********************/ -/************** Begin file opcodes.h *****************************************/ -/* Automatically generated. Do not edit */ -/* See the mkopcodeh.awk script for details */ -#define OP_Goto 1 -#define OP_Gosub 2 -#define OP_Return 3 -#define OP_Yield 4 -#define OP_HaltIfNull 5 -#define OP_Halt 6 -#define OP_Integer 7 -#define OP_Int64 8 -#define OP_Real 130 /* same as TK_FLOAT */ -#define OP_String8 94 /* same as TK_STRING */ -#define OP_String 9 -#define OP_Null 10 -#define OP_Blob 11 -#define OP_Variable 12 -#define OP_Move 13 -#define OP_Copy 14 -#define OP_SCopy 15 -#define OP_ResultRow 16 -#define OP_Concat 91 /* same as TK_CONCAT */ -#define OP_Add 86 /* same as TK_PLUS */ -#define OP_Subtract 87 /* same as TK_MINUS */ -#define OP_Multiply 88 /* same as TK_STAR */ -#define OP_Divide 89 /* same as TK_SLASH */ -#define OP_Remainder 90 /* same as TK_REM */ -#define OP_CollSeq 17 -#define OP_Function 18 -#define OP_BitAnd 82 /* same as TK_BITAND */ -#define OP_BitOr 83 /* same as TK_BITOR */ -#define OP_ShiftLeft 84 /* same as TK_LSHIFT */ -#define OP_ShiftRight 85 /* same as TK_RSHIFT */ -#define OP_AddImm 20 -#define OP_MustBeInt 21 -#define OP_RealAffinity 22 -#define OP_ToText 141 /* same as TK_TO_TEXT */ -#define OP_ToBlob 142 /* same as TK_TO_BLOB */ -#define OP_ToNumeric 143 /* same as TK_TO_NUMERIC*/ -#define OP_ToInt 144 /* same as TK_TO_INT */ -#define OP_ToReal 145 /* same as TK_TO_REAL */ -#define OP_Eq 76 /* same as TK_EQ */ -#define OP_Ne 75 /* same as TK_NE */ -#define OP_Lt 79 /* same as TK_LT */ -#define OP_Le 78 /* same as TK_LE */ -#define OP_Gt 77 /* same as TK_GT */ -#define OP_Ge 80 /* same as TK_GE */ -#define OP_Permutation 23 -#define OP_Compare 24 -#define OP_Jump 25 -#define OP_And 69 /* same as TK_AND */ -#define OP_Or 68 /* same as TK_OR */ -#define OP_Not 19 /* same as TK_NOT */ -#define OP_BitNot 93 /* same as TK_BITNOT */ -#define OP_Once 26 -#define OP_If 27 -#define OP_IfNot 28 -#define OP_IsNull 73 /* same as TK_ISNULL */ -#define OP_NotNull 74 /* same as TK_NOTNULL */ -#define OP_Column 29 -#define OP_Affinity 30 -#define OP_MakeRecord 31 -#define OP_Count 32 -#define OP_Savepoint 33 -#define OP_AutoCommit 34 -#define OP_Transaction 35 -#define OP_ReadCookie 36 -#define OP_SetCookie 37 -#define OP_VerifyCookie 38 -#define OP_OpenRead 39 -#define OP_OpenWrite 40 -#define OP_OpenAutoindex 41 -#define OP_OpenEphemeral 42 -#define OP_SorterOpen 43 -#define OP_OpenPseudo 44 -#define OP_Close 45 -#define OP_SeekLt 46 -#define OP_SeekLe 47 -#define OP_SeekGe 48 -#define OP_SeekGt 49 -#define OP_Seek 50 -#define OP_NotFound 51 -#define OP_Found 52 -#define OP_IsUnique 53 -#define OP_NotExists 54 -#define OP_Sequence 55 -#define OP_NewRowid 56 -#define OP_Insert 57 -#define OP_InsertInt 58 -#define OP_Delete 59 -#define OP_ResetCount 60 -#define OP_SorterCompare 61 -#define OP_SorterData 62 -#define OP_RowKey 63 -#define OP_RowData 64 -#define OP_Rowid 65 -#define OP_NullRow 66 -#define OP_Last 67 -#define OP_SorterSort 70 -#define OP_Sort 71 -#define OP_Rewind 72 -#define OP_SorterNext 81 -#define OP_Prev 92 -#define OP_Next 95 -#define OP_SorterInsert 96 -#define OP_IdxInsert 97 -#define OP_IdxDelete 98 -#define OP_IdxRowid 99 -#define OP_IdxLT 100 -#define OP_IdxGE 101 -#define OP_Destroy 102 -#define OP_Clear 103 -#define OP_CreateIndex 104 -#define OP_CreateTable 105 -#define OP_ParseSchema 106 -#define OP_LoadAnalysis 107 -#define OP_DropTable 108 -#define OP_DropIndex 109 -#define OP_DropTrigger 110 -#define OP_IntegrityCk 111 -#define OP_RowSetAdd 112 -#define OP_RowSetRead 113 -#define OP_RowSetTest 114 -#define OP_Program 115 -#define OP_Param 116 -#define OP_FkCounter 117 -#define OP_FkIfZero 118 -#define OP_MemMax 119 -#define OP_IfPos 120 -#define OP_IfNeg 121 -#define OP_IfZero 122 -#define OP_AggStep 123 -#define OP_AggFinal 124 -#define OP_Checkpoint 125 -#define OP_JournalMode 126 -#define OP_Vacuum 127 -#define OP_IncrVacuum 128 -#define OP_Expire 129 -#define OP_TableLock 131 -#define OP_VBegin 132 -#define OP_VCreate 133 -#define OP_VDestroy 134 -#define OP_VOpen 135 -#define OP_VFilter 136 -#define OP_VColumn 137 -#define OP_VNext 138 -#define OP_VRename 139 -#define OP_VUpdate 140 -#define OP_Pagecount 146 -#define OP_MaxPgcnt 147 -#define OP_Trace 148 -#define OP_Noop 149 -#define OP_Explain 150 - - -/* Properties such as "out2" or "jump" that are specified in -** comments following the "case" for each opcode in the vdbe.c -** are encoded into bitvectors as follows: -*/ -#define OPFLG_JUMP 0x0001 /* jump: P2 holds jmp target */ -#define OPFLG_OUT2_PRERELEASE 0x0002 /* out2-prerelease: */ -#define OPFLG_IN1 0x0004 /* in1: P1 is an input */ -#define OPFLG_IN2 0x0008 /* in2: P2 is an input */ -#define OPFLG_IN3 0x0010 /* in3: P3 is an input */ -#define OPFLG_OUT2 0x0020 /* out2: P2 is an output */ -#define OPFLG_OUT3 0x0040 /* out3: P3 is an output */ -#define OPFLG_INITIALIZER {\ -/* 0 */ 0x00, 0x01, 0x01, 0x04, 0x04, 0x10, 0x00, 0x02,\ -/* 8 */ 0x02, 0x02, 0x02, 0x02, 0x02, 0x00, 0x00, 0x24,\ -/* 16 */ 0x00, 0x00, 0x00, 0x24, 0x04, 0x05, 0x04, 0x00,\ -/* 24 */ 0x00, 0x01, 0x01, 0x05, 0x05, 0x00, 0x00, 0x00,\ -/* 32 */ 0x02, 0x00, 0x00, 0x00, 0x02, 0x10, 0x00, 0x00,\ -/* 40 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x11,\ -/* 48 */ 0x11, 0x11, 0x08, 0x11, 0x11, 0x11, 0x11, 0x02,\ -/* 56 */ 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\ -/* 64 */ 0x00, 0x02, 0x00, 0x01, 0x4c, 0x4c, 0x01, 0x01,\ -/* 72 */ 0x01, 0x05, 0x05, 0x15, 0x15, 0x15, 0x15, 0x15,\ -/* 80 */ 0x15, 0x01, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c,\ -/* 88 */ 0x4c, 0x4c, 0x4c, 0x4c, 0x01, 0x24, 0x02, 0x01,\ -/* 96 */ 0x08, 0x08, 0x00, 0x02, 0x01, 0x01, 0x02, 0x00,\ -/* 104 */ 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\ -/* 112 */ 0x0c, 0x45, 0x15, 0x01, 0x02, 0x00, 0x01, 0x08,\ -/* 120 */ 0x05, 0x05, 0x05, 0x00, 0x00, 0x00, 0x02, 0x00,\ -/* 128 */ 0x01, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,\ -/* 136 */ 0x01, 0x00, 0x01, 0x00, 0x00, 0x04, 0x04, 0x04,\ -/* 144 */ 0x04, 0x04, 0x02, 0x02, 0x00, 0x00, 0x00,} - -/************** End of opcodes.h *********************************************/ -/************** Continuing where we left off in vdbe.h ***********************/ - -/* -** Prototypes for the VDBE interface. See comments on the implementation -** for a description of what each of these routines does. -*/ -SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3*); -SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int); -SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int); -SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int); -SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int); -SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int); -SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int); -SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp); -SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*); -SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, u32 addr, int P1); -SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, u32 addr, int P2); -SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, u32 addr, int P3); -SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5); -SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr); -SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr); -SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N); -SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int); -SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int); -SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*); -SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*); -SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*); -SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3*,Vdbe*); -SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,Parse*); -SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*); -SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int); -SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*); -#ifdef SQLITE_DEBUG -SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *, int); -SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe*,FILE*); -#endif -SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*); -SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe*); -SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*); -SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int); -SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*)); -SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*); -SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*); -SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int); -SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*); -SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*); -SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe*, int, u8); -SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int); -#ifndef SQLITE_OMIT_TRACE -SQLITE_PRIVATE char *sqlite3VdbeExpandSql(Vdbe*, const char*); -#endif - -SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*); -SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*); -SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo *, char *, int, char **); - -#ifndef SQLITE_OMIT_TRIGGER -SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *); -#endif - - -#ifndef NDEBUG -SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe*, const char*, ...); -# define VdbeComment(X) sqlite3VdbeComment X -SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe*, const char*, ...); -# define VdbeNoopComment(X) sqlite3VdbeNoopComment X -#else -# define VdbeComment(X) -# define VdbeNoopComment(X) -#endif - -#endif - -/************** End of vdbe.h ************************************************/ -/************** Continuing where we left off in sqliteInt.h ******************/ -/************** Include pager.h in the middle of sqliteInt.h *****************/ -/************** Begin file pager.h *******************************************/ -/* -** 2001 September 15 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** This header file defines the interface that the sqlite page cache -** subsystem. The page cache subsystem reads and writes a file a page -** at a time and provides a journal for rollback. -*/ - -#ifndef _PAGER_H_ -#define _PAGER_H_ - -/* -** Default maximum size for persistent journal files. A negative -** value means no limit. This value may be overridden using the -** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit". -*/ -#ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT - #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1 -#endif - -/* -** The type used to represent a page number. The first page in a file -** is called page 1. 0 is used to represent "not a page". -*/ -typedef u32 Pgno; - -/* -** Each open file is managed by a separate instance of the "Pager" structure. -*/ -typedef struct Pager Pager; - -/* -** Handle type for pages. -*/ -typedef struct PgHdr DbPage; - -/* -** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is -** reserved for working around a windows/posix incompatibility). It is -** used in the journal to signify that the remainder of the journal file -** is devoted to storing a master journal name - there are no more pages to -** roll back. See comments for function writeMasterJournal() in pager.c -** for details. -*/ -#define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1)) - -/* -** Allowed values for the flags parameter to sqlite3PagerOpen(). -** -** NOTE: These values must match the corresponding BTREE_ values in btree.h. -*/ -#define PAGER_OMIT_JOURNAL 0x0001 /* Do not use a rollback journal */ -#define PAGER_MEMORY 0x0002 /* In-memory database */ - -/* -** Valid values for the second argument to sqlite3PagerLockingMode(). -*/ -#define PAGER_LOCKINGMODE_QUERY -1 -#define PAGER_LOCKINGMODE_NORMAL 0 -#define PAGER_LOCKINGMODE_EXCLUSIVE 1 - -/* -** Numeric constants that encode the journalmode. -*/ -#define PAGER_JOURNALMODE_QUERY (-1) /* Query the value of journalmode */ -#define PAGER_JOURNALMODE_DELETE 0 /* Commit by deleting journal file */ -#define PAGER_JOURNALMODE_PERSIST 1 /* Commit by zeroing journal header */ -#define PAGER_JOURNALMODE_OFF 2 /* Journal omitted. */ -#define PAGER_JOURNALMODE_TRUNCATE 3 /* Commit by truncating journal */ -#define PAGER_JOURNALMODE_MEMORY 4 /* In-memory journal file */ -#define PAGER_JOURNALMODE_WAL 5 /* Use write-ahead logging */ - -/* -** The remainder of this file contains the declarations of the functions -** that make up the Pager sub-system API. See source code comments for -** a detailed description of each routine. -*/ - -/* Open and close a Pager connection. */ -SQLITE_PRIVATE int sqlite3PagerOpen( - sqlite3_vfs*, - Pager **ppPager, - const char*, - int, - int, - int, - void(*)(DbPage*) -); -SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager); -SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*); - -/* Functions used to configure a Pager object. */ -SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *); -SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int); -SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int); -SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int); -SQLITE_PRIVATE void sqlite3PagerShrink(Pager*); -SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager*,int,int,int); -SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int); -SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int); -SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*); -SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*); -SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64); -SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*); - -/* Functions used to obtain and release page references. */ -SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag); -#define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0) -SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno); -SQLITE_PRIVATE void sqlite3PagerRef(DbPage*); -SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*); - -/* Operations on page references. */ -SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*); -SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*); -SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int); -SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*); -SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *); -SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *); - -/* Functions used to manage pager transactions and savepoints. */ -SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*); -SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int); -SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int); -SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*); -SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager); -SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*); -SQLITE_PRIVATE int sqlite3PagerRollback(Pager*); -SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n); -SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint); -SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager); - -#ifndef SQLITE_OMIT_WAL -SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int, int*, int*); -SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager); -SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager); -SQLITE_PRIVATE int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen); -SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager); -#endif - -#ifdef SQLITE_ENABLE_ZIPVFS -SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager); -#endif - -/* Functions used to query pager state and configuration. */ -SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*); -SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*); -SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*); -SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*, int); -SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*); -SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*); -SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*); -SQLITE_PRIVATE int sqlite3PagerNosync(Pager*); -SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*); -SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*); -SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *); -SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *); -SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *); - -/* Functions used to truncate the database file. */ -SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno); - -#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL) -SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *); -#endif - -/* Functions to support testing and debugging. */ -#if !defined(NDEBUG) || defined(SQLITE_TEST) -SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage*); -SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage*); -#endif -#ifdef SQLITE_TEST -SQLITE_PRIVATE int *sqlite3PagerStats(Pager*); -SQLITE_PRIVATE void sqlite3PagerRefdump(Pager*); - void disable_simulated_io_errors(void); - void enable_simulated_io_errors(void); -#else -# define disable_simulated_io_errors() -# define enable_simulated_io_errors() -#endif - -#endif /* _PAGER_H_ */ - -/************** End of pager.h ***********************************************/ -/************** Continuing where we left off in sqliteInt.h ******************/ -/************** Include pcache.h in the middle of sqliteInt.h ****************/ -/************** Begin file pcache.h ******************************************/ -/* -** 2008 August 05 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** This header file defines the interface that the sqlite page cache -** subsystem. -*/ - -#ifndef _PCACHE_H_ - -typedef struct PgHdr PgHdr; -typedef struct PCache PCache; - -/* -** Every page in the cache is controlled by an instance of the following -** structure. -*/ -struct PgHdr { - sqlite3_pcache_page *pPage; /* Pcache object page handle */ - void *pData; /* Page data */ - void *pExtra; /* Extra content */ - PgHdr *pDirty; /* Transient list of dirty pages */ - Pager *pPager; /* The pager this page is part of */ - Pgno pgno; /* Page number for this page */ -#ifdef SQLITE_CHECK_PAGES - u32 pageHash; /* Hash of page content */ -#endif - u16 flags; /* PGHDR flags defined below */ - - /********************************************************************** - ** Elements above are public. All that follows is private to pcache.c - ** and should not be accessed by other modules. - */ - i16 nRef; /* Number of users of this page */ - PCache *pCache; /* Cache that owns this page */ - - PgHdr *pDirtyNext; /* Next element in list of dirty pages */ - PgHdr *pDirtyPrev; /* Previous element in list of dirty pages */ -}; - -/* Bit values for PgHdr.flags */ -#define PGHDR_DIRTY 0x002 /* Page has changed */ -#define PGHDR_NEED_SYNC 0x004 /* Fsync the rollback journal before - ** writing this page to the database */ -#define PGHDR_NEED_READ 0x008 /* Content is unread */ -#define PGHDR_REUSE_UNLIKELY 0x010 /* A hint that reuse is unlikely */ -#define PGHDR_DONT_WRITE 0x020 /* Do not write content to disk */ - -/* Initialize and shutdown the page cache subsystem */ -SQLITE_PRIVATE int sqlite3PcacheInitialize(void); -SQLITE_PRIVATE void sqlite3PcacheShutdown(void); - -/* Page cache buffer management: -** These routines implement SQLITE_CONFIG_PAGECACHE. -*/ -SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n); - -/* Create a new pager cache. -** Under memory stress, invoke xStress to try to make pages clean. -** Only clean and unpinned pages can be reclaimed. -*/ -SQLITE_PRIVATE void sqlite3PcacheOpen( - int szPage, /* Size of every page */ - int szExtra, /* Extra space associated with each page */ - int bPurgeable, /* True if pages are on backing store */ - int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */ - void *pStress, /* Argument to xStress */ - PCache *pToInit /* Preallocated space for the PCache */ -); - -/* Modify the page-size after the cache has been created. */ -SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *, int); - -/* Return the size in bytes of a PCache object. Used to preallocate -** storage space. -*/ -SQLITE_PRIVATE int sqlite3PcacheSize(void); - -/* One release per successful fetch. Page is pinned until released. -** Reference counted. -*/ -SQLITE_PRIVATE int sqlite3PcacheFetch(PCache*, Pgno, int createFlag, PgHdr**); -SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*); - -SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*); /* Remove page from cache */ -SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*); /* Make sure page is marked dirty */ -SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*); /* Mark a single page as clean */ -SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*); /* Mark all dirty list pages as clean */ - -/* Change a page number. Used by incr-vacuum. */ -SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno); - -/* Remove all pages with pgno>x. Reset the cache if x==0 */ -SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x); - -/* Get a list of all dirty pages in the cache, sorted by page number */ -SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*); - -/* Reset and close the cache object */ -SQLITE_PRIVATE void sqlite3PcacheClose(PCache*); - -/* Clear flags from pages of the page cache */ -SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *); - -/* Discard the contents of the cache */ -SQLITE_PRIVATE void sqlite3PcacheClear(PCache*); - -/* Return the total number of outstanding page references */ -SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*); - -/* Increment the reference count of an existing page */ -SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*); - -SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*); - -/* Return the total number of pages stored in the cache */ -SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*); - -#if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG) -/* Iterate through all dirty pages currently stored in the cache. This -** interface is only available if SQLITE_CHECK_PAGES is defined when the -** library is built. -*/ -SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)); -#endif - -/* Set and get the suggested cache-size for the specified pager-cache. -** -** If no global maximum is configured, then the system attempts to limit -** the total number of pages cached by purgeable pager-caches to the sum -** of the suggested cache-sizes. -*/ -SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int); -#ifdef SQLITE_TEST -SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *); -#endif - -/* Free up as much memory as possible from the page cache */ -SQLITE_PRIVATE void sqlite3PcacheShrink(PCache*); - -#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT -/* Try to return memory used by the pcache module to the main memory heap */ -SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int); -#endif - -#ifdef SQLITE_TEST -SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*); -#endif - -SQLITE_PRIVATE void sqlite3PCacheSetDefault(void); - -#endif /* _PCACHE_H_ */ - -/************** End of pcache.h **********************************************/ -/************** Continuing where we left off in sqliteInt.h ******************/ - -/************** Include os.h in the middle of sqliteInt.h ********************/ -/************** Begin file os.h **********************************************/ -/* -** 2001 September 16 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -****************************************************************************** -** -** This header file (together with is companion C source-code file -** "os.c") attempt to abstract the underlying operating system so that -** the SQLite library will work on both POSIX and windows systems. -** -** This header file is #include-ed by sqliteInt.h and thus ends up -** being included by every source file. -*/ -#ifndef _SQLITE_OS_H_ -#define _SQLITE_OS_H_ - -/* -** Figure out if we are dealing with Unix, Windows, or some other -** operating system. After the following block of preprocess macros, -** all of SQLITE_OS_UNIX, SQLITE_OS_WIN, and SQLITE_OS_OTHER -** will defined to either 1 or 0. One of the four will be 1. The other -** three will be 0. -*/ -#if defined(SQLITE_OS_OTHER) -# if SQLITE_OS_OTHER==1 -# undef SQLITE_OS_UNIX -# define SQLITE_OS_UNIX 0 -# undef SQLITE_OS_WIN -# define SQLITE_OS_WIN 0 -# else -# undef SQLITE_OS_OTHER -# endif -#endif -#if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER) -# define SQLITE_OS_OTHER 0 -# ifndef SQLITE_OS_WIN -# if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__) -# define SQLITE_OS_WIN 1 -# define SQLITE_OS_UNIX 0 -# else -# define SQLITE_OS_WIN 0 -# define SQLITE_OS_UNIX 1 -# endif -# else -# define SQLITE_OS_UNIX 0 -# endif -#else -# ifndef SQLITE_OS_WIN -# define SQLITE_OS_WIN 0 -# endif -#endif - -#if SQLITE_OS_WIN -# include -#endif - -/* -** Determine if we are dealing with Windows NT. -** -** We ought to be able to determine if we are compiling for win98 or winNT -** using the _WIN32_WINNT macro as follows: -** -** #if defined(_WIN32_WINNT) -** # define SQLITE_OS_WINNT 1 -** #else -** # define SQLITE_OS_WINNT 0 -** #endif -** -** However, vs2005 does not set _WIN32_WINNT by default, as it ought to, -** so the above test does not work. We'll just assume that everything is -** winNT unless the programmer explicitly says otherwise by setting -** SQLITE_OS_WINNT to 0. -*/ -#if SQLITE_OS_WIN && !defined(SQLITE_OS_WINNT) -# define SQLITE_OS_WINNT 1 -#endif - -/* -** Determine if we are dealing with WindowsCE - which has a much -** reduced API. -*/ -#if defined(_WIN32_WCE) -# define SQLITE_OS_WINCE 1 -#else -# define SQLITE_OS_WINCE 0 -#endif - -/* -** Determine if we are dealing with WinRT, which provides only a subset of -** the full Win32 API. -*/ -#if !defined(SQLITE_OS_WINRT) -# define SQLITE_OS_WINRT 0 -#endif - -/* -** When compiled for WinCE or WinRT, there is no concept of the current -** directory. - */ -#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT -# define SQLITE_CURDIR 1 -#endif - -/* If the SET_FULLSYNC macro is not defined above, then make it -** a no-op -*/ -#ifndef SET_FULLSYNC -# define SET_FULLSYNC(x,y) -#endif - -/* -** The default size of a disk sector -*/ -#ifndef SQLITE_DEFAULT_SECTOR_SIZE -# define SQLITE_DEFAULT_SECTOR_SIZE 4096 -#endif - -/* -** Temporary files are named starting with this prefix followed by 16 random -** alphanumeric characters, and no file extension. They are stored in the -** OS's standard temporary file directory, and are deleted prior to exit. -** If sqlite is being embedded in another program, you may wish to change the -** prefix to reflect your program's name, so that if your program exits -** prematurely, old temporary files can be easily identified. This can be done -** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line. -** -** 2006-10-31: The default prefix used to be "sqlite_". But then -** Mcafee started using SQLite in their anti-virus product and it -** started putting files with the "sqlite" name in the c:/temp folder. -** This annoyed many windows users. Those users would then do a -** Google search for "sqlite", find the telephone numbers of the -** developers and call to wake them up at night and complain. -** For this reason, the default name prefix is changed to be "sqlite" -** spelled backwards. So the temp files are still identified, but -** anybody smart enough to figure out the code is also likely smart -** enough to know that calling the developer will not help get rid -** of the file. -*/ -#ifndef SQLITE_TEMP_FILE_PREFIX -# define SQLITE_TEMP_FILE_PREFIX "etilqs_" -#endif - -/* -** The following values may be passed as the second argument to -** sqlite3OsLock(). The various locks exhibit the following semantics: -** -** SHARED: Any number of processes may hold a SHARED lock simultaneously. -** RESERVED: A single process may hold a RESERVED lock on a file at -** any time. Other processes may hold and obtain new SHARED locks. -** PENDING: A single process may hold a PENDING lock on a file at -** any one time. Existing SHARED locks may persist, but no new -** SHARED locks may be obtained by other processes. -** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks. -** -** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a -** process that requests an EXCLUSIVE lock may actually obtain a PENDING -** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to -** sqlite3OsLock(). -*/ -#define NO_LOCK 0 -#define SHARED_LOCK 1 -#define RESERVED_LOCK 2 -#define PENDING_LOCK 3 -#define EXCLUSIVE_LOCK 4 - -/* -** File Locking Notes: (Mostly about windows but also some info for Unix) -** -** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because -** those functions are not available. So we use only LockFile() and -** UnlockFile(). -** -** LockFile() prevents not just writing but also reading by other processes. -** A SHARED_LOCK is obtained by locking a single randomly-chosen -** byte out of a specific range of bytes. The lock byte is obtained at -** random so two separate readers can probably access the file at the -** same time, unless they are unlucky and choose the same lock byte. -** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range. -** There can only be one writer. A RESERVED_LOCK is obtained by locking -** a single byte of the file that is designated as the reserved lock byte. -** A PENDING_LOCK is obtained by locking a designated byte different from -** the RESERVED_LOCK byte. -** -** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available, -** which means we can use reader/writer locks. When reader/writer locks -** are used, the lock is placed on the same range of bytes that is used -** for probabilistic locking in Win95/98/ME. Hence, the locking scheme -** will support two or more Win95 readers or two or more WinNT readers. -** But a single Win95 reader will lock out all WinNT readers and a single -** WinNT reader will lock out all other Win95 readers. -** -** The following #defines specify the range of bytes used for locking. -** SHARED_SIZE is the number of bytes available in the pool from which -** a random byte is selected for a shared lock. The pool of bytes for -** shared locks begins at SHARED_FIRST. -** -** The same locking strategy and -** byte ranges are used for Unix. This leaves open the possiblity of having -** clients on win95, winNT, and unix all talking to the same shared file -** and all locking correctly. To do so would require that samba (or whatever -** tool is being used for file sharing) implements locks correctly between -** windows and unix. I'm guessing that isn't likely to happen, but by -** using the same locking range we are at least open to the possibility. -** -** Locking in windows is manditory. For this reason, we cannot store -** actual data in the bytes used for locking. The pager never allocates -** the pages involved in locking therefore. SHARED_SIZE is selected so -** that all locks will fit on a single page even at the minimum page size. -** PENDING_BYTE defines the beginning of the locks. By default PENDING_BYTE -** is set high so that we don't have to allocate an unused page except -** for very large databases. But one should test the page skipping logic -** by setting PENDING_BYTE low and running the entire regression suite. -** -** Changing the value of PENDING_BYTE results in a subtly incompatible -** file format. Depending on how it is changed, you might not notice -** the incompatibility right away, even running a full regression test. -** The default location of PENDING_BYTE is the first byte past the -** 1GB boundary. -** -*/ -#ifdef SQLITE_OMIT_WSD -# define PENDING_BYTE (0x40000000) -#else -# define PENDING_BYTE sqlite3PendingByte -#endif -#define RESERVED_BYTE (PENDING_BYTE+1) -#define SHARED_FIRST (PENDING_BYTE+2) -#define SHARED_SIZE 510 - -/* -** Wrapper around OS specific sqlite3_os_init() function. -*/ -SQLITE_PRIVATE int sqlite3OsInit(void); - -/* -** Functions for accessing sqlite3_file methods -*/ -SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*); -SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset); -SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset); -SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size); -SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int); -SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize); -SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int); -SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int); -SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut); -SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*); -SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file*,int,void*); -#define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0 -SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id); -SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id); -SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **); -SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int); -SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id); -SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int); - - -/* -** Functions for accessing sqlite3_vfs methods -*/ -SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *); -SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int); -SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut); -SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *); -#ifndef SQLITE_OMIT_LOAD_EXTENSION -SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *); -SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *); -SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void); -SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *); -#endif /* SQLITE_OMIT_LOAD_EXTENSION */ -SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *); -SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int); -SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*); - -/* -** Convenience functions for opening and closing files using -** sqlite3_malloc() to obtain space for the file-handle structure. -*/ -SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*); -SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *); - -#endif /* _SQLITE_OS_H_ */ - -/************** End of os.h **************************************************/ -/************** Continuing where we left off in sqliteInt.h ******************/ -/************** Include mutex.h in the middle of sqliteInt.h *****************/ -/************** Begin file mutex.h *******************************************/ -/* -** 2007 August 28 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** -** This file contains the common header for all mutex implementations. -** The sqliteInt.h header #includes this file so that it is available -** to all source files. We break it out in an effort to keep the code -** better organized. -** -** NOTE: source files should *not* #include this header file directly. -** Source files should #include the sqliteInt.h file and let that file -** include this one indirectly. -*/ - - -/* -** Figure out what version of the code to use. The choices are -** -** SQLITE_MUTEX_OMIT No mutex logic. Not even stubs. The -** mutexes implemention cannot be overridden -** at start-time. -** -** SQLITE_MUTEX_NOOP For single-threaded applications. No -** mutual exclusion is provided. But this -** implementation can be overridden at -** start-time. -** -** SQLITE_MUTEX_PTHREADS For multi-threaded applications on Unix. -** -** SQLITE_MUTEX_W32 For multi-threaded applications on Win32. -*/ -#if !SQLITE_THREADSAFE -# define SQLITE_MUTEX_OMIT -#endif -#if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP) -# if SQLITE_OS_UNIX -# define SQLITE_MUTEX_PTHREADS -# elif SQLITE_OS_WIN -# define SQLITE_MUTEX_W32 -# else -# define SQLITE_MUTEX_NOOP -# endif -#endif - -#ifdef SQLITE_MUTEX_OMIT -/* -** If this is a no-op implementation, implement everything as macros. -*/ -#define sqlite3_mutex_alloc(X) ((sqlite3_mutex*)8) -#define sqlite3_mutex_free(X) -#define sqlite3_mutex_enter(X) -#define sqlite3_mutex_try(X) SQLITE_OK -#define sqlite3_mutex_leave(X) -#define sqlite3_mutex_held(X) ((void)(X),1) -#define sqlite3_mutex_notheld(X) ((void)(X),1) -#define sqlite3MutexAlloc(X) ((sqlite3_mutex*)8) -#define sqlite3MutexInit() SQLITE_OK -#define sqlite3MutexEnd() -#define MUTEX_LOGIC(X) -#else -#define MUTEX_LOGIC(X) X -#endif /* defined(SQLITE_MUTEX_OMIT) */ - -/************** End of mutex.h ***********************************************/ -/************** Continuing where we left off in sqliteInt.h ******************/ - - -/* -** Each database file to be accessed by the system is an instance -** of the following structure. There are normally two of these structures -** in the sqlite.aDb[] array. aDb[0] is the main database file and -** aDb[1] is the database file used to hold temporary tables. Additional -** databases may be attached. -*/ -struct Db { - char *zName; /* Name of this database */ - Btree *pBt; /* The B*Tree structure for this database file */ - u8 inTrans; /* 0: not writable. 1: Transaction. 2: Checkpoint */ - u8 safety_level; /* How aggressive at syncing data to disk */ - Schema *pSchema; /* Pointer to database schema (possibly shared) */ -}; - -/* -** An instance of the following structure stores a database schema. -** -** Most Schema objects are associated with a Btree. The exception is -** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing. -** In shared cache mode, a single Schema object can be shared by multiple -** Btrees that refer to the same underlying BtShared object. -** -** Schema objects are automatically deallocated when the last Btree that -** references them is destroyed. The TEMP Schema is manually freed by -** sqlite3_close(). -* -** A thread must be holding a mutex on the corresponding Btree in order -** to access Schema content. This implies that the thread must also be -** holding a mutex on the sqlite3 connection pointer that owns the Btree. -** For a TEMP Schema, only the connection mutex is required. -*/ -struct Schema { - int schema_cookie; /* Database schema version number for this file */ - int iGeneration; /* Generation counter. Incremented with each change */ - Hash tblHash; /* All tables indexed by name */ - Hash idxHash; /* All (named) indices indexed by name */ - Hash trigHash; /* All triggers indexed by name */ - Hash fkeyHash; /* All foreign keys by referenced table name */ - Table *pSeqTab; /* The sqlite_sequence table used by AUTOINCREMENT */ - u8 file_format; /* Schema format version for this file */ - u8 enc; /* Text encoding used by this database */ - u16 flags; /* Flags associated with this schema */ - int cache_size; /* Number of pages to use in the cache */ -}; - -/* -** These macros can be used to test, set, or clear bits in the -** Db.pSchema->flags field. -*/ -#define DbHasProperty(D,I,P) (((D)->aDb[I].pSchema->flags&(P))==(P)) -#define DbHasAnyProperty(D,I,P) (((D)->aDb[I].pSchema->flags&(P))!=0) -#define DbSetProperty(D,I,P) (D)->aDb[I].pSchema->flags|=(P) -#define DbClearProperty(D,I,P) (D)->aDb[I].pSchema->flags&=~(P) - -/* -** Allowed values for the DB.pSchema->flags field. -** -** The DB_SchemaLoaded flag is set after the database schema has been -** read into internal hash tables. -** -** DB_UnresetViews means that one or more views have column names that -** have been filled out. If the schema changes, these column names might -** changes and so the view will need to be reset. -*/ -#define DB_SchemaLoaded 0x0001 /* The schema has been loaded */ -#define DB_UnresetViews 0x0002 /* Some views have defined column names */ -#define DB_Empty 0x0004 /* The file is empty (length 0 bytes) */ - -/* -** The number of different kinds of things that can be limited -** using the sqlite3_limit() interface. -*/ -#define SQLITE_N_LIMIT (SQLITE_LIMIT_TRIGGER_DEPTH+1) - -/* -** Lookaside malloc is a set of fixed-size buffers that can be used -** to satisfy small transient memory allocation requests for objects -** associated with a particular database connection. The use of -** lookaside malloc provides a significant performance enhancement -** (approx 10%) by avoiding numerous malloc/free requests while parsing -** SQL statements. -** -** The Lookaside structure holds configuration information about the -** lookaside malloc subsystem. Each available memory allocation in -** the lookaside subsystem is stored on a linked list of LookasideSlot -** objects. -** -** Lookaside allocations are only allowed for objects that are associated -** with a particular database connection. Hence, schema information cannot -** be stored in lookaside because in shared cache mode the schema information -** is shared by multiple database connections. Therefore, while parsing -** schema information, the Lookaside.bEnabled flag is cleared so that -** lookaside allocations are not used to construct the schema objects. -*/ -struct Lookaside { - u16 sz; /* Size of each buffer in bytes */ - u8 bEnabled; /* False to disable new lookaside allocations */ - u8 bMalloced; /* True if pStart obtained from sqlite3_malloc() */ - int nOut; /* Number of buffers currently checked out */ - int mxOut; /* Highwater mark for nOut */ - int anStat[3]; /* 0: hits. 1: size misses. 2: full misses */ - LookasideSlot *pFree; /* List of available buffers */ - void *pStart; /* First byte of available memory space */ - void *pEnd; /* First byte past end of available space */ -}; -struct LookasideSlot { - LookasideSlot *pNext; /* Next buffer in the list of free buffers */ -}; - -/* -** A hash table for function definitions. -** -** Hash each FuncDef structure into one of the FuncDefHash.a[] slots. -** Collisions are on the FuncDef.pHash chain. -*/ -struct FuncDefHash { - FuncDef *a[23]; /* Hash table for functions */ -}; - -/* -** Each database connection is an instance of the following structure. -*/ -struct sqlite3 { - sqlite3_vfs *pVfs; /* OS Interface */ - struct Vdbe *pVdbe; /* List of active virtual machines */ - CollSeq *pDfltColl; /* The default collating sequence (BINARY) */ - sqlite3_mutex *mutex; /* Connection mutex */ - Db *aDb; /* All backends */ - int nDb; /* Number of backends currently in use */ - int flags; /* Miscellaneous flags. See below */ - i64 lastRowid; /* ROWID of most recent insert (see above) */ - unsigned int openFlags; /* Flags passed to sqlite3_vfs.xOpen() */ - int errCode; /* Most recent error code (SQLITE_*) */ - int errMask; /* & result codes with this before returning */ - u16 dbOptFlags; /* Flags to enable/disable optimizations */ - u8 autoCommit; /* The auto-commit flag. */ - u8 temp_store; /* 1: file 2: memory 0: default */ - u8 mallocFailed; /* True if we have seen a malloc failure */ - u8 dfltLockMode; /* Default locking-mode for attached dbs */ - signed char nextAutovac; /* Autovac setting after VACUUM if >=0 */ - u8 suppressErr; /* Do not issue error messages if true */ - u8 vtabOnConflict; /* Value to return for s3_vtab_on_conflict() */ - u8 isTransactionSavepoint; /* True if the outermost savepoint is a TS */ - int nextPagesize; /* Pagesize after VACUUM if >0 */ - u32 magic; /* Magic number for detect library misuse */ - int nChange; /* Value returned by sqlite3_changes() */ - int nTotalChange; /* Value returned by sqlite3_total_changes() */ - int aLimit[SQLITE_N_LIMIT]; /* Limits */ - struct sqlite3InitInfo { /* Information used during initialization */ - int newTnum; /* Rootpage of table being initialized */ - u8 iDb; /* Which db file is being initialized */ - u8 busy; /* TRUE if currently initializing */ - u8 orphanTrigger; /* Last statement is orphaned TEMP trigger */ - } init; - int activeVdbeCnt; /* Number of VDBEs currently executing */ - int writeVdbeCnt; /* Number of active VDBEs that are writing */ - int vdbeExecCnt; /* Number of nested calls to VdbeExec() */ - int nExtension; /* Number of loaded extensions */ - void **aExtension; /* Array of shared library handles */ - void (*xTrace)(void*,const char*); /* Trace function */ - void *pTraceArg; /* Argument to the trace function */ - void (*xProfile)(void*,const char*,u64); /* Profiling function */ - void *pProfileArg; /* Argument to profile function */ - void *pCommitArg; /* Argument to xCommitCallback() */ - int (*xCommitCallback)(void*); /* Invoked at every commit. */ - void *pRollbackArg; /* Argument to xRollbackCallback() */ - void (*xRollbackCallback)(void*); /* Invoked at every commit. */ - void *pUpdateArg; - void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64); -#ifndef SQLITE_OMIT_WAL - int (*xWalCallback)(void *, sqlite3 *, const char *, int); - void *pWalArg; -#endif - void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*); - void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*); - void *pCollNeededArg; - sqlite3_value *pErr; /* Most recent error message */ - char *zErrMsg; /* Most recent error message (UTF-8 encoded) */ - char *zErrMsg16; /* Most recent error message (UTF-16 encoded) */ - union { - volatile int isInterrupted; /* True if sqlite3_interrupt has been called */ - double notUsed1; /* Spacer */ - } u1; - Lookaside lookaside; /* Lookaside malloc configuration */ -#ifndef SQLITE_OMIT_AUTHORIZATION - int (*xAuth)(void*,int,const char*,const char*,const char*,const char*); - /* Access authorization function */ - void *pAuthArg; /* 1st argument to the access auth function */ -#endif -#ifndef SQLITE_OMIT_PROGRESS_CALLBACK - int (*xProgress)(void *); /* The progress callback */ - void *pProgressArg; /* Argument to the progress callback */ - int nProgressOps; /* Number of opcodes for progress callback */ -#endif -#ifndef SQLITE_OMIT_VIRTUALTABLE - int nVTrans; /* Allocated size of aVTrans */ - Hash aModule; /* populated by sqlite3_create_module() */ - VtabCtx *pVtabCtx; /* Context for active vtab connect/create */ - VTable **aVTrans; /* Virtual tables with open transactions */ - VTable *pDisconnect; /* Disconnect these in next sqlite3_prepare() */ -#endif - FuncDefHash aFunc; /* Hash table of connection functions */ - Hash aCollSeq; /* All collating sequences */ - BusyHandler busyHandler; /* Busy callback */ - Db aDbStatic[2]; /* Static space for the 2 default backends */ - Savepoint *pSavepoint; /* List of active savepoints */ - int busyTimeout; /* Busy handler timeout, in msec */ - int nSavepoint; /* Number of non-transaction savepoints */ - int nStatement; /* Number of nested statement-transactions */ - i64 nDeferredCons; /* Net deferred constraints this transaction. */ - int *pnBytesFreed; /* If not NULL, increment this in DbFree() */ - -#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY - /* The following variables are all protected by the STATIC_MASTER - ** mutex, not by sqlite3.mutex. They are used by code in notify.c. - ** - ** When X.pUnlockConnection==Y, that means that X is waiting for Y to - ** unlock so that it can proceed. - ** - ** When X.pBlockingConnection==Y, that means that something that X tried - ** tried to do recently failed with an SQLITE_LOCKED error due to locks - ** held by Y. - */ - sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */ - sqlite3 *pUnlockConnection; /* Connection to watch for unlock */ - void *pUnlockArg; /* Argument to xUnlockNotify */ - void (*xUnlockNotify)(void **, int); /* Unlock notify callback */ - sqlite3 *pNextBlocked; /* Next in list of all blocked connections */ -#endif -}; - -/* -** A macro to discover the encoding of a database. -*/ -#define ENC(db) ((db)->aDb[0].pSchema->enc) - -/* -** Possible values for the sqlite3.flags. -*/ -#define SQLITE_VdbeTrace 0x00000001 /* True to trace VDBE execution */ -#define SQLITE_InternChanges 0x00000002 /* Uncommitted Hash table changes */ -#define SQLITE_FullColNames 0x00000004 /* Show full column names on SELECT */ -#define SQLITE_ShortColNames 0x00000008 /* Show short columns names */ -#define SQLITE_CountRows 0x00000010 /* Count rows changed by INSERT, */ - /* DELETE, or UPDATE and return */ - /* the count using a callback. */ -#define SQLITE_NullCallback 0x00000020 /* Invoke the callback once if the */ - /* result set is empty */ -#define SQLITE_SqlTrace 0x00000040 /* Debug print SQL as it executes */ -#define SQLITE_VdbeListing 0x00000080 /* Debug listings of VDBE programs */ -#define SQLITE_WriteSchema 0x00000100 /* OK to update SQLITE_MASTER */ -#define SQLITE_VdbeAddopTrace 0x00000200 /* Trace sqlite3VdbeAddOp() calls */ -#define SQLITE_IgnoreChecks 0x00000400 /* Do not enforce check constraints */ -#define SQLITE_ReadUncommitted 0x0000800 /* For shared-cache mode */ -#define SQLITE_LegacyFileFmt 0x00001000 /* Create new databases in format 1 */ -#define SQLITE_FullFSync 0x00002000 /* Use full fsync on the backend */ -#define SQLITE_CkptFullFSync 0x00004000 /* Use full fsync for checkpoint */ -#define SQLITE_RecoveryMode 0x00008000 /* Ignore schema errors */ -#define SQLITE_ReverseOrder 0x00010000 /* Reverse unordered SELECTs */ -#define SQLITE_RecTriggers 0x00020000 /* Enable recursive triggers */ -#define SQLITE_ForeignKeys 0x00040000 /* Enforce foreign key constraints */ -#define SQLITE_AutoIndex 0x00080000 /* Enable automatic indexes */ -#define SQLITE_PreferBuiltin 0x00100000 /* Preference to built-in funcs */ -#define SQLITE_LoadExtension 0x00200000 /* Enable load_extension */ -#define SQLITE_EnableTrigger 0x00400000 /* True to enable triggers */ - -/* -** Bits of the sqlite3.dbOptFlags field that are used by the -** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to -** selectively disable various optimizations. -*/ -#define SQLITE_QueryFlattener 0x0001 /* Query flattening */ -#define SQLITE_ColumnCache 0x0002 /* Column cache */ -#define SQLITE_GroupByOrder 0x0004 /* GROUPBY cover of ORDERBY */ -#define SQLITE_FactorOutConst 0x0008 /* Constant factoring */ -#define SQLITE_IdxRealAsInt 0x0010 /* Store REAL as INT in indices */ -#define SQLITE_DistinctOpt 0x0020 /* DISTINCT using indexes */ -#define SQLITE_CoverIdxScan 0x0040 /* Covering index scans */ -#define SQLITE_OrderByIdxJoin 0x0080 /* ORDER BY of joins via index */ -#define SQLITE_SubqCoroutine 0x0100 /* Evaluate subqueries as coroutines */ -#define SQLITE_Transitive 0x0200 /* Transitive constraints */ -#define SQLITE_AllOpts 0xffff /* All optimizations */ - -/* -** Macros for testing whether or not optimizations are enabled or disabled. -*/ -#ifndef SQLITE_OMIT_BUILTIN_TEST -#define OptimizationDisabled(db, mask) (((db)->dbOptFlags&(mask))!=0) -#define OptimizationEnabled(db, mask) (((db)->dbOptFlags&(mask))==0) -#else -#define OptimizationDisabled(db, mask) 0 -#define OptimizationEnabled(db, mask) 1 -#endif - -/* -** Possible values for the sqlite.magic field. -** The numbers are obtained at random and have no special meaning, other -** than being distinct from one another. -*/ -#define SQLITE_MAGIC_OPEN 0xa029a697 /* Database is open */ -#define SQLITE_MAGIC_CLOSED 0x9f3c2d33 /* Database is closed */ -#define SQLITE_MAGIC_SICK 0x4b771290 /* Error and awaiting close */ -#define SQLITE_MAGIC_BUSY 0xf03b7906 /* Database currently in use */ -#define SQLITE_MAGIC_ERROR 0xb5357930 /* An SQLITE_MISUSE error occurred */ -#define SQLITE_MAGIC_ZOMBIE 0x64cffc7f /* Close with last statement close */ - -/* -** Each SQL function is defined by an instance of the following -** structure. A pointer to this structure is stored in the sqlite.aFunc -** hash table. When multiple functions have the same name, the hash table -** points to a linked list of these structures. -*/ -struct FuncDef { - i16 nArg; /* Number of arguments. -1 means unlimited */ - u8 iPrefEnc; /* Preferred text encoding (SQLITE_UTF8, 16LE, 16BE) */ - u8 flags; /* Some combination of SQLITE_FUNC_* */ - void *pUserData; /* User data parameter */ - FuncDef *pNext; /* Next function with same name */ - void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */ - void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */ - void (*xFinalize)(sqlite3_context*); /* Aggregate finalizer */ - char *zName; /* SQL name of the function. */ - FuncDef *pHash; /* Next with a different name but the same hash */ - FuncDestructor *pDestructor; /* Reference counted destructor function */ -}; - -/* -** This structure encapsulates a user-function destructor callback (as -** configured using create_function_v2()) and a reference counter. When -** create_function_v2() is called to create a function with a destructor, -** a single object of this type is allocated. FuncDestructor.nRef is set to -** the number of FuncDef objects created (either 1 or 3, depending on whether -** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor -** member of each of the new FuncDef objects is set to point to the allocated -** FuncDestructor. -** -** Thereafter, when one of the FuncDef objects is deleted, the reference -** count on this object is decremented. When it reaches 0, the destructor -** is invoked and the FuncDestructor structure freed. -*/ -struct FuncDestructor { - int nRef; - void (*xDestroy)(void *); - void *pUserData; -}; - -/* -** Possible values for FuncDef.flags. Note that the _LENGTH and _TYPEOF -** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG. There -** are assert() statements in the code to verify this. -*/ -#define SQLITE_FUNC_LIKE 0x01 /* Candidate for the LIKE optimization */ -#define SQLITE_FUNC_CASE 0x02 /* Case-sensitive LIKE-type function */ -#define SQLITE_FUNC_EPHEM 0x04 /* Ephemeral. Delete with VDBE */ -#define SQLITE_FUNC_NEEDCOLL 0x08 /* sqlite3GetFuncCollSeq() might be called */ -#define SQLITE_FUNC_COUNT 0x10 /* Built-in count(*) aggregate */ -#define SQLITE_FUNC_COALESCE 0x20 /* Built-in coalesce() or ifnull() function */ -#define SQLITE_FUNC_LENGTH 0x40 /* Built-in length() function */ -#define SQLITE_FUNC_TYPEOF 0x80 /* Built-in typeof() function */ - -/* -** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are -** used to create the initializers for the FuncDef structures. -** -** FUNCTION(zName, nArg, iArg, bNC, xFunc) -** Used to create a scalar function definition of a function zName -** implemented by C function xFunc that accepts nArg arguments. The -** value passed as iArg is cast to a (void*) and made available -** as the user-data (sqlite3_user_data()) for the function. If -** argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set. -** -** AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal) -** Used to create an aggregate function definition implemented by -** the C functions xStep and xFinal. The first four parameters -** are interpreted in the same way as the first 4 parameters to -** FUNCTION(). -** -** LIKEFUNC(zName, nArg, pArg, flags) -** Used to create a scalar function definition of a function zName -** that accepts nArg arguments and is implemented by a call to C -** function likeFunc. Argument pArg is cast to a (void *) and made -** available as the function user-data (sqlite3_user_data()). The -** FuncDef.flags variable is set to the value passed as the flags -** parameter. -*/ -#define FUNCTION(zName, nArg, iArg, bNC, xFunc) \ - {nArg, SQLITE_UTF8, (bNC*SQLITE_FUNC_NEEDCOLL), \ - SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0} -#define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags) \ - {nArg, SQLITE_UTF8, (bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags, \ - SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0} -#define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \ - {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \ - pArg, 0, xFunc, 0, 0, #zName, 0, 0} -#define LIKEFUNC(zName, nArg, arg, flags) \ - {nArg, SQLITE_UTF8, flags, (void *)arg, 0, likeFunc, 0, 0, #zName, 0, 0} -#define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \ - {nArg, SQLITE_UTF8, nc*SQLITE_FUNC_NEEDCOLL, \ - SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0} - -/* -** All current savepoints are stored in a linked list starting at -** sqlite3.pSavepoint. The first element in the list is the most recently -** opened savepoint. Savepoints are added to the list by the vdbe -** OP_Savepoint instruction. -*/ -struct Savepoint { - char *zName; /* Savepoint name (nul-terminated) */ - i64 nDeferredCons; /* Number of deferred fk violations */ - Savepoint *pNext; /* Parent savepoint (if any) */ -}; - -/* -** The following are used as the second parameter to sqlite3Savepoint(), -** and as the P1 argument to the OP_Savepoint instruction. -*/ -#define SAVEPOINT_BEGIN 0 -#define SAVEPOINT_RELEASE 1 -#define SAVEPOINT_ROLLBACK 2 - - -/* -** Each SQLite module (virtual table definition) is defined by an -** instance of the following structure, stored in the sqlite3.aModule -** hash table. -*/ -struct Module { - const sqlite3_module *pModule; /* Callback pointers */ - const char *zName; /* Name passed to create_module() */ - void *pAux; /* pAux passed to create_module() */ - void (*xDestroy)(void *); /* Module destructor function */ -}; - -/* -** information about each column of an SQL table is held in an instance -** of this structure. -*/ -struct Column { - char *zName; /* Name of this column */ - Expr *pDflt; /* Default value of this column */ - char *zDflt; /* Original text of the default value */ - char *zType; /* Data type for this column */ - char *zColl; /* Collating sequence. If NULL, use the default */ - u8 notNull; /* An OE_ code for handling a NOT NULL constraint */ - char affinity; /* One of the SQLITE_AFF_... values */ - u16 colFlags; /* Boolean properties. See COLFLAG_ defines below */ -}; - -/* Allowed values for Column.colFlags: -*/ -#define COLFLAG_PRIMKEY 0x0001 /* Column is part of the primary key */ -#define COLFLAG_HIDDEN 0x0002 /* A hidden column in a virtual table */ - -/* -** A "Collating Sequence" is defined by an instance of the following -** structure. Conceptually, a collating sequence consists of a name and -** a comparison routine that defines the order of that sequence. -** -** If CollSeq.xCmp is NULL, it means that the -** collating sequence is undefined. Indices built on an undefined -** collating sequence may not be read or written. -*/ -struct CollSeq { - char *zName; /* Name of the collating sequence, UTF-8 encoded */ - u8 enc; /* Text encoding handled by xCmp() */ - void *pUser; /* First argument to xCmp() */ - int (*xCmp)(void*,int, const void*, int, const void*); - void (*xDel)(void*); /* Destructor for pUser */ -}; - -/* -** A sort order can be either ASC or DESC. -*/ -#define SQLITE_SO_ASC 0 /* Sort in ascending order */ -#define SQLITE_SO_DESC 1 /* Sort in ascending order */ - -/* -** Column affinity types. -** -** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and -** 't' for SQLITE_AFF_TEXT. But we can save a little space and improve -** the speed a little by numbering the values consecutively. -** -** But rather than start with 0 or 1, we begin with 'a'. That way, -** when multiple affinity types are concatenated into a string and -** used as the P4 operand, they will be more readable. -** -** Note also that the numeric types are grouped together so that testing -** for a numeric type is a single comparison. -*/ -#define SQLITE_AFF_TEXT 'a' -#define SQLITE_AFF_NONE 'b' -#define SQLITE_AFF_NUMERIC 'c' -#define SQLITE_AFF_INTEGER 'd' -#define SQLITE_AFF_REAL 'e' - -#define sqlite3IsNumericAffinity(X) ((X)>=SQLITE_AFF_NUMERIC) - -/* -** The SQLITE_AFF_MASK values masks off the significant bits of an -** affinity value. -*/ -#define SQLITE_AFF_MASK 0x67 - -/* -** Additional bit values that can be ORed with an affinity without -** changing the affinity. -*/ -#define SQLITE_JUMPIFNULL 0x08 /* jumps if either operand is NULL */ -#define SQLITE_STOREP2 0x10 /* Store result in reg[P2] rather than jump */ -#define SQLITE_NULLEQ 0x80 /* NULL=NULL */ - -/* -** An object of this type is created for each virtual table present in -** the database schema. -** -** If the database schema is shared, then there is one instance of this -** structure for each database connection (sqlite3*) that uses the shared -** schema. This is because each database connection requires its own unique -** instance of the sqlite3_vtab* handle used to access the virtual table -** implementation. sqlite3_vtab* handles can not be shared between -** database connections, even when the rest of the in-memory database -** schema is shared, as the implementation often stores the database -** connection handle passed to it via the xConnect() or xCreate() method -** during initialization internally. This database connection handle may -** then be used by the virtual table implementation to access real tables -** within the database. So that they appear as part of the callers -** transaction, these accesses need to be made via the same database -** connection as that used to execute SQL operations on the virtual table. -** -** All VTable objects that correspond to a single table in a shared -** database schema are initially stored in a linked-list pointed to by -** the Table.pVTable member variable of the corresponding Table object. -** When an sqlite3_prepare() operation is required to access the virtual -** table, it searches the list for the VTable that corresponds to the -** database connection doing the preparing so as to use the correct -** sqlite3_vtab* handle in the compiled query. -** -** When an in-memory Table object is deleted (for example when the -** schema is being reloaded for some reason), the VTable objects are not -** deleted and the sqlite3_vtab* handles are not xDisconnect()ed -** immediately. Instead, they are moved from the Table.pVTable list to -** another linked list headed by the sqlite3.pDisconnect member of the -** corresponding sqlite3 structure. They are then deleted/xDisconnected -** next time a statement is prepared using said sqlite3*. This is done -** to avoid deadlock issues involving multiple sqlite3.mutex mutexes. -** Refer to comments above function sqlite3VtabUnlockList() for an -** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect -** list without holding the corresponding sqlite3.mutex mutex. -** -** The memory for objects of this type is always allocated by -** sqlite3DbMalloc(), using the connection handle stored in VTable.db as -** the first argument. -*/ -struct VTable { - sqlite3 *db; /* Database connection associated with this table */ - Module *pMod; /* Pointer to module implementation */ - sqlite3_vtab *pVtab; /* Pointer to vtab instance */ - int nRef; /* Number of pointers to this structure */ - u8 bConstraint; /* True if constraints are supported */ - int iSavepoint; /* Depth of the SAVEPOINT stack */ - VTable *pNext; /* Next in linked list (see above) */ -}; - -/* -** Each SQL table is represented in memory by an instance of the -** following structure. -** -** Table.zName is the name of the table. The case of the original -** CREATE TABLE statement is stored, but case is not significant for -** comparisons. -** -** Table.nCol is the number of columns in this table. Table.aCol is a -** pointer to an array of Column structures, one for each column. -** -** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of -** the column that is that key. Otherwise Table.iPKey is negative. Note -** that the datatype of the PRIMARY KEY must be INTEGER for this field to -** be set. An INTEGER PRIMARY KEY is used as the rowid for each row of -** the table. If a table has no INTEGER PRIMARY KEY, then a random rowid -** is generated for each row of the table. TF_HasPrimaryKey is set if -** the table has any PRIMARY KEY, INTEGER or otherwise. -** -** Table.tnum is the page number for the root BTree page of the table in the -** database file. If Table.iDb is the index of the database table backend -** in sqlite.aDb[]. 0 is for the main database and 1 is for the file that -** holds temporary tables and indices. If TF_Ephemeral is set -** then the table is stored in a file that is automatically deleted -** when the VDBE cursor to the table is closed. In this case Table.tnum -** refers VDBE cursor number that holds the table open, not to the root -** page number. Transient tables are used to hold the results of a -** sub-query that appears instead of a real table name in the FROM clause -** of a SELECT statement. -*/ -struct Table { - char *zName; /* Name of the table or view */ - Column *aCol; /* Information about each column */ - Index *pIndex; /* List of SQL indexes on this table. */ - Select *pSelect; /* NULL for tables. Points to definition if a view. */ - FKey *pFKey; /* Linked list of all foreign keys in this table */ - char *zColAff; /* String defining the affinity of each column */ -#ifndef SQLITE_OMIT_CHECK - ExprList *pCheck; /* All CHECK constraints */ -#endif - tRowcnt nRowEst; /* Estimated rows in table - from sqlite_stat1 table */ - int tnum; /* Root BTree node for this table (see note above) */ - i16 iPKey; /* If not negative, use aCol[iPKey] as the primary key */ - i16 nCol; /* Number of columns in this table */ - u16 nRef; /* Number of pointers to this Table */ - u8 tabFlags; /* Mask of TF_* values */ - u8 keyConf; /* What to do in case of uniqueness conflict on iPKey */ -#ifndef SQLITE_OMIT_ALTERTABLE - int addColOffset; /* Offset in CREATE TABLE stmt to add a new column */ -#endif -#ifndef SQLITE_OMIT_VIRTUALTABLE - int nModuleArg; /* Number of arguments to the module */ - char **azModuleArg; /* Text of all module args. [0] is module name */ - VTable *pVTable; /* List of VTable objects. */ -#endif - Trigger *pTrigger; /* List of triggers stored in pSchema */ - Schema *pSchema; /* Schema that contains this table */ - Table *pNextZombie; /* Next on the Parse.pZombieTab list */ -}; - -/* -** Allowed values for Tabe.tabFlags. -*/ -#define TF_Readonly 0x01 /* Read-only system table */ -#define TF_Ephemeral 0x02 /* An ephemeral table */ -#define TF_HasPrimaryKey 0x04 /* Table has a primary key */ -#define TF_Autoincrement 0x08 /* Integer primary key is autoincrement */ -#define TF_Virtual 0x10 /* Is a virtual table */ - - -/* -** Test to see whether or not a table is a virtual table. This is -** done as a macro so that it will be optimized out when virtual -** table support is omitted from the build. -*/ -#ifndef SQLITE_OMIT_VIRTUALTABLE -# define IsVirtual(X) (((X)->tabFlags & TF_Virtual)!=0) -# define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0) -#else -# define IsVirtual(X) 0 -# define IsHiddenColumn(X) 0 -#endif - -/* -** Each foreign key constraint is an instance of the following structure. -** -** A foreign key is associated with two tables. The "from" table is -** the table that contains the REFERENCES clause that creates the foreign -** key. The "to" table is the table that is named in the REFERENCES clause. -** Consider this example: -** -** CREATE TABLE ex1( -** a INTEGER PRIMARY KEY, -** b INTEGER CONSTRAINT fk1 REFERENCES ex2(x) -** ); -** -** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2". -** -** Each REFERENCES clause generates an instance of the following structure -** which is attached to the from-table. The to-table need not exist when -** the from-table is created. The existence of the to-table is not checked. -*/ -struct FKey { - Table *pFrom; /* Table containing the REFERENCES clause (aka: Child) */ - FKey *pNextFrom; /* Next foreign key in pFrom */ - char *zTo; /* Name of table that the key points to (aka: Parent) */ - FKey *pNextTo; /* Next foreign key on table named zTo */ - FKey *pPrevTo; /* Previous foreign key on table named zTo */ - int nCol; /* Number of columns in this key */ - /* EV: R-30323-21917 */ - u8 isDeferred; /* True if constraint checking is deferred till COMMIT */ - u8 aAction[2]; /* ON DELETE and ON UPDATE actions, respectively */ - Trigger *apTrigger[2]; /* Triggers for aAction[] actions */ - struct sColMap { /* Mapping of columns in pFrom to columns in zTo */ - int iFrom; /* Index of column in pFrom */ - char *zCol; /* Name of column in zTo. If 0 use PRIMARY KEY */ - } aCol[1]; /* One entry for each of nCol column s */ -}; - -/* -** SQLite supports many different ways to resolve a constraint -** error. ROLLBACK processing means that a constraint violation -** causes the operation in process to fail and for the current transaction -** to be rolled back. ABORT processing means the operation in process -** fails and any prior changes from that one operation are backed out, -** but the transaction is not rolled back. FAIL processing means that -** the operation in progress stops and returns an error code. But prior -** changes due to the same operation are not backed out and no rollback -** occurs. IGNORE means that the particular row that caused the constraint -** error is not inserted or updated. Processing continues and no error -** is returned. REPLACE means that preexisting database rows that caused -** a UNIQUE constraint violation are removed so that the new insert or -** update can proceed. Processing continues and no error is reported. -** -** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys. -** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the -** same as ROLLBACK for DEFERRED keys. SETNULL means that the foreign -** key is set to NULL. CASCADE means that a DELETE or UPDATE of the -** referenced table row is propagated into the row that holds the -** foreign key. -** -** The following symbolic values are used to record which type -** of action to take. -*/ -#define OE_None 0 /* There is no constraint to check */ -#define OE_Rollback 1 /* Fail the operation and rollback the transaction */ -#define OE_Abort 2 /* Back out changes but do no rollback transaction */ -#define OE_Fail 3 /* Stop the operation but leave all prior changes */ -#define OE_Ignore 4 /* Ignore the error. Do not do the INSERT or UPDATE */ -#define OE_Replace 5 /* Delete existing record, then do INSERT or UPDATE */ - -#define OE_Restrict 6 /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */ -#define OE_SetNull 7 /* Set the foreign key value to NULL */ -#define OE_SetDflt 8 /* Set the foreign key value to its default */ -#define OE_Cascade 9 /* Cascade the changes */ - -#define OE_Default 99 /* Do whatever the default action is */ - - -/* -** An instance of the following structure is passed as the first -** argument to sqlite3VdbeKeyCompare and is used to control the -** comparison of the two index keys. -*/ -struct KeyInfo { - sqlite3 *db; /* The database connection */ - u8 enc; /* Text encoding - one of the SQLITE_UTF* values */ - u16 nField; /* Number of entries in aColl[] */ - u8 *aSortOrder; /* Sort order for each column. May be NULL */ - CollSeq *aColl[1]; /* Collating sequence for each term of the key */ -}; - -/* -** An instance of the following structure holds information about a -** single index record that has already been parsed out into individual -** values. -** -** A record is an object that contains one or more fields of data. -** Records are used to store the content of a table row and to store -** the key of an index. A blob encoding of a record is created by -** the OP_MakeRecord opcode of the VDBE and is disassembled by the -** OP_Column opcode. -** -** This structure holds a record that has already been disassembled -** into its constituent fields. -*/ -struct UnpackedRecord { - KeyInfo *pKeyInfo; /* Collation and sort-order information */ - u16 nField; /* Number of entries in apMem[] */ - u8 flags; /* Boolean settings. UNPACKED_... below */ - i64 rowid; /* Used by UNPACKED_PREFIX_SEARCH */ - Mem *aMem; /* Values */ -}; - -/* -** Allowed values of UnpackedRecord.flags -*/ -#define UNPACKED_INCRKEY 0x01 /* Make this key an epsilon larger */ -#define UNPACKED_PREFIX_MATCH 0x02 /* A prefix match is considered OK */ -#define UNPACKED_PREFIX_SEARCH 0x04 /* Ignore final (rowid) field */ - -/* -** Each SQL index is represented in memory by an -** instance of the following structure. -** -** The columns of the table that are to be indexed are described -** by the aiColumn[] field of this structure. For example, suppose -** we have the following table and index: -** -** CREATE TABLE Ex1(c1 int, c2 int, c3 text); -** CREATE INDEX Ex2 ON Ex1(c3,c1); -** -** In the Table structure describing Ex1, nCol==3 because there are -** three columns in the table. In the Index structure describing -** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed. -** The value of aiColumn is {2, 0}. aiColumn[0]==2 because the -** first column to be indexed (c3) has an index of 2 in Ex1.aCol[]. -** The second column to be indexed (c1) has an index of 0 in -** Ex1.aCol[], hence Ex2.aiColumn[1]==0. -** -** The Index.onError field determines whether or not the indexed columns -** must be unique and what to do if they are not. When Index.onError=OE_None, -** it means this is not a unique index. Otherwise it is a unique index -** and the value of Index.onError indicate the which conflict resolution -** algorithm to employ whenever an attempt is made to insert a non-unique -** element. -*/ -struct Index { - char *zName; /* Name of this index */ - int *aiColumn; /* Which columns are used by this index. 1st is 0 */ - tRowcnt *aiRowEst; /* From ANALYZE: Est. rows selected by each column */ - Table *pTable; /* The SQL table being indexed */ - char *zColAff; /* String defining the affinity of each column */ - Index *pNext; /* The next index associated with the same table */ - Schema *pSchema; /* Schema containing this index */ - u8 *aSortOrder; /* for each column: True==DESC, False==ASC */ - char **azColl; /* Array of collation sequence names for index */ - int tnum; /* DB Page containing root of this index */ - u16 nColumn; /* Number of columns in table used by this index */ - u8 onError; /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */ - unsigned autoIndex:2; /* 1==UNIQUE, 2==PRIMARY KEY, 0==CREATE INDEX */ - unsigned bUnordered:1; /* Use this index for == or IN queries only */ -#ifdef SQLITE_ENABLE_STAT3 - int nSample; /* Number of elements in aSample[] */ - tRowcnt avgEq; /* Average nEq value for key values not in aSample */ - IndexSample *aSample; /* Samples of the left-most key */ -#endif -}; - -/* -** Each sample stored in the sqlite_stat3 table is represented in memory -** using a structure of this type. See documentation at the top of the -** analyze.c source file for additional information. -*/ -struct IndexSample { - union { - char *z; /* Value if eType is SQLITE_TEXT or SQLITE_BLOB */ - double r; /* Value if eType is SQLITE_FLOAT */ - i64 i; /* Value if eType is SQLITE_INTEGER */ - } u; - u8 eType; /* SQLITE_NULL, SQLITE_INTEGER ... etc. */ - int nByte; /* Size in byte of text or blob. */ - tRowcnt nEq; /* Est. number of rows where the key equals this sample */ - tRowcnt nLt; /* Est. number of rows where key is less than this sample */ - tRowcnt nDLt; /* Est. number of distinct keys less than this sample */ -}; - -/* -** Each token coming out of the lexer is an instance of -** this structure. Tokens are also used as part of an expression. -** -** Note if Token.z==0 then Token.dyn and Token.n are undefined and -** may contain random values. Do not make any assumptions about Token.dyn -** and Token.n when Token.z==0. -*/ -struct Token { - const char *z; /* Text of the token. Not NULL-terminated! */ - unsigned int n; /* Number of characters in this token */ -}; - -/* -** An instance of this structure contains information needed to generate -** code for a SELECT that contains aggregate functions. -** -** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a -** pointer to this structure. The Expr.iColumn field is the index in -** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate -** code for that node. -** -** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the -** original Select structure that describes the SELECT statement. These -** fields do not need to be freed when deallocating the AggInfo structure. -*/ -struct AggInfo { - u8 directMode; /* Direct rendering mode means take data directly - ** from source tables rather than from accumulators */ - u8 useSortingIdx; /* In direct mode, reference the sorting index rather - ** than the source table */ - int sortingIdx; /* Cursor number of the sorting index */ - int sortingIdxPTab; /* Cursor number of pseudo-table */ - int nSortingColumn; /* Number of columns in the sorting index */ - ExprList *pGroupBy; /* The group by clause */ - struct AggInfo_col { /* For each column used in source tables */ - Table *pTab; /* Source table */ - int iTable; /* Cursor number of the source table */ - int iColumn; /* Column number within the source table */ - int iSorterColumn; /* Column number in the sorting index */ - int iMem; /* Memory location that acts as accumulator */ - Expr *pExpr; /* The original expression */ - } *aCol; - int nColumn; /* Number of used entries in aCol[] */ - int nAccumulator; /* Number of columns that show through to the output. - ** Additional columns are used only as parameters to - ** aggregate functions */ - struct AggInfo_func { /* For each aggregate function */ - Expr *pExpr; /* Expression encoding the function */ - FuncDef *pFunc; /* The aggregate function implementation */ - int iMem; /* Memory location that acts as accumulator */ - int iDistinct; /* Ephemeral table used to enforce DISTINCT */ - } *aFunc; - int nFunc; /* Number of entries in aFunc[] */ -}; - -/* -** The datatype ynVar is a signed integer, either 16-bit or 32-bit. -** Usually it is 16-bits. But if SQLITE_MAX_VARIABLE_NUMBER is greater -** than 32767 we have to make it 32-bit. 16-bit is preferred because -** it uses less memory in the Expr object, which is a big memory user -** in systems with lots of prepared statements. And few applications -** need more than about 10 or 20 variables. But some extreme users want -** to have prepared statements with over 32767 variables, and for them -** the option is available (at compile-time). -*/ -#if SQLITE_MAX_VARIABLE_NUMBER<=32767 -typedef i16 ynVar; -#else -typedef int ynVar; -#endif - -/* -** Each node of an expression in the parse tree is an instance -** of this structure. -** -** Expr.op is the opcode. The integer parser token codes are reused -** as opcodes here. For example, the parser defines TK_GE to be an integer -** code representing the ">=" operator. This same integer code is reused -** to represent the greater-than-or-equal-to operator in the expression -** tree. -** -** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB, -** or TK_STRING), then Expr.token contains the text of the SQL literal. If -** the expression is a variable (TK_VARIABLE), then Expr.token contains the -** variable name. Finally, if the expression is an SQL function (TK_FUNCTION), -** then Expr.token contains the name of the function. -** -** Expr.pRight and Expr.pLeft are the left and right subexpressions of a -** binary operator. Either or both may be NULL. -** -** Expr.x.pList is a list of arguments if the expression is an SQL function, -** a CASE expression or an IN expression of the form " IN (, ...)". -** Expr.x.pSelect is used if the expression is a sub-select or an expression of -** the form " IN (SELECT ...)". If the EP_xIsSelect bit is set in the -** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is -** valid. -** -** An expression of the form ID or ID.ID refers to a column in a table. -** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is -** the integer cursor number of a VDBE cursor pointing to that table and -** Expr.iColumn is the column number for the specific column. If the -** expression is used as a result in an aggregate SELECT, then the -** value is also stored in the Expr.iAgg column in the aggregate so that -** it can be accessed after all aggregates are computed. -** -** If the expression is an unbound variable marker (a question mark -** character '?' in the original SQL) then the Expr.iTable holds the index -** number for that variable. -** -** If the expression is a subquery then Expr.iColumn holds an integer -** register number containing the result of the subquery. If the -** subquery gives a constant result, then iTable is -1. If the subquery -** gives a different answer at different times during statement processing -** then iTable is the address of a subroutine that computes the subquery. -** -** If the Expr is of type OP_Column, and the table it is selecting from -** is a disk table or the "old.*" pseudo-table, then pTab points to the -** corresponding table definition. -** -** ALLOCATION NOTES: -** -** Expr objects can use a lot of memory space in database schema. To -** help reduce memory requirements, sometimes an Expr object will be -** truncated. And to reduce the number of memory allocations, sometimes -** two or more Expr objects will be stored in a single memory allocation, -** together with Expr.zToken strings. -** -** If the EP_Reduced and EP_TokenOnly flags are set when -** an Expr object is truncated. When EP_Reduced is set, then all -** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees -** are contained within the same memory allocation. Note, however, that -** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately -** allocated, regardless of whether or not EP_Reduced is set. -*/ -struct Expr { - u8 op; /* Operation performed by this node */ - char affinity; /* The affinity of the column or 0 if not a column */ - u16 flags; /* Various flags. EP_* See below */ - union { - char *zToken; /* Token value. Zero terminated and dequoted */ - int iValue; /* Non-negative integer value if EP_IntValue */ - } u; - - /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no - ** space is allocated for the fields below this point. An attempt to - ** access them will result in a segfault or malfunction. - *********************************************************************/ - - Expr *pLeft; /* Left subnode */ - Expr *pRight; /* Right subnode */ - union { - ExprList *pList; /* Function arguments or in " IN ( IN (