dMatrix clSpline::GetCoordinates(const dMatrix &uSpec) { dMatrix coord; if(uSpec.GetNumberColumns() != 1 || uSpec.GetNumberRows() == 0) { throw clException("clSpline", "GetCoordinates", "Invalid dimensions of matrix uSpec."); } else { coord.SetNumberRows(uSpec.GetNumberRows()); coord.SetNumberColumns(3); if(!initialised) { Initialise(); } // Do for all specified u's for(int i=1; i<=uSpec.GetNumberRows(); i++) { if(uSpec(i, 1) < 0 || uSpec(i, 1) > 1) { throw clException("clSpline", "GetCoordinates", "Invalid value for uSpec."); } else { // Now find the position of uSpec double uu = uSpec(i, 1)*GetSplineLength(); int j = 1; while((uu - u(j+1, 1) > 0) && (j<u.GetNumberRows()-1)) { j++; } // Now calculate the coefficients double A = (u(j+1, 1)-uu)/(u(j+1, 1)-u(j,1)); double B = 1-A; double C = (A*A*A-A)/6 * (u(j+1, 1)-u(j, 1))*(u(j+1, 1)-u(j, 1)); double D = (B*B*B-B)/6 * (u(j+1, 1)-u(j, 1))*(u(j+1, 1)-u(j, 1)); // Finally calculate the coordinates coord.SetElement(i, 1, A*X(j, 1) + B*X(j+1, 1) + C*X2(j, 1) + D*X2(j+1, 1)); coord.SetElement(i, 2, A*Y(j, 1) + B*Y(j+1, 1) + C*Y2(j, 1) + D*Y2(j+1, 1)); coord.SetElement(i, 3, A*Z(j, 1) + B*Z(j+1, 1) + C*Z2(j, 1) + D*Z2(j+1, 1)); } } } return (coord); }
void clSpline::FirstDerivatives(void) { double deltaU; double deltaX; double deltaY; double deltaZ; // Get maximum number of rows int rmax = u.GetNumberRows(); X1.SetNumberRows(rmax); X1.SetNumberColumns(1); Y1.SetNumberRows(rmax); Y1.SetNumberColumns(1); Z1.SetNumberRows(rmax); Z1.SetNumberColumns(1); for(int r=1; r<rmax; r++) { deltaU = u.GetElement(r+1, 1) - u.GetElement(r, 1); if(fabs(deltaU)<PRECISION) { deltaU = PRECISION; //throw clException("clSpline", "FirstDerivatives", "Division by zero."); } deltaX = X.GetElement(r+1, 1) - X.GetElement(r, 1); deltaY = Y.GetElement(r+1, 1) - Y.GetElement(r, 1); deltaZ = Z.GetElement(r+1, 1) - Z.GetElement(r, 1); X1.SetElement(r, 1, fabs(deltaX)*(deltaX/deltaU - deltaU*X2(r, 1)/3.0 - deltaU*X2(r+1, 1)/6.0)); Y1.SetElement(r, 1, fabs(deltaY)*(deltaY/deltaU - deltaU*Y2(r, 1)/3.0 - deltaU*Y2(r+1, 1)/6.0)); Z1.SetElement(r, 1, fabs(deltaZ)*(deltaZ/deltaU - deltaU*Z2(r, 1)/3.0 - deltaU*Z2(r+1, 1)/6.0)); } // Do last control point; work backwards deltaU = u.GetElement(rmax-1, 1) - u.GetElement(rmax, 1); if(fabs(deltaU)<PRECISION) { deltaU = PRECISION; //throw clException("clSpline", "FirstDerivatives", "Division by zero."); } deltaX = X.GetElement(rmax-1, 1) - X.GetElement(rmax, 1); deltaY = Y.GetElement(rmax-1, 1) - Y.GetElement(rmax, 1); deltaZ = Z.GetElement(rmax-1, 1) - Z.GetElement(rmax, 1); X1.SetElement(rmax, 1, fabs(deltaX)*(deltaX/deltaU - deltaU*X2(rmax, 1)/3.0 - deltaU*X2(rmax-1, 1)/6.0)); Y1.SetElement(rmax, 1, fabs(deltaY)*(deltaY/deltaU - deltaU*Y2(rmax, 1)/3.0 - deltaU*Y2(rmax-1, 1)/6.0)); Z1.SetElement(rmax, 1, fabs(deltaZ)*(deltaZ/deltaU - deltaU*Z2(rmax, 1)/3.0 - deltaU*Z2(rmax-1, 1)/6.0)); }
void sleep_apnea::HP_LP_filter (QVector<QVector<double> > &tab_res) { int i,j; //high-pass filter QVector<double> Z1(tab_res[0].size()); for(i=0;i<Z1.size();i++)Z1[i]=0; double CUTOFF = 0.01; double RC = 1.0/(CUTOFF*2*3.14); double dt = 1.0/1.0; double alpha = RC/(RC+dt); for (j=1;j<tab_res[0].size();j++) Z1[j]=alpha*(Z1[j-1] + tab_res[1][j] - tab_res[1][j-1]); //low-pass filter QVector<double> Z2(tab_res[0].size()); for(int i=0;i<Z2.size();i++)Z2[i]=0; CUTOFF = 0.09; RC = 1.0/(CUTOFF*2*3.14); dt = 1.0/1.0; alpha = dt/(RC+dt); for (j=1;j<Z1.size();j++) Z2[j] = Z2[j-1] + (alpha * (Z1[j] - Z2[j-1])); //wrtiting to output array for (i=0;i<tab_res[0].size();i++) tab_res[1][i]=Z2[i]; }
/// \brief Update Kalman filter void UnscentedKalmanFilter::updateUKF(vnl_vector<double> u, vnl_vector<double> z) { // create Sigma points X for the current estimate distribution vnl_matrix<double> X(N,2*N+1); sigmas(x_hat, P_hat+Q, sqrt(C), X); vnl_matrix<double> Dbg; qDebug() << "X: "; for( int i = 0; i<6; i++) { qDebug() << X(i,0) << " " << X(i,1) << " " << X(i,2) << " " << X(i,3) << " " << X(i,4) << " " << X(i,5) << " " << X(i,6) << " " << X(i,7) << " " << X(i,8) << " " << X(i,9) << " " << X(i,10) << " " << X(i,11) << " " << X(i,12); } // apply unscented transformation for process model vnl_vector<double> x1(6); vnl_matrix<double> X1(N,2*N+1), P1(N,N), X2(N,2*N+1); utf(X, u, x1, X1, P1, X2); // apply unscented transformation for observation model vnl_vector<double> z1(M); vnl_matrix<double> Z1(M,2*M+1), P2(M,M), Z2(M,2*M+1); utg(X1, z1, Z1, P2, Z2); // define transformated cross-covariance vnl_matrix<double> WC(2*N+1,2*N+1,0.0); WC.set_diagonal(Wc.get_row(0)); vnl_matrix<double> P12 = X2*WC*Z2.transpose(); // perform state update K = P12*vnl_matrix_inverse<double>(P2); x_hat = x1 + K*(z-z1); // perform covariance update P_hat = P1 - K*P12.transpose(); }
const stresstensor& YieldFunction::InTensorDerivative(const stresstensor& Stre, const MaterialParameter &MaterialParameter_in, int which) const { tensor Z2(2, def_dim_2, 0.0); stressYF.Initialize(Z2); return stressYF; }
dMatrix clSpline::GetSecondDerivatives(void) { dMatrix dummy; if(!initialised) { Initialise(); } dummy.SetNumberRows(X2.GetNumberRows()); dummy.SetNumberColumns(3); for(int i=1; i<=X2.GetNumberRows(); i++) { dummy.SetElement(i, 1, fabs(X2(i, 1)) < PRECISION ? 0.0 : X2(i, 1)); dummy.SetElement(i, 2, fabs(Y2(i, 1)) < PRECISION ? 0.0 : Y2(i, 1)); dummy.SetElement(i, 3, fabs(Z2(i, 1)) < PRECISION ? 0.0 : Z2(i, 1)); } return(dummy); }
void HClusterDlg::SpatialConstraintClustering() { int transpose = 0; // row wise fastcluster::cluster_result Z2(rows-1); if (chk_contiguity->GetValue()) { vector<boost::uuids::uuid> 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; } //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; } 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<bool> undefs(rows, false); SpanningTreeClustering::AbstractClusterFactory* redcap = new SpanningTreeClustering::FirstOrderSLKRedCap(rows, columns, distances, input_data, undefs, gw->gal, NULL, 0); for (int i=0; i<redcap->ordered_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; } delete redcap; } }
//function [y,Y,P,Y1]=ut(f,X,Wm,Wc,n,R) void BFilterUKF::utMeasurement(fmat X, fvec Wm, fvec Wc, unsigned int n, fmat R) { //Unscented Transformation //Input: // f: nonlinear map // X: sigma points // Wm: weights for mean // Wc: weights for covraiance // n: numer of outputs of f // R: additive covariance //Output: // y: transformed mean // Y: transformed smapling points // P: transformed covariance // Y1: transformed deviations unsigned int L=X.n_cols; z1=zeros<fvec>(n); Z1=zeros<fmat>(n,L); //for k=1:L for (unsigned int k=0; k < L; ++k) { fmat XColK = X.col(k); Z1.col(k)= process->ffun(&XColK); z1=z1+Wm(k)*Z1.col(k); } //Z2=Z1-x1(:,ones(1,L)); Z2 = Z1; for (unsigned int j = 0; j < L; ++j) { for (unsigned int i = 0; i < x1.n_rows; ++i) { Z2(i,j) -= x1(i); } } P2=Z2*Wc.diag()*Z2.t()+R; }
Lattice Z2() { Lattice Z2(2); Z2.bond(0,0,coo(1,0)).bond(0,0,coo(0,1)); Z2.z[0]=0; return Z2; }
SEXP fastcluster(SEXP const N_, SEXP const method_, SEXP D_, SEXP members_) { SEXP r = NULL; // return value try{ /* Input checks */ // Parameter N: number of data points PROTECT(N_); if (!IS_INTEGER(N_) || LENGTH(N_)!=1) Rf_error("'N' must be a single integer."); const int N = *INTEGER_POINTER(N_); if (N<2) Rf_error("N must be at least 2."); const std::ptrdiff_t NN = static_cast<std::ptrdiff_t>(N)*(N-1)/2; UNPROTECT(1); // N_ // Parameter method: dissimilarity index update method PROTECT(method_); if (!IS_INTEGER(method_) || LENGTH(method_)!=1) Rf_error("'method' must be a single integer."); const int method = *INTEGER_POINTER(method_) - 1; // index-0 based; if (method<METHOD_METR_SINGLE || method>METHOD_METR_MEDIAN) { Rf_error("Invalid method index."); } UNPROTECT(1); // method_ // Parameter members: number of members in each node auto_array_ptr<t_float> members; if (method==METHOD_METR_AVERAGE || method==METHOD_METR_WARD || method==METHOD_METR_CENTROID) { members.init(N); if (Rf_isNull(members_)) { for (t_index i=0; i<N; ++i) members[i] = 1; } else { PROTECT(members_ = AS_NUMERIC(members_)); if (LENGTH(members_)!=N) Rf_error("'members' must have length N."); const t_float * const m = NUMERIC_POINTER(members_); for (t_index i=0; i<N; ++i) members[i] = m[i]; UNPROTECT(1); // members } } // Parameter D_: dissimilarity matrix PROTECT(D_ = AS_NUMERIC(D_)); if (LENGTH(D_)!=NN) Rf_error("'D' must have length (N \\choose 2)."); const double * const D = NUMERIC_POINTER(D_); // Make a working copy of the dissimilarity array // for all methods except "single". auto_array_ptr<double> D__; if (method!=METHOD_METR_SINGLE) { D__.init(NN); for (std::ptrdiff_t i=0; i<NN; ++i) D__[i] = D[i]; } UNPROTECT(1); // D_ /* Clustering step */ cluster_result Z2(N-1); switch (method) { case METHOD_METR_SINGLE: MST_linkage_core(N, D, Z2); break; case METHOD_METR_COMPLETE: NN_chain_core<METHOD_METR_COMPLETE, t_float>(N, D__, NULL, Z2); break; case METHOD_METR_AVERAGE: NN_chain_core<METHOD_METR_AVERAGE, t_float>(N, D__, members, Z2); break; case METHOD_METR_WEIGHTED: NN_chain_core<METHOD_METR_WEIGHTED, t_float>(N, D__, NULL, Z2); break; case METHOD_METR_WARD: NN_chain_core<METHOD_METR_WARD, t_float>(N, D__, members, Z2); break; case METHOD_METR_CENTROID: generic_linkage<METHOD_METR_CENTROID, t_float>(N, D__, members, Z2); break; case METHOD_METR_MEDIAN: generic_linkage<METHOD_METR_MEDIAN, t_float>(N, D__, NULL, Z2); break; default: throw std::runtime_error(std::string("Invalid method.")); } D__.free(); // Free the memory now members.free(); // (not strictly necessary). SEXP m; // return field "merge" PROTECT(m = NEW_INTEGER(2*(N-1))); int * const merge = INTEGER_POINTER(m); SEXP dim_m; // Specify that m is an (N-1)×2 matrix PROTECT(dim_m = NEW_INTEGER(2)); INTEGER(dim_m)[0] = N-1; INTEGER(dim_m)[1] = 2; SET_DIM(m, dim_m); SEXP h; // return field "height" PROTECT(h = NEW_NUMERIC(N-1)); double * const height = NUMERIC_POINTER(h); SEXP o; // return fiels "order' PROTECT(o = NEW_INTEGER(N)); int * const order = INTEGER_POINTER(o); if (method==METHOD_METR_CENTROID || method==METHOD_METR_MEDIAN) generate_R_dendrogram<true>(merge, height, order, Z2, N); else generate_R_dendrogram<false>(merge, height, order, Z2, N); SEXP n; // names PROTECT(n = NEW_CHARACTER(3)); SET_STRING_ELT(n, 0, COPY_TO_USER_STRING("merge")); SET_STRING_ELT(n, 1, COPY_TO_USER_STRING("height")); SET_STRING_ELT(n, 2, COPY_TO_USER_STRING("order")); PROTECT(r = NEW_LIST(3)); // field names in the output list SET_ELEMENT(r, 0, m); SET_ELEMENT(r, 1, h); SET_ELEMENT(r, 2, o); SET_NAMES(r, n); UNPROTECT(6); // m, dim_m, h, o, r, n } // try catch (const std::bad_alloc&) { Rf_error( "Memory overflow."); } catch(const std::exception& e){ Rf_error( e.what() ); } catch(const nan_error&){ Rf_error("NaN dissimilarity value."); } #ifdef FE_INVALID catch(const fenv_error&){ Rf_error( "NaN dissimilarity value in intermediate results."); } #endif catch(...){ Rf_error( "C++ exception (unknown reason)." ); } return r; }
SEXP fastcluster_vector(SEXP const method_, SEXP const metric_, SEXP X_, SEXP members_, SEXP p_) { SEXP r = NULL; // return value try{ /* Input checks */ // Parameter method: dissimilarity index update method PROTECT(method_); if (!IS_INTEGER(method_) || LENGTH(method_)!=1) Rf_error("'method' must be a single integer."); int method = *INTEGER_POINTER(method_) - 1; // index-0 based; if (method<METHOD_VECTOR_SINGLE || method>METHOD_VECTOR_MEDIAN) { Rf_error("Invalid method index."); } UNPROTECT(1); // method_ // Parameter metric PROTECT(metric_); if (!IS_INTEGER(metric_) || LENGTH(metric_)!=1) Rf_error("'metric' must be a single integer."); int metric = *INTEGER_POINTER(metric_) - 1; // index-0 based; if (metric<0 || metric>5 || (method!=METHOD_VECTOR_SINGLE && metric!=0) ) { Rf_error("Invalid metric index."); } UNPROTECT(1); // metric_ // data array PROTECT(X_ = AS_NUMERIC(X_)); SEXP dims_ = PROTECT( Rf_getAttrib( X_, R_DimSymbol ) ) ; if( dims_ == R_NilValue || LENGTH(dims_) != 2 ) { Rf_error( "Argument is not a matrix."); } const int * const dims = INTEGER(dims_); const int N = dims[0]; const int dim = dims[1]; if (N<2) Rf_error("There must be at least two data points."); // Make a working copy of the dissimilarity array // for all methods except "single". double * X__ = NUMERIC_POINTER(X_); // Copy the input array and change it from Fortran-contiguous style // to C-contiguous style // (Waste of memory for 'single'; the other methods need a copy auto_array_ptr<double> X(LENGTH(X_)); for (std::ptrdiff_t i=0; i<N; ++i) for (std::ptrdiff_t j=0; j<dim; ++j) X[i*dim+j] = X__[i+j*N]; UNPROTECT(2); // dims_, X_ // Parameter members: number of members in each node auto_array_ptr<t_float> members; if (method==METHOD_VECTOR_WARD || method==METHOD_VECTOR_CENTROID) { members.init(N); if (Rf_isNull(members_)) { for (t_index i=0; i<N; ++i) members[i] = 1; } else { PROTECT(members_ = AS_NUMERIC(members_)); if (LENGTH(members_)!=N) Rf_error("The length of 'members' must be the same as the number of data points."); const t_float * const m = NUMERIC_POINTER(members_); for (t_index i=0; i<N; ++i) members[i] = m[i]; UNPROTECT(1); // members } } // Parameter p PROTECT(p_); double p = 0; if (metric==METRIC_R_MINKOWSKI) { if (!IS_NUMERIC(p_) || LENGTH(p_)!=1) Rf_error("'p' must be a single floating point number."); p = *NUMERIC_POINTER(p_); } else { if (p_ != R_NilValue) { Rf_error("No metric except 'minkowski' allows a 'p' parameter."); } } UNPROTECT(1); // p_ /* The generic_linkage_vector_alternative algorithm uses labels N,N+1,... for the new nodes, so we need a table which node is stored in which row. Instructions: Set this variable to true for all methods which use the generic_linkage_vector_alternative algorithm below. */ bool make_row_repr = (method==METHOD_VECTOR_CENTROID || method==METHOD_VECTOR_MEDIAN); R_dissimilarity dist(X, N, dim, members, static_cast<unsigned char>(method), static_cast<unsigned char>(metric), p, make_row_repr); cluster_result Z2(N-1); /* Clustering step */ switch (method) { case METHOD_VECTOR_SINGLE: MST_linkage_core_vector(N, dist, Z2); break; case METHOD_VECTOR_WARD: generic_linkage_vector<METHOD_METR_WARD>(N, dist, Z2); break; case METHOD_VECTOR_CENTROID: generic_linkage_vector_alternative<METHOD_METR_CENTROID>(N, dist, Z2); break; case METHOD_VECTOR_MEDIAN: generic_linkage_vector_alternative<METHOD_METR_MEDIAN>(N, dist, Z2); break; default: throw std::runtime_error(std::string("Invalid method.")); } X.free(); // Free the memory now members.free(); // (not strictly necessary). dist.postprocess(Z2); SEXP m; // return field "merge" PROTECT(m = NEW_INTEGER(2*(N-1))); int * const merge = INTEGER_POINTER(m); SEXP dim_m; // Specify that m is an (N-1)×2 matrix PROTECT(dim_m = NEW_INTEGER(2)); INTEGER(dim_m)[0] = N-1; INTEGER(dim_m)[1] = 2; SET_DIM(m, dim_m); SEXP h; // return field "height" PROTECT(h = NEW_NUMERIC(N-1)); double * const height = NUMERIC_POINTER(h); SEXP o; // return fiels "order' PROTECT(o = NEW_INTEGER(N)); int * const order = INTEGER_POINTER(o); if (method==METHOD_VECTOR_SINGLE) generate_R_dendrogram<false>(merge, height, order, Z2, N); else generate_R_dendrogram<true>(merge, height, order, Z2, N); SEXP n; // names PROTECT(n = NEW_CHARACTER(3)); SET_STRING_ELT(n, 0, COPY_TO_USER_STRING("merge")); SET_STRING_ELT(n, 1, COPY_TO_USER_STRING("height")); SET_STRING_ELT(n, 2, COPY_TO_USER_STRING("order")); PROTECT(r = NEW_LIST(3)); // field names in the output list SET_ELEMENT(r, 0, m); SET_ELEMENT(r, 1, h); SET_ELEMENT(r, 2, o); SET_NAMES(r, n); UNPROTECT(6); // m, dim_m, h, o, r, n } // try catch (const std::bad_alloc&) { Rf_error( "Memory overflow."); } catch(const std::exception& e){ Rf_error( e.what() ); } catch(const nan_error&){ Rf_error("NaN dissimilarity value."); } catch(...){ Rf_error( "C++ exception (unknown reason)." ); } return r; }
inline void ReformHermitianMatrix ( UpperOrLower uplo, DistMatrix<R,MC,MR>& A, const DistMatrix<R,VR,STAR>& w, const DistMatrix<R,MC,MR>& Z, const RealFunctor& f ) { #ifndef RELEASE PushCallStack("hermitian_function::ReformHermitianMatrix"); #endif const Grid& g = A.Grid(); DistMatrix<R,MC,MR> ZL(g), ZR(g), Z0(g), Z1(g), Z2(g); DistMatrix<R,VR,STAR> wT(g), w0(g), wB(g), w1(g), w2(g); DistMatrix<R,MC, STAR> Z1_MC_STAR(g); DistMatrix<R,VR, STAR> Z1_VR_STAR(g); DistMatrix<R,STAR,MR > Z1Trans_STAR_MR(g); DistMatrix<R,STAR,STAR> w1_STAR_STAR(g); if( uplo == LOWER ) MakeTrapezoidal( LEFT, UPPER, 1, A ); else MakeTrapezoidal( LEFT, LOWER, -1, A ); LockedPartitionRight( Z, ZL, ZR, 0 ); LockedPartitionDown ( w, wT, wB, 0 ); while( ZL.Width() < Z.Width() ) { LockedRepartitionRight ( ZL, /**/ ZR, Z0, /**/ Z1, Z2 ); LockedRepartitionDown ( wT, w0, /**/ /**/ w1, wB, w2 ); Z1_MC_STAR.AlignWith( A ); Z1_VR_STAR.AlignWith( A ); Z1Trans_STAR_MR.AlignWith( A ); //--------------------------------------------------------------------// Z1_MC_STAR = Z1; Z1_VR_STAR = Z1_MC_STAR; w1_STAR_STAR = w1; // Scale Z1[VR,* ] with the modified eigenvalues const int width = Z1_VR_STAR.Width(); const int localHeight = Z1_VR_STAR.LocalHeight(); for( int j=0; j<width; ++j ) { const R omega = f(w1_STAR_STAR.GetLocalEntry(j,0)); R* buffer = Z1_VR_STAR.LocalBuffer(0,j); for( int iLocal=0; iLocal<localHeight; ++iLocal ) buffer[iLocal] *= omega; } Z1Trans_STAR_MR.TransposeFrom( Z1_VR_STAR ); internal::LocalTrrk( uplo, (R)1, Z1_MC_STAR, Z1Trans_STAR_MR, (R)1, A ); //--------------------------------------------------------------------// Z1Trans_STAR_MR.FreeAlignments(); Z1_VR_STAR.FreeAlignments(); Z1_MC_STAR.FreeAlignments(); SlideLockedPartitionDown ( wT, w0, w1, /**/ /**/ wB, w2 ); SlideLockedPartitionRight ( ZL, /**/ ZR, Z0, Z1, /**/ Z2 ); } #ifndef RELEASE PopCallStack(); #endif }
inline void ReformNormalMatrix ( DistMatrix<Complex<R>,MC,MR >& A, const DistMatrix<R, VR,STAR>& w, const DistMatrix<Complex<R>,MC,MR >& Z, const ComplexFunctor& f ) { #ifndef RELEASE PushCallStack("hermitian_function::ReformNormalMatrix"); #endif const Grid& g = A.Grid(); typedef Complex<R> C; DistMatrix<C,MC,MR> ZL(g), ZR(g), Z0(g), Z1(g), Z2(g); DistMatrix<R,VR,STAR> wT(g), w0(g), wB(g), w1(g), w2(g); DistMatrix<C,MC, STAR> Z1_MC_STAR(g); DistMatrix<C,VR, STAR> Z1_VR_STAR(g); DistMatrix<C,STAR,MR > Z1Adj_STAR_MR(g); DistMatrix<R,STAR,STAR> w1_STAR_STAR(g); Zero( A ); LockedPartitionRight( Z, ZL, ZR, 0 ); LockedPartitionDown ( w, wT, wB, 0 ); while( ZL.Width() < Z.Width() ) { LockedRepartitionRight ( ZL, /**/ ZR, Z0, /**/ Z1, Z2 ); LockedRepartitionDown ( wT, w0, /**/ /**/ w1, wB, w2 ); Z1_MC_STAR.AlignWith( A ); Z1_VR_STAR.AlignWith( A ); Z1Adj_STAR_MR.AlignWith( A ); //--------------------------------------------------------------------// Z1_MC_STAR = Z1; Z1_VR_STAR = Z1_MC_STAR; w1_STAR_STAR = w1; // Scale Z1[VR,* ] with the modified eigenvalues const int width = Z1_VR_STAR.Width(); const int localHeight = Z1_VR_STAR.LocalHeight(); for( int j=0; j<width; ++j ) { const C conjOmega = Conj(f(w1_STAR_STAR.GetLocalEntry(j,0))); C* buffer = Z1_VR_STAR.LocalBuffer(0,j); for( int iLocal=0; iLocal<localHeight; ++iLocal ) buffer[iLocal] *= conjOmega; } Z1Adj_STAR_MR.AdjointFrom( Z1_VR_STAR ); internal::LocalGemm ( NORMAL, NORMAL, (C)1, Z1_MC_STAR, Z1Adj_STAR_MR, (C)1, A ); //--------------------------------------------------------------------// Z1Adj_STAR_MR.FreeAlignments(); Z1_VR_STAR.FreeAlignments(); Z1_MC_STAR.FreeAlignments(); SlideLockedPartitionDown ( wT, w0, w1, /**/ /**/ wB, w2 ); SlideLockedPartitionRight ( ZL, /**/ ZR, Z0, Z1, /**/ Z2 ); } #ifndef RELEASE PopCallStack(); #endif }
inline void HermitianFromEVD ( UpperOrLower uplo, DistMatrix<F>& A, const DistMatrix<BASE(F),VR,STAR>& w, const DistMatrix<F>& Z ) { #ifndef RELEASE CallStackEntry entry("HermitianFromEVD"); #endif const Grid& g = A.Grid(); typedef BASE(F) R; DistMatrix<F> ZL(g), ZR(g), Z0(g), Z1(g), Z2(g); DistMatrix<R,VR,STAR> wT(g), w0(g), wB(g), w1(g), w2(g); DistMatrix<F,MC, STAR> Z1_MC_STAR(g); DistMatrix<F,VR, STAR> Z1_VR_STAR(g); DistMatrix<F,STAR,MR > Z1Adj_STAR_MR(g); DistMatrix<R,STAR,STAR> w1_STAR_STAR(g); A.ResizeTo( Z.Height(), Z.Height() ); if( uplo == LOWER ) MakeTrapezoidal( UPPER, A, 1 ); else MakeTrapezoidal( LOWER, A, -1 ); LockedPartitionRight( Z, ZL, ZR, 0 ); LockedPartitionDown ( w, wT, wB, 0 ); while( ZL.Width() < Z.Width() ) { LockedRepartitionRight ( ZL, /**/ ZR, Z0, /**/ Z1, Z2 ); LockedRepartitionDown ( wT, w0, /**/ /**/ w1, wB, w2 ); Z1_MC_STAR.AlignWith( A ); Z1_VR_STAR.AlignWith( A ); Z1Adj_STAR_MR.AlignWith( A ); //--------------------------------------------------------------------// Z1_MC_STAR = Z1; Z1_VR_STAR = Z1_MC_STAR; w1_STAR_STAR = w1; DiagonalScale( RIGHT, NORMAL, w1_STAR_STAR, Z1_VR_STAR ); Z1Adj_STAR_MR.AdjointFrom( Z1_VR_STAR ); LocalTrrk( uplo, F(1), Z1_MC_STAR, Z1Adj_STAR_MR, F(1), A ); //--------------------------------------------------------------------// SlideLockedPartitionDown ( wT, w0, w1, /**/ /**/ wB, w2 ); SlideLockedPartitionRight ( ZL, /**/ ZR, Z0, Z1, /**/ Z2 ); } }
void VideoFluids::trackVelocity(Matrix& Zn1,Matrix& Zn,Matrix& U,Matrix& V) { Matrix Zx(height,width),Zy(height,width),ZZx(height,width),ZZy(height,width),Zt(height,width),ZZt(height,width),ZZtx(height,width),ZZty(height,width); Matrix Au1(height,width),Au2(height,width),Av1(height,width),Av2(height,width); Matrix Z2x(height,width),Z2y(height,width),Z2(height,width); Matrix Cu(height,width),Cv(height,width); Matrix tmp(height,width),tmp1(height,width); Matrix U_old(height,width),V_old(height,width),Ux(height,width),Uy(height,width),Vx(height,width),Vy(height,width),Uax(height,width),Uay(height,width),Vax(height,width),Vay(height,width),Uxy(height,width),Vxy(height,width); Matrix Coe(height,width); Zt = Zn; Zt -= Zn1; DotMul(Zn,Zt,ZZt); Zn.output("Zn.txt"); Zn1.output("Zn1.txt"); Zt.output("Zt.txt"); Partial(ZZt,ZZtx,AXIS_X); Partial(ZZt,ZZty,AXIS_Y); Partial(Zn,Zx,AXIS_X); Partial(Zn,Zy,AXIS_Y); DotMul(Zn,Zx,ZZx); DotMul(Zn,Zy,ZZy); DotMul(Zx,Zx,Au1); Partial(ZZx,tmp,AXIS_X); Au1-=tmp; DotMul(Zn,Zn,tmp); Au1+=tmp; Au1+=2*alpha*alpha; DotMul(Zx,Zy,Au2); Partial(ZZy,tmp,AXIS_X); Au2-=tmp; DotMul(Zx,Zy,Av1); Partial(ZZx,tmp,AXIS_Y); Av1-=tmp; DotMul(Zy,Zy,Av2); Partial(ZZy,tmp,AXIS_Y); Av2-=tmp; DotMul(Zn,Zn,tmp); Av2+=tmp; Av2+=2*alpha*alpha; DotMul(Zn,Zn,Z2); Partial(Z2,Z2x,AXIS_X); Partial(Z2,Z2y,AXIS_Y); for (int i = 0;i<height;i++) for (int j = 0;j<width;j++) Coe[i][j] = 1.0/(Au1[i][j]*Av2[i][j]-Au2[i][j]*Av1[i][j]); U = 0.0; V = 0.0; for (int iter_time = 0;iter_time<iterationTime;iter_time++) { V_old = V; U_old = U; Partial(U,Ux,AXIS_X); Partial(U,Uy,AXIS_Y); Partial(V,Vx,AXIS_X); Partial(V,Vy,AXIS_Y); Partial(Vx,Vxy,AXIS_Y); Partial(Ux,Uxy,AXIS_Y); Average(U,Uax,AXIS_X); Average(U,Uay,AXIS_Y); Average(V,Vax,AXIS_X); Average(V,Vay,AXIS_Y); DotMul(Z2x,Ux,Cu); DotMul(ZZy,Vx,tmp); Cu += tmp; tmp = ZZx*-1; tmp+=Z2x; DotMul(tmp,Vy,tmp1); Cu+=tmp1; tmp = Z2; tmp+=alpha*alpha; DotMul(tmp,Uax,tmp1); Cu+=tmp1; tmp1=Uay; tmp1*=alpha*alpha; Cu+=tmp1; DotMul(Z2,Vxy,tmp1); Cu+=tmp1; DotMul(Zx,Zt,tmp); Cu-=tmp; Cu+=ZZtx; DotMul(Z2y,Vy,Cv); DotMul(ZZx,Uy,tmp); Cv += tmp; tmp = ZZy; tmp*=-1; tmp+=Z2y; DotMul(tmp,Ux,tmp1); Cv+=tmp1; tmp = Z2; tmp+=alpha*alpha; DotMul(tmp,Vay,tmp1); Cv+=tmp1; tmp1=Vax; tmp1*=alpha*alpha; Cv+=tmp1; DotMul(Z2,Uxy,tmp1); Cv+=tmp1; DotMul(Zy,Zt,tmp); Cv-=tmp; Cv+=ZZty; for (int i = 0;i<height;i++) for (int j = 0;j<width;j++) { U[i][j] = Coe[i][j]*(Av2[i][j]*Cu[i][j]-Au2[i][j]*Cv[i][j]); V[i][j] = Coe[i][j]*(-Av1[i][j]*Cu[i][j]+Au1[i][j]*Cv[i][j]); } for (int i = 0;i<height;i++) { U[i][0] = U[i][1]; U[i][width-1] = U[i][width-2]; V[i][0] = V[i][1]; V[i][width-1] =V[i][width-2]; } for (int i = 0;i<width;i++) { U[0][i] = U[1][i]; U[height-1][i] = U[height-2][i]; V[0][i] = V[1][i]; V[height-1][i] =V[height-2][i]; } FILE* fp; // Au1.output("Au1.txt"); // Au2.output("Au2.txt"); // Av1.output("Av1.txt"); // Av2.output("Av2.txt"); // Cu.output("Cu.txt"); // Cv.output("Cv.txt"); float d1 = Difference(U,U_old); float d2 = Difference(V,V_old); // U.output("U.txt"); // U_old.output("U_old.txt"); // V.output("V.txt"); cout<<d1<<' '<<d2<<endl; if (d1<iterationTorlerance && d2<iterationTorlerance) break; } U.output("U.txt"); cv::Mat showV(height,width,CV_8UC3); float lowv=10000000,lowu=10000000,highu=-10000000,highv=-1000000; for(int j=0;j<height;j++){ for(int k=0;k<width;k++){ if(U[j][k]>highu) highu=U[j][k]; if(U[j][k]<lowu) lowu=U[j][k]; if(V[j][k]>highv) highv=V[j][k]; if(V[j][k]<lowv) lowv=V[j][k]; } } for(int j=0;j<height;j++){ for(int k=0;k<width;k++){ //printf("%d %d\n",j,k); //if(sfs_list[i][j][k]<low) // showH.at<uchar>(j,k)=0; //else float u=(U[j][k]-lowu)/(highu-lowu); float v=(V[j][k]-lowv)/(highv-lowv); if(u>0.5) showV.at<cv::Vec3b>(j,k)[2]=255; else showV.at<cv::Vec3b>(j,k)[2]=255*u; if(v>0.5){ showV.at<cv::Vec3b>(j,k)[0]=255; showV.at<cv::Vec3b>(j,k)[1]=255*(1-v); } else{ showV.at<cv::Vec3b>(j,k)[1]=255; showV.at<cv::Vec3b>(j,k)[0]=255*v; } } } cv::imwrite("testV.bmp",showV); printf("show you"); }
int main() { read_pars("input"); read_ensemble_pars(base_path,T,ibeta,nmass,mass,iml_un,nlights,data_list_file); TH=L=T/2; int ncombo=nmass*nmass; //load all the corrs double *buf=new double[4*ncombo*T*(njack+1)]; FILE *fin=open_file(combine("%s/%s",base_path,corr_name).c_str(),"r"); int stat=fread(buf,sizeof(double),4*ncombo*(njack+1)*T,fin); if(stat!=4*ncombo*(njack+1)*T) { cerr<<"Error loading data!"<<endl; exit(1); } jvec M(ncombo,njack); jvec Z2(ncombo,njack); //define minuit staff TMinuit minu(2); minu.SetPrintLevel(-1); minu.SetFCN(chi2); corr_fit=new double[TH+1]; corr_err=new double[TH+1]; int ic=0; //fit each combo for(int ims=0;ims<nmass;ims++) for(int imc=0;imc<nmass;imc++) { int ic1=0+2*(imc+nmass*(0+2*ims)); int ic2=1+2*(imc+nmass*(1+2*ims)); printf("%d %d\n",ic1,ic2); //take into account corr jvec corr(T,njack); jvec corr1(T,njack); jvec corr2(T,njack); corr1.put(buf+ic1*T*(njack+1)); corr2.put(buf+ic2*T*(njack+1)); corr=(corr1+corr2)/2; //choose the index of the fitting interval if(ims>=nlights) ifit_int=2; else if(imc>=nlights) ifit_int=1; else ifit_int=0; //simmetrize corr=corr.simmetrized(parity); int ttmin=tmin[ifit_int]; int ttmax=tmax[ifit_int]; jvec Mcor=effective_mass(corr),Z2cor(TH+1,njack); jack Meff=constant_fit(Mcor,ttmin,ttmax); for(int t=0;t<=TH;t++) for(int ijack=0;ijack<=njack;ijack++) Z2cor[t].data[ijack]=corr[t].data[ijack]/fun_fit(1,Meff[ijack],t); jack Z2eff=constant_fit(Z2cor,ttmin,ttmax); if(!isnan(Z2eff[0])) minu.DefineParameter(0,"Z2",Z2eff[0],Z2eff.err(),0,2*Z2eff[0]); if(!isnan(Meff[0])) minu.DefineParameter(1,"M",Meff[0],Meff.err(),0,2*Meff[0]); for(int t=tmin[ifit_int];t<=tmax[ifit_int];t++) corr_err[t]=corr.data[t].err(); //jacknife analysis for(int ijack=0;ijack<njack+1;ijack++) { //copy data so that glob function may access it for(int t=tmin[ifit_int];t<=tmax[ifit_int];t++) corr_fit[t]=corr.data[t].data[ijack]; //fit double dum; minu.Migrad(); minu.GetParameter(0,Z2.data[ic].data[ijack],dum); minu.GetParameter(1,M.data[ic].data[ijack],dum); } //if((ims==iml_un||ims==nlights-1||ims==nlights||ims==nmass-1)&& //(imc==iml_un||imc==nlights-1||imc==nlights||imc==nmass-1)) { //plot eff mass { ofstream out(combine("eff_mass_plot_%02d_%02d.xmg",ims,imc).c_str()); out<<"@type xydy"<<endl; out<<"@s0 line type 0"<<endl; out<<Mcor<<endl; out<<"&"<<endl; out<<"@type xy"<<endl; double av_mass=M[ic].med(); double er_mass=M[ic].err(); out<<tmin[ifit_int]<<" "<<av_mass-er_mass<<endl; out<<tmax[ifit_int]<<" "<<av_mass-er_mass<<endl; out<<tmax[ifit_int]<<" "<<av_mass+er_mass<<endl; out<<tmin[ifit_int]<<" "<<av_mass+er_mass<<endl; out<<tmin[ifit_int]<<" "<<av_mass-er_mass<<endl; } //plot fun { ofstream out(combine("fun_plot_%02d_%02d.xmg",ims,imc).c_str()); out<<"@type xydy"<<endl; out<<"@s0 line type 0"<<endl; out<<corr<<endl; out<<"&"<<endl; out<<"@type xy"<<endl; for(int t=tmin[ifit_int];t<tmax[ifit_int];t++) out<<t<<" "<<fun_fit(Z2[ic][njack],M[ic][njack],t)<<endl; } } cout<<mass[ims]<<" "<<mass[imc]<<" "<<M[ic]<<" "<<Z2[ic]<<" "<<sqrt(Z2[ic])/(sinh(M[ic])*M[ic])*(mass[ims]+mass[imc])<<endl; ic++; } ofstream out("fitted_mass.xmg"); out<<"@type xydy"<<endl; for(int ims=0;ims<nmass;ims++) { //out<<"s0 line type 0"<<endl; for(int imc=0;imc<nmass;imc++) { int ic=imc+nmass*ims; out<<mass[imc]<<" "<<M[ic]<<endl; } out<<"&"<<endl; } M.write_to_binfile(out_file); Z2.append_to_binfile(out_file); return 0; }
int main() { // Patients (n), attributes (p), iterations in solving DP (N1), iterations in estimation of ratio (N2); int p = 45; int n = 50; int N1 = 250; int N2 = 250; std::mt19937 generator1 (61245); std::mt19937 generator2 (16746); std::mt19937 generator3 (27351); std::mt19937 generator4 (66459); std::mt19937 generator5 (12612); std::mt19937 generator6 (16326); std::mt19937 generator7 (86733); std::normal_distribution <double> nd(0.0, 1.0); std::chi_squared_distribution <double> xs(p - 2); //R is Cholesky factorization of Covar matrix //mu is vector of patient attribute means Eigen::MatrixXd s(p-1,p-1); Eigen::MatrixXd si(p-1,p-1); Eigen::MatrixXd zee(n,p-1); Eigen::MatrixXd Z(n,p-1); Eigen::MatrixXd Z2(n,p); //Update mu as necessary Eigen::VectorXd mu = Eigen::VectorXd::Zero(p-1); //Generates matrix of standard normals, then uses cholesky factorization to get correct covar matrix for (int i = 0; i < n; i++){ for (int j = 0; j < p-1; j++){ zee(i,j) = nd(generator1); } } for (int i = 0; i < p-1; i++){ for (int j = 0; j < p-1; j++){ if (i==j) { s(i,j) = 1.0; } else { s(i,j) = 0.1; } } } si = s.inverse(); Eigen::LLT<Eigen::MatrixXd> lltOfS(s); Eigen::MatrixXd R = lltOfS.matrixL(); double temp = 0; //Z2 is matrix of patient attributes (n x p) Z = zee*R; for (int i = 0; i < n; i++){ for (int j = 0; j < p; j++){ if(j > 0){ Z2(i,j) = Z(i,j-1) + mu(j-1); } else{ Z2(i,j) = 1; } } } //Eta + Xi computation double eta1 [N1]; double xi1 [N1]; double eta2 [N1]; double xi2 [N1]; for (int i = 0; i < N1; i++){ eta1[i] = nd(generator3)+2; xi1[i] = xs(generator4); eta2[i] = nd(generator6)-2; xi2[i] = xs(generator7); } //Solving 2-D DP using mesh double M = 2000.0; double delta = 0.2; int steps = ceil(M/delta)+1; DP table(n, delta, M); //syntax helpers double lambda = 0; int m = 0; double lambda_up = 0; double lambda_down = 0; double roundup_plus = 0; double rounddown_plus = 0; double roundup_minus = 0; double rounddown_minus = 0; double distdown_minus = 0; double distup_minus = 0; double distdown_plus = 0; double distup_plus = 0; double plus = 0; double minus = 0; double plus2 = 0; double minus2 = 0; int screwups = 0; //Boundary condition for (int i = 0; i < 2*n + 1; i++){ for (int j = 0; j < steps;j++){ m = i-n; lambda = delta*j; table.set(0, i, j, pow(m, 2) + lambda); } } //Solving mesh for (int l = 1;l < n; l++){ std::cout << l << "\n"; for (int i = l; i < 2*n+1-l; i++){ //under my indexing, l + k = n m = i-n; for (int j = 0; j < steps; j++){ lambda = delta*j; temp = 0; for (int iter = 0; iter < N1; iter++){ lambda_up = pow(sqrt(lambda)+eta1[iter],2)+xi1[iter]; lambda_down = pow(sqrt(lambda)-eta1[iter],2)+xi1[iter]; if (lambda_down > M){ lambda_down = M; } if (lambda_up > M){ lambda_up = M; } roundup_plus = ceil(lambda_up/delta); rounddown_plus = floor(lambda_up/delta); distdown_plus = lambda_up - rounddown_plus*delta; distup_plus = roundup_plus*delta - lambda_up; roundup_minus = ceil(lambda_down/delta); rounddown_minus = floor(lambda_down/delta); distdown_minus = lambda_down - rounddown_minus*delta; distup_minus = roundup_minus*delta - lambda_down; try{ plus = (1/delta)*(distup_plus*table.at(l-1, i+1, rounddown_plus) + distdown_plus*table.at(l-1, i+1, roundup_plus)); minus = (1/delta)*(distup_minus*table.at(l-1,i-1,rounddown_minus) + distdown_minus*table.at(l-1,i-1,roundup_minus)); } catch (const std::out_of_range& e){ std::cout << "roundup/down_plus " << roundup_plus << ", " << rounddown_plus << "\n"; std::cout << "roundup/down_minus " << roundup_minus << ", " << rounddown_minus << "\n"; std::cout << "Line 151 \n"; return 0; } lambda_up = pow(sqrt(lambda)+eta2[iter],2)+xi2[iter]; lambda_down = pow(sqrt(lambda)-eta2[iter],2)+xi2[iter]; if (lambda_down > M){ lambda_down = M; } if (lambda_up > M){ lambda_up = M; } roundup_plus = ceil(lambda_up/delta); rounddown_plus = floor(lambda_up/delta); distdown_plus = lambda_up - rounddown_plus*delta; distup_plus = roundup_plus*delta - lambda_up; roundup_minus = ceil(lambda_down/delta); rounddown_minus = floor(lambda_down/delta); distdown_minus = lambda_down - rounddown_minus*delta; distup_minus = roundup_minus*delta - lambda_down; try{ plus += (1/delta)*(distup_plus*table.at(l-1, i+1, rounddown_plus) + distdown_plus*table.at(l-1, i+1, roundup_plus)); minus += (1/delta)*(distup_minus*table.at(l-1,i-1,rounddown_minus) + distdown_minus*table.at(l-1,i-1,roundup_minus)); } catch (const std::out_of_range& e){ std::cout << "roundup/down_plus " << roundup_plus << ", " << rounddown_plus << "\n"; std::cout << "roundup/down_minus " << roundup_minus << ", " << rounddown_minus << "\n"; std::cout << "Line 151 \n"; return 0; } temp = temp*iter/(iter+1) + std::min(plus,minus)/(iter+1); /*if(temp < 0){ std::cout << lambda_down << " " << lambda_up << "\n"; std::cout << distdown_plus << " " << distup_plus << "\n"; std::cout << distdown_minus << " " << distup_minus << "\n"; return 0; }*/ } try{ table.set(l,i,j,temp); } catch (const std::out_of_range& e){ std::cout << "(" << l << ", " << i << ", " << j <<") \n"; } } } } char result[ PATH_MAX ]; ssize_t count = readlink( "/proc/self/exe", result, PATH_MAX ); std::string name = std::string( result, (count > 0) ? count : 0); std::string extension = ".csv"; name.append(extension); std::ofstream outputFile; outputFile.open(name); //for (int l = 0; l < n; l++){ for (int l = 0; l < n; l++){ for (int i=0; i < 2*n+1;i++){ for (int j=0; j < 1; j++){ outputFile << table.at(l,i,j) << ", "; } //outputFile << "\n"; } outputFile << "\n"; } outputFile.close(); return 0; //Vs Naive random allocation //Eff = x^T P_Z x where x is allocations, P_Z = I - Z(Z^T Z)^(-1) Z^T Eigen::MatrixXd PZ; Eigen::MatrixXd I = Eigen::MatrixXd::Identity(n,n); Eigen::MatrixXd Z2I; //Generates matrix of standard normals, then uses cholesky factorization to get correct covar matrix //Vector of n/2 1's and -1's int rand_x[n]; for (int i = 0; i < n; i++){ rand_x[i] = -1 + 2*floor(2*i/n); } std::vector <int> myvector (rand_x, rand_x+n); Eigen::VectorXd random_x(n); Eigen::VectorXd dp_x(n); double eff_r = 0; double eff_dp = 0; double eff = 0; //Tracks variable Delta as in paper Eigen::VectorXd var_Delta(p-1); var_Delta.setZero(); Eigen::VectorXd var_Delta_up(p-1); Eigen::VectorXd var_Delta_down(p-1); Eigen::MatrixXd condition(n,n); //Used to prevent floating point problems int var_delta; double mahalanobis_plus = 0; double mahalanobis_minus = 0; //Eigen::EigenSolver<Eigen::MatrixXd> es; //Large loop to test policies for (int asdf = 0; asdf < N2; asdf++){ //std::cout << "asdf = " << asdf << "\n"; var_delta = n; var_Delta.setZero(); for (int i = 0; i < n; i++){ for (int j = 0; j < p-1; j++){ zee(i,j) = nd(generator1); } } //Z is matrix of patient attributes (n x p) Z = zee*R; for (int i = 0; i < n; i++){ for (int j = 0; j < p; j++){ if(j > 0){ Z2(i,j) = Z(i,j-1) + mu(j-1); } else{ Z2(i,j) = 1; } } } Z2I = Z2.transpose()*Z2; PZ = I - Z2*(Z2I.inverse())*Z2.transpose(); //es.compute(PZ, false); //temp = 0; //for (int i = 0; i < n; i++){ // if (temp > (double)(es.eigenvalues()(i,0).real())){ // temp = (double)(es.eigenvalues()(i,0).real()); // } //} //PZ = PZ + Eigen::MatrixXd::Identity(n,n)*temp; //This is where randomized sampling is done for (int i = 0; i < N1; i++){ std::random_shuffle ( myvector.begin(), myvector.end()); for (int j = 0; j < n; j++){ random_x(j) = myvector[j]; } temp = random_x.transpose() * PZ * random_x; eff_r = eff_r*i/(i+1) + temp/(i+1); } //This is where we do "optimal" sampling for (int i = 0; i < n; i++){ std::cout << Z2.block(i,1,1,p-1) << "\n"; var_Delta_up = var_Delta + Z2.block(i,1,1,p-1).transpose(); std::cout << var_Delta_up.transpose() << "\n"; var_Delta_down = var_Delta - Z2.block(i,1,1,p-1).transpose(); std::cout << var_Delta_down.transpose() << "\n"; mahalanobis_plus = var_Delta_up.transpose()*si*var_Delta_up; std::cout << mahalanobis_plus << "\n"; roundup_plus = ceil(mahalanobis_plus/delta); rounddown_plus = floor(mahalanobis_plus/delta ); distup_plus = roundup_plus*delta - mahalanobis_plus; distdown_plus = mahalanobis_plus - rounddown_plus*delta; //std::cout << var_delta << "\n"; //std::cout << rounddown_plus << " " << roundup_plus << "\n"; //std::cout << "(" << n-i-1 << "," << var_delta+1 << ", " << rounddown_plus << ") \n"; //std::cout << "plus done \n"; mahalanobis_minus = var_Delta_down.transpose()*si*var_Delta_down; roundup_minus = ceil(mahalanobis_minus/delta ); rounddown_minus = floor(mahalanobis_minus/delta); distup_minus = roundup_minus*delta - mahalanobis_minus; distdown_minus = mahalanobis_minus - rounddown_minus*delta; //std::cout << "(" << n-i-1 << "," << var_delta-1 << ", " << rounddown_plus << ") \n"; try{ plus = (1/delta)*(distup_plus*table.at(n-1-i,var_delta+1, rounddown_plus) + distdown_plus*table.at(n-1-i,var_delta+1,roundup_plus)); minus = (1/delta)*(distup_minus*table.at(n-1-i,var_delta-1, rounddown_minus) + distdown_minus*table.at(n-1-i,var_delta-1,roundup_minus)); if (minus > plus){ var_delta++; var_Delta = var_Delta_up; dp_x(i) = 1; } else{ var_delta--; var_Delta = var_Delta_down; dp_x(i) = -1; } } catch (const std::out_of_range& e){ std::cout << "mahalanobis_plus = " << mahalanobis_plus << "\n"; std::cout << "mahalanobis_minus = " << mahalanobis_minus << "\n"; std::cout << "distdown/up plus =" << distdown_plus << ", " << distup_plus << "\n"; std::cout << "distdown/up minus =" << distdown_minus << ", " << distup_minus << "\n"; std::cout << "line 273 \n"; std::cout << asdf << "\n"; screwups++; } std::cout << "Press any key to continue."; std::cin.get(); } eff_dp = dp_x.transpose()*PZ*dp_x; std::cout << eff_r << ", " << eff_dp << "\n"; temp += eff_dp/eff_r; eff = eff*asdf/(asdf+1) + (eff_dp/eff_r)/(asdf+1); } std::cout << temp/(N1-screwups) << "\n"; std::cout << "screwups = " << screwups << "\n"; std::cout << eff << "\n"; //std::cout << "\n" << PZ << "\n"; //std::cout << "\n" << eff_r << "\n \n" << eff_dp << "\n"; //std::cout << "\n" << dp_x << "\n \n" << dp_x.transpose()*PZ*dp_x; //Eigen::EigenSolver<Eigen::MatrixXd> es; //es.compute(PZ); //std::cout << "\n" << es.eigenvalues(); }
bool HClusterDlg::Run(vector<wxInt64>& clusters) { // NOTE input_data should be retrieved first!! // get input: weights (auto) weight = GetWeights(columns); double* pwdist = NULL; if (dist == 'e') { pwdist = DataUtils::getPairWiseDistance(input_data, weight, rows, columns, DataUtils::EuclideanDistance); } else { pwdist = DataUtils::getPairWiseDistance(input_data, weight, rows, columns, DataUtils::ManhattanDistance); } fastcluster::auto_array_ptr<t_index> members; if (htree != NULL) { delete[] htree; htree = NULL; } htree = new GdaNode[rows-1]; fastcluster::cluster_result Z2(rows-1); if (method == 's') { fastcluster::MST_linkage_core(rows, pwdist, Z2); } else if (method == 'w') { members.init(rows, 1); fastcluster::NN_chain_core<fastcluster::METHOD_METR_WARD, t_index>(rows, pwdist, members, Z2); } else if (method == 'm') { fastcluster::NN_chain_core<fastcluster::METHOD_METR_COMPLETE, t_index>(rows, pwdist, NULL, Z2); } else if (method == 'a') { members.init(rows, 1); fastcluster::NN_chain_core<fastcluster::METHOD_METR_AVERAGE, t_index>(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 <<endl; //cout << i<< ":" << htree[i].left << ", " << htree[i].right << ", " << htree[i].distance <<endl; htree[i].left = node1; htree[i].right = node2; htree[i].distance = Z2[i]->dist; } clusters.clear(); int* clusterid = new int[rows]; cutoffDistance = cuttree (rows, htree, n_cluster, clusterid); for (int i=0; i<rows; i++) { clusters.push_back(clusterid[i]+1); } delete[] clusterid; clusterid = NULL; return true; }