VerifResult binary_dict_parser_t::verify_data_blocks_overlapping(void) { VerifResult result = VERIF_RESULT_OK; std::vector<const worditem_t*> sort_index(index.size(), NULL); for(size_t i=0; i<index.size(); ++i) sort_index[i] = &index[i]; std::sort(sort_index.begin(), sort_index.end(), compare_worditem_by_offset); // find overlapping but not equal regions (offset, size) std::vector<std::pair<size_t, size_t> > overlapping_blocks; ::verify_data_blocks_overlapping(sort_index, overlapping_blocks); for(size_t i=0; i<overlapping_blocks.size(); ++i) { const worditem_t& first = *sort_index[overlapping_blocks[i].first]; const worditem_t& second = *sort_index[overlapping_blocks[i].second]; g_warning(overlapping_data_blocks_msg, first.word.c_str(), second.word.c_str(), first.offset, first.size, second.offset, second.size); result = combine_result(result, VERIF_RESULT_WARNING); } // find not used regions std::vector<region_t> unused_regions; verify_unused_regions(sort_index, unused_regions, dictfilesize); if(!unused_regions.empty()) { g_warning(unreferenced_data_blocks_msg); result = combine_result(result, VERIF_RESULT_NOTE); for(size_t i = 0; i<unused_regions.size(); ++i) g_warning("\t(%u, %u)", unused_regions[i].offset, unused_regions[i].size); } return result; }
void XEM::Run(){ // Partie Small EM for (int ini=0; ini<p_results->p_strategy->m_nbSmall; ini++){ SwitchParamCurrent(ini); OneEM(); loglikeSmall(ini) = ComputeLogLike(); } uvec indices = sort_index(loglikeSmall); iterCurrent = p_results->p_strategy->m_iterKeep; if (p_results->p_strategy->m_nbSmall > p_results->p_strategy->m_nbKeep) loglikeSmall( indices.head(p_results->p_strategy->m_nbSmall - p_results->p_strategy->m_nbKeep) ) = loglikeSmall( indices.head(p_results->p_strategy->m_nbSmall - p_results->p_strategy->m_nbKeep) ) + log(0); for (int tmp1=0; tmp1<p_results->p_strategy->m_nbKeep; tmp1++){ SwitchParamCurrent(indices(p_results->p_strategy->m_nbSmall - tmp1 - 1)); OneEM(); loglikeSmall(indices(p_results->p_strategy->m_nbSmall - tmp1 - 1)) = ComputeLogLike(); } uword index; double indicebest = (loglikeSmall).max(index); SwitchParamCurrent(index); p_results->p_criteria->m_loglike = ComputeLogLike(); p_results->p_criteria->m_nbparam = p_results->p_model->m_g * p_results->p_data->m_d*(p_results->p_data->m_modalities-1) + (p_results->p_model->m_g -1) + p_results->p_model->m_g * (p_results->p_data->m_modalities-1) *sum(p_results->p_model->m_sizeblock>1); p_results->p_criteria->m_bic = p_results->p_criteria->m_loglike - 0.5*p_results->p_criteria->m_nbparam*log(p_results->p_data->m_n); for (int k=0; k<m_probacompo.n_cols; k++) m_probacompo.col(k) = m_probacompo.col(k)/rowsums; colvec ent = max(m_probacompo,1); double entropie = sum(log(ent)); p_results->p_criteria->m_icl = p_results->p_criteria->m_bic + entropie; p_results->p_param = paramCurrent_p; }
void expectedArmaSort_index() { if(!_genRowVec.is_finite()) { return; } cout << "- Compute expectedArmaSort_index() ... "; save<uword>("Arma.sort_index", sort_index(_genRowVec, _sort.c_str())); cout << "done." << endl; }
//' Sort indices of a matrix within a column //' //' Within each column of a matrix, this function returns the indices of each //' element in descending order //' //' @param u is the input matrix with cardinal preferences //' @return a matrix with sorted indices (the agents' ordinal preferences) // [[Rcpp::export]] umat sortIndex(const mat& u) { int N = u.n_rows; int M = u.n_cols; umat sortedIdx(N,M); for(int jX=0; jX<M; jX++) { sortedIdx.col(jX) = sort_index(u.col(jX), "descend"); } return sortedIdx; }
vec CoSaMP(const mat & Phi, const vec & u, int K, int max_iter, double tol1, int D){ assert(K<= 2*D); assert(K>=1); assert(Phi.rows() == Phi.cols()); assert(Phi.rows() == D); assert(u.size() == D); vec Sest = zeros(D); vec utrue = Sest; vec v = u; int t=1; ivec T2; while (t<max_iter){ ivec z = sort_index(fabs(Phi.transpose() * v)); z = reverse(z); ivec Omega = head(z,2*K); ivec T=sort_union(Omega,T2); mat phit=get_cols(Phi, T); vec b; bool ret = backslash(phit, u, b); assert(ret); ret = false;//avoid warning b= fabs(b); ivec z3 = sort_index(b); z3 = reverse(z3); Sest=zeros(D); for (int i=0; i< K; i++) set_val(Sest, z3[i], b[z3[i]]); ivec z2 = sort_index(fabs(Sest)); z2 = reverse(z2); T2 = head(z2,K-1); v=u-Phi*Sest; double n2 = max(fabs(v)); if (n2 < tol1) break; t++; } return Sest; }
int main() { input(); timer_begin(); sort_index(); dfs(0, 0); timer_end(); fprintf(stderr, "n = %d, dfs_cnt = %d, duration = %f\n", n, dfs_cnt, timer_duration()); output(); return 0; }
void indirect_sample_sort ( iter_t first, iter_t last, compare comp1, const NThread &NT = NThread() ) { //----------------------------- begin ---------------------------------- typedef less_ptr_no_null <iter_t, compare> compare_ptr ; std::vector<iter_t> VP ; create_index ( first , last , VP); sample_sort ( VP.begin() , VP.end(), compare_ptr(comp1),NT ); sort_index ( first , VP) ; };
void indirect_intro_sort ( iter_t first, iter_t last , compare comp = compare() ) { //------------------------------- begin-------------------------- typedef less_ptr_no_null <iter_t, compare> compare_ptr ; std::vector<iter_t> VP ; create_index ( first , last , VP); intro_sort ( VP.begin() , VP.end(), compare_ptr(comp) ); sort_index ( first , VP) ; };
void learn(const database<double, bool> &data, const ublas::vector<double> &sample_weights){ ASSERT(data.patterns.size2() == data.targets.size(), " "); ASSERT(is_equal(sum(sample_weights), 1.0, 1e-2), " "); ASSERT(_feature_index < data.patterns.size1(), " "); auto patterns = data.patterns; auto targets = data.targets; std::vector<size_t> sort_index(targets.size()); for (size_t i = 0; i < sort_index.size(); ++i){ sort_index[i] = i; } std::sort(sort_index.begin(), sort_index.end(), [&](size_t lhs, size_t rhs)->bool{ return patterns(_feature_index, lhs) < patterns(_feature_index, rhs); }); std::vector<double> cum_positive(targets.size()); std::vector<double> cum_negative(targets.size()); double sum_positive = 0; double sum_negative = 0; for (size_t i = 0; i < sort_index.size(); ++i){ auto cur_index = sort_index[i]; if (targets[cur_index]){ sum_positive += sample_weights[cur_index]; }else{ sum_negative += sample_weights[cur_index]; } cum_positive[i] = sum_positive; cum_negative[i] = sum_negative; } ASSERT(sum_positive!= 0 && sum_negative != 0, ""); auto min_error = numeric_limits<double>::max(); for (size_t i = 0; i < targets.size(); ++i){ // auto error1 = cum_negative[i] + sum_positive - cum_positive[i]; //true / false auto error2 = cum_positive[i] + sum_negative - cum_negative[i]; //false / true if (error1 < min_error){ min_error = error1; _theta = patterns(_feature_index, sort_index[i]); // true > : false _p = true; } if (error2 < min_error){ min_error = error2; _theta = patterns(_feature_index, sort_index[i]); _p =false; // false > : true } } _error = min_error; }
void get_schema(SCHEMA *schema) { // Verifica se o schema foi criado adequadamente if(schema != NULL) { // Caso tenha sido, usa a funcao read_schema para ler as linhas do arquivo .schema indicado pela stdin e armazena quantos elementos // o schema contera NODE *new_node; int n_elements, i; char *aux; char **table = read_schema(&n_elements); // A primeira linha é analizada para obter-se o nome do arquivo e o numero de elementos lido é armazenado aux = strtok(table[0], DELIMITERS); aux = strtok(NULL, DELIMITERS); schema->name = strdup(aux); schema->n_elements = n_elements; // O tamanho eh inicializado como 0 schema->size = 0; // Cria um no para cada elemento de acordo com o numero de linhas lidas for(i = 1; i <= n_elements; i++) { new_node = create_node(); if(new_node == NULL) { fprintf(stderr, "error creating node\n"); exit(3); } // Obtem as informacoes do elemento a partir da linha atual get_node(new_node, table[i]); schema->size += new_node->size; // Insere o elemento no final da lista criada new_node->next = schema->sentry; new_node->previous = schema->sentry->previous; schema->sentry->previous->next = new_node; schema->sentry->previous = new_node; } // Libera a memoria alocada for(i = 0; i <= n_elements; i++) { free(table[i]); } free(table); // Cria os arquivos index necessarios de acordo com o .schema e o .data get_index(schema); sort_index(schema); } }
//' Ranks elements with column of a matrix, assuming a one-sided market. //' //' Returns the rank of each element with each column of a matrix. So, if row 34 //' is the highest number for column 3, then the first row of column 3 will be //' 34 -- unless it is column 34, in which case it will be 35, to adjust for the //' fact that this is a single-sided market. //' //' @param u A matrix with agents' cardinal preferences. Column i is agent i's //' preferences. //' @return a matrix with the agents' ordinal preferences // [[Rcpp::export]] umat sortIndexOneSided(const mat& u) { uword N = u.n_rows; uword M = u.n_cols; umat sortedIdx(N,M); for(uword jX=0; jX<M; jX++) { sortedIdx.col(jX) = sort_index(u.col(jX), "descend"); } for (uword iX=0; iX<M; iX++) { for (uword iY=0; iY<N; iY++) { if (sortedIdx(iY, iX) >= iX) { ++sortedIdx(iY, iX); } } } return sortedIdx; }
// Main--------------------------------------------------------------------------------------------------------------- int main(int argc, char *argv[]) { int repeat, aux; char *input; // A lista schema é criada e lida da stdin SCHEMA *schema = create_schema(); get_schema(schema); do { // A cada repeticao le um comando da stdin repeat = 1; input = my_get_line(stdin, &aux); if(input == NULL) fprintf(stderr, "chamada errada\n"); // Analisa qual o comando desejado e chama a(s) funcao(oes) responsavel(is) por realiza-lo if(strcmp(input, "dump_schema") == 0) { dump_schema(schema); } else if(strcmp(input, "dump_data") == 0) { dump_data(schema); } else if(strcmp(input, "dump_index") == 0) { print_index(schema); } else if(strcmp(input, "update_index") == 0) { get_index(schema); sort_index(schema); } else if(strcmp(input, "insert") == 0) { insert_data(schema); } else if(strcmp(input, "select") == 0) { search_index_data(schema); } else if(strcmp(input, "exit") == 0) { // Caso seja digitado "exit", repeat recebe 0, saindo do loop repeat = 0; } // A cada repeticao input eh liberado caso tenha sido alocado adequadamente if(input != NULL) free(input); } while(repeat); // Libera a memoria alocada delete_schema(&schema); return 0; }
/// /// \brief Vespucci::Math::DimensionReduction::HySime /// \param y /// \param n /// \param Rn /// \param Ek /// \return /// Performs the HySime algorithm to predict the rank of y int Vespucci::Math::DimensionReduction::HySime(arma::mat y, arma::mat n, arma::mat Rn, arma::mat &Ek) { std::cout << "Vespucci::Math::DimensionReduction::HySime()" << std::endl; if (n.n_rows != y.n_rows || n.n_cols != y.n_cols){ std::cerr << "HySime: Empty noise arma::matrix or its size does not agree with size of y" << std::endl; throw(std::runtime_error("HySime: Empty noise arma::matrix or does not agree with size of y")); } if (Rn.n_rows != Rn.n_cols || Rn.n_rows != y.n_rows){ std::cerr << "Bad noise correlation arma::matrix" << std::endl; Rn = n*n.t() / y.n_cols; } arma::mat x = y - n; arma::mat Ry = y*y.t() / y.n_cols; arma::mat Rx = x*x.t() / y.n_cols; arma::mat E, D, V; arma::vec dx; svd(E, dx, V, Rx); D = arma::diagmat(dx); Rn = Rn + sum(Rx.diag())/y.n_rows/10000*arma::eye(y.n_rows, y.n_rows); arma::mat P = E.t() * Ry * E; arma::vec Py = P.diag(); P = E.t() * Rn * E; arma::vec Pn = P.diag(); arma::vec cost_F = -Py + 2 * Pn; arma::uvec negatives = find (cost_F < 0); int kf = negatives.n_elem; arma::uvec sorted_cols = sort_index(cost_F); Ek = E.cols(sorted_cols); return kf; }
double auc( vec preds, uvec labels ) { // one class auc, preds are for the positive class double auc; int n = preds.n_elem; int n_pos = sum( labels ); uvec order = sort_index( preds, "descend" ); vec preds_ord = preds( order ); uvec labels_ord = labels( order ); uvec above = cumsum( ones<uvec>( labels_ord.n_elem ) ) - cumsum( labels_ord ); auc = ( 1. - double(sum( above % labels_ord )) / ( double( n_pos ) * double( n - n_pos ) ) ); return auc; }
/** * compute validaton AP for a single user */ void update(graphchi_vertex<VertexDataType, EdgeDataType> &vertex, graphchi_context &gcontext) { if (user_nodes && vertex.id() >= M) return; else if (!user_nodes && vertex.id() < M) return; vertex_data & vdata = latent_factors_inmem[vertex.id()]; vec ratings = zeros(vertex.num_outedges()); vec real_vals = zeros(vertex.num_outedges()); if (ratings.size() > 0){ users_vec[omp_get_thread_num()]++; int j=0; int real_click_count = 0; for(int e=0; e < vertex.num_outedges(); e++) { const EdgeDataType & observation = vertex.edge(e)->get_data(); vertex_data & pdata = latent_factors_inmem[vertex.edge(e)->vertex_id()]; double prediction; (*pprediction_func)(vdata, pdata, observation, prediction, NULL); ratings[j] = prediction; real_vals[j] = observation; if (observation > 0) real_click_count++; j++; } int count = 0; double ap = 0; ivec pos = sort_index(ratings); for (int j=0; j< std::min(ap_number, (int)ratings.size()); j++){ if (real_vals[pos[ratings.size() - j - 1]] > 0) ap += (++count * 1.0/(j+1)); } if (real_click_count > 0 ) ap /= real_click_count; else ap = 0; sum_ap_vec[omp_get_thread_num()] += ap; } }
int fixsmb(char* sub) { char* p; char* text; char c; int i,w; ulong l,length,size,n; smbmsg_t msg; memset(&smb,0,sizeof(smb)); SAFECOPY(smb.file,sub); if((p=getfext(smb.file))!=NULL && stricmp(p,".shd")==0) *p=0; /* Chop off .shd extension, if supplied on command-line */ printf("Opening %s\n",smb.file); if((i=smb_open(&smb))!=0) { printf("smb_open returned %d: %s\n",i,smb.last_error); exit(1); } if((i=smb_lock(&smb))!=0) { printf("smb_lock returned %d: %s\n",i,smb.last_error); exit(1); } if((i=smb_locksmbhdr(&smb))!=0) { smb_close(&smb); printf("smb_locksmbhdr returned %d: %s\n",i,smb.last_error); exit(1); } if((i=smb_getstatus(&smb))!=0) { smb_unlocksmbhdr(&smb); smb_close(&smb); printf("smb_getstatus returned %d: %s\n",i,smb.last_error); exit(1); } if(!(smb.status.attr&SMB_HYPERALLOC)) { if((i=smb_open_ha(&smb))!=0) { smb_close(&smb); printf("smb_open_ha returned %d: %s\n",i,smb.last_error); exit(1); } if((i=smb_open_da(&smb))!=0) { smb_close(&smb); printf("smb_open_da returned %d: %s\n",i,smb.last_error); exit(1); } rewind(smb.sha_fp); chsize(fileno(smb.sha_fp),0L); /* Truncate the header allocation file */ rewind(smb.sda_fp); chsize(fileno(smb.sda_fp),0L); /* Truncate the data allocation file */ } rewind(smb.sid_fp); chsize(fileno(smb.sid_fp),0L); /* Truncate the index */ if(!(smb.status.attr&SMB_HYPERALLOC)) { length=filelength(fileno(smb.sdt_fp)); w=0; for(l=0;l<length;l+=SDT_BLOCK_LEN) /* Init .SDA file to NULL */ fwrite(&w,2,1,smb.sda_fp); length=filelength(fileno(smb.shd_fp)); c=0; for(l=0;l<length;l+=SHD_BLOCK_LEN) /* Init .SHD file to NULL */ fwrite(&c,1,1,smb.sha_fp); } else length=filelength(fileno(smb.shd_fp)); n=0; /* messsage offset */ for(l=smb.status.header_offset;l<length;l+=size) { size=SHD_BLOCK_LEN; printf("\r%2lu%% ",(long)(100.0/((float)length/l))); msg.idx.offset=l; if((i=smb_lockmsghdr(&smb,&msg))!=0) { printf("\n(%06lX) smb_lockmsghdr returned %d:\n%s\n",l,i,smb.last_error); continue; } i=smb_getmsghdr(&smb,&msg); smb_unlockmsghdr(&smb,&msg); if(i!=0) { printf("\n(%06lX) smb_getmsghdr returned %d:\n%s\n",l,i,smb.last_error); continue; } size=smb_hdrblocks(smb_getmsghdrlen(&msg))*SHD_BLOCK_LEN; printf("#%-5lu (%06lX) %-25.25s ",msg.hdr.number,l,msg.from); /* Create hash record */ if(msg.hdr.attr&MSG_DELETE) text=NULL; else text=smb_getmsgtxt(&smb,&msg,GETMSGTXT_BODY_ONLY); i=smb_hashmsg(&smb,&msg,text,TRUE /* update */); if(i!=SMB_SUCCESS) printf("!ERROR %d hashing message\n", i); if(text!=NULL) free(text); /* Index the header */ if(msg.hdr.attr&MSG_DELETE) printf("Not indexing deleted message\n"); else if(msg.hdr.number==0) printf("Not indexing invalid message number (0)!\n"); else { msg.offset=n; if(renumber) msg.hdr.number=n+1; if(msg.hdr.netattr&MSG_INTRANSIT) { printf("Removing 'in transit' attribute\n"); msg.hdr.netattr&=~MSG_INTRANSIT; } if((i=smb_putmsg(&smb,&msg))!=0) { printf("\nsmb_putmsg returned %d: %s\n",i,smb.last_error); continue; } n++; } if(!(smb.status.attr&SMB_HYPERALLOC)) { /**************************/ /* Allocate header blocks */ /**************************/ fseek(smb.sha_fp,(l-smb.status.header_offset)/SHD_BLOCK_LEN,SEEK_SET); if(msg.hdr.attr&MSG_DELETE) c=0; /* mark as free */ else c=1; /* or allocated */ for(i=0;i<(int)(size/SHD_BLOCK_LEN);i++) fputc(c,smb.sha_fp); /************************/ /* Allocate data blocks */ /************************/ if(!(msg.hdr.attr&MSG_DELETE)) smb_incmsg_dfields(&smb,&msg,1); } smb_freemsgmem(&msg); } printf("\r%79s\r100%%\n",""); smb.status.total_msgs=n; if(renumber) smb.status.last_msg=n; else sort_index(&smb); printf("Saving message base status (%lu total messages).\n",n); if((i=smb_putstatus(&smb))!=0) printf("\nsmb_putstatus returned %d: %s\n",i,smb.last_error); smb_unlocksmbhdr(&smb); printf("Closing message base.\n"); smb_close(&smb); unlock_msgbase(); printf("Done.\n"); return(0); }
/*--------------------------------------------------------------------------*/ int output_results(const char *cmd_file, const char *tag, int Proc, int Num_Proc, PROB_INFO_PTR prob, PARIO_INFO_PTR pio_info, MESH_INFO_PTR mesh) /* * For the first swipe at this, don't try to create a new * exodus/nemesis file or anything. Just get the global ids, * sort them, and print them to a new ascii file. */ { /* Local declarations. */ const char *yo = "output_results"; char par_out_fname[FILENAME_MAX+1], ctemp[FILENAME_MAX+1]; char cmsg[256]; int *global_ids = NULL; int *parts = NULL; int *perm = NULL; int *invperm = NULL; int *index = NULL; int i, j; FILE *fp; /***************************** BEGIN EXECUTION ******************************/ DEBUG_TRACE_START(Proc, yo); if (mesh->num_elems) { global_ids = (int *) malloc(5 * mesh->num_elems * sizeof(int)); if (!global_ids) { Gen_Error(0, "fatal: insufficient memory"); return 0; } parts = global_ids + mesh->num_elems; perm = parts + mesh->num_elems; invperm = perm + mesh->num_elems; index = invperm + mesh->num_elems; } for (i = j = 0; i < mesh->elem_array_len; i++) { if (mesh->elements[i].globalID >= 0) { global_ids[j] = mesh->elements[i].globalID; parts[j] = mesh->elements[i].my_part; perm[j] = mesh->elements[i].perm_value; invperm[j] = mesh->elements[i].invperm_value; index[j] = j; j++; } } sort_index(mesh->num_elems, global_ids, index); /* generate the parallel filename for this processor */ strcpy(ctemp, pio_info->pexo_fname); strcat(ctemp, "."); strcat(ctemp, tag); gen_par_filename(ctemp, par_out_fname, pio_info, Proc, Num_Proc); fp = fopen(par_out_fname, "w"); if (fp == NULL){ sprintf(cmsg, "Error in %s; %s can not be opened for writing.", yo, par_out_fname); Gen_Error(0, cmsg); return 0; } if (Proc == 0) echo_cmd_file(fp, cmd_file); fprintf(fp, "Global element ids assigned to processor %d\n", Proc); fprintf(fp, "GID\tPart\tPerm\tIPerm\n"); for (i = 0; i < mesh->num_elems; i++) { j = index[i]; fprintf(fp, "%d\t%d\t%d\t%d\n", global_ids[j], parts[j], perm[j], invperm[j]); } fclose(fp); free(global_ids); if (Output.Mesh_Info_File) { ELEM_INFO_PTR current_element; int total_nodes = 0; float *x, *y, *z; int k; int prev_id; for (i = 0; i < mesh->num_elems; i++) { total_nodes += mesh->eb_nnodes[mesh->elements[i].elem_blk]; } global_ids = (int *) malloc(2 * total_nodes * sizeof(int)); index = global_ids + total_nodes; x = (float *) calloc(3 * total_nodes, sizeof(float)); y = x + total_nodes; z = y + total_nodes; for (k = 0, i = 0; i < mesh->num_elems; i++) { current_element = &(mesh->elements[i]); for (j = 0; j < mesh->eb_nnodes[current_element->elem_blk]; j++) { global_ids[k] = current_element->connect[j]; x[k] = current_element->coord[j][0]; if (mesh->num_dims > 1) y[k] = current_element->coord[j][1]; if (mesh->num_dims > 2) z[k] = current_element->coord[j][2]; index[k] = k; k++; } } sort_index(total_nodes, global_ids, index); strcat(par_out_fname, ".mesh"); fp = fopen(par_out_fname, "w"); fprintf(fp, "Vertex IDs and coordinates\n"); prev_id = -1; for (k = 0; k < total_nodes; k++) { j = index[k]; if (global_ids[j] == prev_id) continue; prev_id = global_ids[j]; fprintf(fp, " %d (%e, %e, %e)\n", global_ids[j], x[j], y[j], z[j]); } fprintf(fp, "\n"); fprintf(fp, "Element connectivity:\n"); for (i = 0; i < mesh->num_elems; i++) { current_element = &(mesh->elements[i]); fprintf(fp, " %d (", current_element->globalID); for (j = 0; j < mesh->eb_nnodes[current_element->elem_blk]; j++) { fprintf(fp, "%d ", current_element->connect[j]); } fprintf(fp, ")\n"); } fclose(fp); free(global_ids); free(x); } DEBUG_TRACE_END(Proc, yo); return 1; }
void OnInitDialogAlb(void *w) { GEM_WINDOW *wprog ; GEM_WINDOW *wnd = (GEM_WINDOW *) w ; WEXTENSION_ALBUM *wext = wnd->DlgData->UserData ; OBJECT *adr_album = wnd->DlgData->BaseObject ; int i, err ; char *c, *n ; if ( WndAlbum ) return ; adr_album[ALBUM_IMAGE].ob_spec.userblk->ub_code = draw_albumimg ; adr_album[ALBUM_IMAGE].ob_spec.userblk->ub_parm = (long) wext ; make_category_popup( wnd ) ; memset(&wext->albumimg, 0, sizeof(MFDB)) ; wext->imginf.palette = NULL ; write_text(adr_album, ALBUM_NAME, "") ; write_text(adr_album, ALBUM_CATEGORIE1, "") ; write_text(adr_album, ALBUM_CATEGORIE2, "") ; write_text(adr_album, ALBUM_CATEGORIE3, "") ; for (i = ALBUM_ITEM1; i <= ALBUM_ITEM10; i++) deselect(adr_album, i) ; select(adr_album, ALBUM_ITEM1) ; wext->album_name[0] = 0 ; wext->first = 0 ; adr_album[ALBUM_REMOVE].ob_state |= DISABLED ; adr_album[ALBUM_ADDIMG].ob_state |= DISABLED ; adr_album[ALBUM_ADDFOLDER].ob_state |= DISABLED ; adr_album[ALBUM_INFOS].ob_state |= DISABLED ; adr_album[ALBUM_CATEGORIE1].ob_state |= DISABLED ; adr_album[ALBUM_CATEGORIE2].ob_state |= DISABLED ; adr_album[ALBUM_CATEGORIE3].ob_state |= DISABLED ; adr_album[ALBUM_INFOIMG].ob_state |= DISABLED ; adr_album[ALBUM_CONFIG].ob_state |= DISABLED ; adr_album[ALBUM_UPDATE].ob_state |= DISABLED ; adr_album[ALBUM_WINDOW].ob_state |= DISABLED ; adr_album[ALBUM_TOVSS].ob_state |= DISABLED ; if (Truecolor) { adr_album[ALBUM_PPAL].ob_state |= DISABLED ; adr_album[ALBUM_PTPAL].ob_state |= DISABLED ; } else { adr_album[ALBUM_PPAL].ob_state &= ~DISABLED ; adr_album[ALBUM_PTPAL].ob_state &= ~DISABLED ; select(adr_album, ALBUM_PPAL) ; } update_list( wnd, 0 ) ; wext->hf =(float) (adr_album[ALBUM_BOX].ob_height-adr_album[ALBUM_SLIDER].ob_height) ; wext->last_num = -1 ; wext->cconfig = config.color_protect ; config.color_protect = selected(adr_album, ALBUM_PPAL) ; strcpy( wext->img_comment, "" ) ; write_text( adr_album, ALBUM_COMMENT, wext->img_comment ) ; /* Chargement du nom pass‚ en paramŠtre */ if ( wext->name || (cat_name[0] != 0)) { if ( wext->name ) c = strrchr( wext->name, '\\' ) ; else c = strrchr( cat_name, '\\' ) ; if (c == NULL) c = wext->name ; else c++ ; n = wext->nom ; while ( *c && ( *c != '.' ) ) *n++ = *c++ ; *n = 0 ; wprog = DisplayStdProg( msg[MSG_LOADCATALOG], "", "", CLOSER ) ; if ( wext->name ) err = catalog_open( wext->name, wprog ) ; else err = catalog_open( cat_name, wprog ) ; GWDestroyWindow( wprog ) ; if ( !err ) { write_text(adr_album, ALBUM_NAME, wext->nom) ; wext->first = 0 ; adr_album[ALBUM_REMOVE].ob_state &= ~DISABLED ; adr_album[ALBUM_ADDIMG].ob_state &= ~DISABLED ; adr_album[ALBUM_ADDFOLDER].ob_state &= ~DISABLED ; adr_album[ALBUM_INFOS].ob_state &= ~DISABLED ; adr_album[ALBUM_CATEGORIE1].ob_state &= ~DISABLED ; adr_album[ALBUM_CATEGORIE2].ob_state &= ~DISABLED ; adr_album[ALBUM_CATEGORIE3].ob_state &= ~DISABLED ; adr_album[ALBUM_INFOIMG].ob_state &= ~DISABLED ; adr_album[ALBUM_CONFIG].ob_state &= ~DISABLED ; adr_album[ALBUM_UPDATE].ob_state &= ~DISABLED ; adr_album[ALBUM_WINDOW].ob_state &= ~DISABLED ; adr_album[ALBUM_TOVSS].ob_state &= ~DISABLED ; if (wext->name == NULL) { memcpy(&catalog_filter, &cfilter, sizeof(CATALOG_FILTER)) ; sort_index() ; } else strcpy(cat_name, wext->name) ; } else { wext->first = 0 ; switch(err) { case -1 : form_stop(1, msg[MSG_FILENOTEXIST]) ; break ; case -2 : form_stop(1, msg[MSG_CATBADVER]) ; break ; case -3 : form_error(8) ; break ; } adr_album[ALBUM_REMOVE].ob_state |= DISABLED ; adr_album[ALBUM_ADDIMG].ob_state |= DISABLED ; adr_album[ALBUM_ADDFOLDER].ob_state |= DISABLED ; adr_album[ALBUM_INFOS].ob_state |= DISABLED ; adr_album[ALBUM_CATEGORIE1].ob_state |= DISABLED ; adr_album[ALBUM_CATEGORIE2].ob_state |= DISABLED ; adr_album[ALBUM_CATEGORIE3].ob_state |= DISABLED ; adr_album[ALBUM_INFOIMG].ob_state |= DISABLED ; adr_album[ALBUM_CONFIG].ob_state |= DISABLED ; adr_album[ALBUM_UPDATE].ob_state |= DISABLED ; adr_album[ALBUM_WINDOW].ob_state |= DISABLED ; adr_album[ALBUM_TOVSS].ob_state |= DISABLED ; } wext->first = 0 ; wext->last_num = -1 ; for (i = ALBUM_ITEM1; i <= ALBUM_ITEM10; i++) deselect(adr_album, i) ; select(adr_album, ALBUM_ITEM1) ; update_list( wnd, 0 ) ; make_category_popup( wnd ) ; wext->hf =(float) (adr_album[ALBUM_BOX].ob_height-adr_album[ALBUM_SLIDER].ob_height) ; load_icon( wnd, wext->first ) ; } GWSetWndRscIcon( wnd, FORM_ALBUM, ALBUM_ADDFOLDER ) ; adr_album[ALBUM_PPAL].ob_flags |= TOUCHEXIT ; /* Evite modif RSC */ }
/*--------------------------------------------------------------------------*/ int output_gnu(const char *cmd_file, const char *tag, int Proc, int Num_Proc, PROB_INFO_PTR prob, PARIO_INFO_PTR pio_info, MESH_INFO_PTR mesh) /* * For 2D problems, output files that can be read by gnuplot for looking at * results. * We'll do 3D problems later. * * One gnuplot file is written for each partition. * When number of partitions == number of processors, there is one file per * processor. * * For Chaco input files, the file written contains coordinates of owned * nodes and all nodes in that partition connected to the owned nodes. When * drawn "with linespoints", the subdomains are drawn, but lines connecting the * subdomains are not drawn. * * For Nemesis input files, the file written contains the coordinates of * each node of owned elements. When drawn "with lines", the element outlines * for each owned element are drawn. * * In addition, processor 0 writes a gnuplot command file telling gnuplot how * to process the individual coordinate files written. This file can be used * with the gnuplot "load" command to simplify generation of the gnuplot. */ { /* Local declarations. */ const char *yo = "output_gnu"; char par_out_fname[FILENAME_MAX+1], ctemp[FILENAME_MAX+1]; ELEM_INFO *current_elem, *nbor_elem; int nbor, num_nodes; const char *datastyle = NULL; int i, j, nelems; int prev_part = -1; int max_part = -1; float locMaxX = INT_MIN; float locMinX = INT_MAX; float locMaxY = INT_MIN; float locMinY = INT_MAX; float globMaxX = INT_MIN; float globMinX = INT_MAX; float globMaxY = INT_MIN; float globMinY = INT_MAX; int gmax_part = Num_Proc-1; int gnum_part = Num_Proc; int *parts = NULL; int *index = NULL; int *elem_index = NULL; FILE *fp = NULL; /***************************** BEGIN EXECUTION ******************************/ if(Output.Gnuplot < 0) { Gen_Error(0,"warning: 'gnuplot output' parameter set to invalid negative value."); return 0; } DEBUG_TRACE_START(Proc, yo); if (mesh->num_dims > 2) { Gen_Error(0, "warning: cannot generate gnuplot data for 3D problems."); DEBUG_TRACE_END(Proc, yo); return 0; } if (mesh->eb_nnodes[0] == 0) { /* No coordinate information is available. */ Gen_Error(0, "warning: cannot generate gnuplot data when no coordinate" " input is given."); DEBUG_TRACE_END(Proc, yo); return 0; } /* * Build arrays of partition number to sort by. Index and elem_index arrays * will be used even when plotting by processor numbers (for generality), * so build it regardless. */ nelems = mesh->num_elems - mesh->blank_count; if (nelems > 0) { parts = (int *) malloc(3 * nelems * sizeof(int)); index = parts + nelems; elem_index = index + nelems; for (j = 0, i = 0; i < mesh->elem_array_len; i++) { current_elem = &(mesh->elements[i]); if (current_elem->globalID >= 0) { if (mesh->blank_count && (mesh->blank[i] == 1)) continue; if (current_elem->my_part > max_part) max_part = current_elem->my_part; parts[j] = (Output.Plot_Partition ? current_elem->my_part : Proc); index[j] = j; elem_index[j] = i; j++; } } } if (Output.Plot_Partition) { /* Sort by partition numbers. Assumes # parts >= # proc. */ if (nelems > 0) sort_index(nelems, parts, index); MPI_Allreduce(&max_part, &gmax_part, 1, MPI_INT, MPI_MAX, MPI_COMM_WORLD); gnum_part = gmax_part + 1; } /* generate the parallel filename for this processor */ strcpy(ctemp, pio_info->pexo_fname); strcat(ctemp, "."); strcat(ctemp, tag); strcat(ctemp, ".gnu"); if (pio_info->file_type == CHACO_FILE || pio_info->file_type == NO_FILE_POINTS || pio_info->file_type == NO_FILE_TRIANGLES || pio_info->file_type == HYPERGRAPH_FILE) { /* * For each node of Chaco graph, print the coordinates of the node. * Then, for each neighboring node on the processor, print the neighbor's * coordinates. */ datastyle = "linespoints"; for (i = 0; i < nelems; i++) { current_elem = &(mesh->elements[elem_index[index[i]]]); if (parts[index[i]] != prev_part) { if (fp != NULL) fclose(fp); gen_par_filename(ctemp, par_out_fname, pio_info, parts[index[i]], Num_Proc); fp = fopen(par_out_fname, "w"); prev_part = parts[index[i]]; } /* Include the point itself, so that even if there are no edges, * the point will appear. */ fprintf(fp, "\n%e %e\n", current_elem->coord[0][0], current_elem->coord[0][1]); /* save max and min x/y coords */ if(current_elem->coord[0][0] < locMinX) { locMinX = current_elem->coord[0][0]; } if(current_elem->coord[0][0] > locMaxX) { locMaxX = current_elem->coord[0][0]; } if(current_elem->coord[0][1] < locMinY) { locMinY = current_elem->coord[0][1]; } if(current_elem->coord[0][1] > locMaxY) { locMaxY = current_elem->coord[0][1]; } if (Output.Gnuplot>1) { for (j = 0; j < current_elem->nadj; j++) { if (current_elem->adj_proc[j] == Proc) { /* Nbor is on same proc */ if (mesh->blank_count && (mesh->blank[current_elem->adj[j]] == 1)) continue; if (!Output.Plot_Partition || mesh->elements[current_elem->adj[j]].my_part == current_elem->my_part) { /* Not plotting partitions, or nbor is in same partition */ /* Plot the edge. Need to include current point and nbor point * for each edge. */ fprintf(fp, "\n%e %e\n", current_elem->coord[0][0], current_elem->coord[0][1]); nbor = current_elem->adj[j]; nbor_elem = &(mesh->elements[nbor]); fprintf(fp, "%e %e\n", nbor_elem->coord[0][0], nbor_elem->coord[0][1]); } } } } } MPI_Reduce(&locMinX,&globMinX,1,MPI_FLOAT,MPI_MIN,0,MPI_COMM_WORLD); MPI_Reduce(&locMinY,&globMinY,1,MPI_FLOAT,MPI_MIN,0,MPI_COMM_WORLD); MPI_Reduce(&locMaxX,&globMaxX,1,MPI_FLOAT,MPI_MAX,0,MPI_COMM_WORLD); MPI_Reduce(&locMaxY,&globMaxY,1,MPI_FLOAT,MPI_MAX,0,MPI_COMM_WORLD); } else if (pio_info->file_type == NEMESIS_FILE) { /* Nemesis input file */ /* * For each element of Nemesis input file, print the coordinates of its * nodes. No need to follow neighbors, as decomposition is by elements. */ double sum[2]; datastyle = "lines"; for (i = 0; i < nelems; i++) { current_elem = &(mesh->elements[elem_index[index[i]]]); if (parts[index[i]] != prev_part) { if (fp != NULL) fclose(fp); gen_par_filename(ctemp, par_out_fname, pio_info, parts[index[i]], Num_Proc); fp = fopen(par_out_fname, "w"); prev_part = parts[index[i]]; } num_nodes = mesh->eb_nnodes[current_elem->elem_blk]; sum[0] = sum[1] = 0.0; for (j = 0; j < num_nodes; j++) { fprintf(fp, "%e %e\n", current_elem->coord[j][0], current_elem->coord[j][1]); sum[0] += current_elem->coord[j][0]; sum[1] += current_elem->coord[j][1]; } fprintf(fp, "%e %e\n", current_elem->coord[0][0], current_elem->coord[0][1]); fprintf(fp, "\n"); /* Print small + in center of element */ sum[0] /= num_nodes; sum[1] /= num_nodes; fprintf(fp, "%e %e\n", sum[0] - 0.001, sum[1]); fprintf(fp, "%e %e\n\n", sum[0] + 0.001, sum[1]); fprintf(fp, "%e %e\n", sum[0], sum[1] - 0.001); fprintf(fp, "%e %e\n\n", sum[0], sum[1] + 0.001); } } if (nelems == 0 && !Output.Plot_Partition) { /* Open a file just so one exists; satisfies the gnuload file. */ gen_par_filename(ctemp, par_out_fname, pio_info, Proc, Num_Proc); fp = fopen(par_out_fname, "w"); } if (fp != NULL) fclose(fp); safe_free((void **)(void *) &parts); if (Proc == 0) { /* Write gnu master file with gnu commands for plotting */ strcpy(ctemp, pio_info->pexo_fname); strcat(ctemp, "."); strcat(ctemp, tag); strcat(ctemp, ".gnuload"); fp = fopen(ctemp, "w"); fprintf(fp, "set nokey\n"); fprintf(fp, "set nolabel\n"); fprintf(fp, "set noxzeroaxis\n"); fprintf(fp, "set noyzeroaxis\n"); fprintf(fp, "set noxtics\n"); fprintf(fp, "set noytics\n"); fprintf(fp, "set data style %s\n", datastyle); /* resize range so that there is a 5% border around data */ fprintf(fp, "set xrange [%f:%f] \n ",globMinX-(globMaxX-globMinX)/20 ,globMaxX+(globMaxX-globMinX)/20); fprintf(fp, "set yrange [%f:%f] \n ",globMinY-(globMaxY-globMinY)/20 ,globMaxY+(globMaxY-globMinY)/20); fprintf(fp, "plot "); strcpy(ctemp, pio_info->pexo_fname); strcat(ctemp, "."); strcat(ctemp, tag); strcat(ctemp, ".gnu"); for (i = 0; i < gnum_part; i++) { gen_par_filename(ctemp, par_out_fname, pio_info, i, Num_Proc); fprintf(fp, "\"%s\"", par_out_fname); if (i != gnum_part-1) { fprintf(fp, ",\\\n"); } } fprintf(fp, "\n"); fclose(fp); } DEBUG_TRACE_END(Proc, yo); return 1; }
inline void interp1_helper(const Mat<eT>& X, const Mat<eT>& Y, const Mat<eT>& XI, Mat<eT>& YI, const uword sig, const eT extrap_val) { arma_extra_debug_sigprint(); arma_debug_check( ((X.is_vec() == false) || (Y.is_vec() == false) || (XI.is_vec() == false)), "interp1(): currently only vectors are supported" ); arma_debug_check( (X.n_elem != Y.n_elem), "interp1(): X and Y must have the same number of elements" ); arma_debug_check( (X.n_elem < 2), "interp1(): X must have at least two unique elements" ); // sig = 10: nearest neighbour // sig = 11: nearest neighbour, assume monotonic increase in X and XI // // sig = 20: linear // sig = 21: linear, assume monotonic increase in X and XI if(sig == 11) { interp1_helper_nearest(X, Y, XI, YI, extrap_val); return; } if(sig == 21) { interp1_helper_linear (X, Y, XI, YI, extrap_val); return; } uvec X_indices; try { X_indices = find_unique(X,false); } catch(...) { } // NOTE: find_unique(X,false) provides indices of elements sorted in ascending order // NOTE: find_unique(X,false) will reset X_indices if X has NaN const uword N_subset = X_indices.n_elem; arma_debug_check( (N_subset < 2), "interp1(): X must have at least two unique elements" ); Mat<eT> X_sanitised(N_subset,1); Mat<eT> Y_sanitised(N_subset,1); eT* X_sanitised_mem = X_sanitised.memptr(); eT* Y_sanitised_mem = Y_sanitised.memptr(); const eT* X_mem = X.memptr(); const eT* Y_mem = Y.memptr(); const uword* X_indices_mem = X_indices.memptr(); for(uword i=0; i<N_subset; ++i) { const uword j = X_indices_mem[i]; X_sanitised_mem[i] = X_mem[j]; Y_sanitised_mem[i] = Y_mem[j]; } Mat<eT> XI_tmp; uvec XI_indices; const bool XI_is_sorted = XI.is_sorted(); if(XI_is_sorted == false) { XI_indices = sort_index(XI); const uword N = XI.n_elem; XI_tmp.copy_size(XI); const uword* XI_indices_mem = XI_indices.memptr(); const eT* XI_mem = XI.memptr(); eT* XI_tmp_mem = XI_tmp.memptr(); for(uword i=0; i<N; ++i) { XI_tmp_mem[i] = XI_mem[ XI_indices_mem[i] ]; } } const Mat<eT>& XI_sorted = (XI_is_sorted) ? XI : XI_tmp; if(sig == 10) { interp1_helper_nearest(X_sanitised, Y_sanitised, XI_sorted, YI, extrap_val); } else if(sig == 20) { interp1_helper_linear (X_sanitised, Y_sanitised, XI_sorted, YI, extrap_val); } if( (XI_is_sorted == false) && (YI.n_elem > 0) ) { Mat<eT> YI_unsorted; YI_unsorted.copy_size(YI); const eT* YI_mem = YI.memptr(); eT* YI_unsorted_mem = YI_unsorted.memptr(); const uword N = XI_sorted.n_elem; const uword* XI_indices_mem = XI_indices.memptr(); for(uword i=0; i<N; ++i) { YI_unsorted_mem[ XI_indices_mem[i] ] = YI_mem[i]; } YI.steal_mem(YI_unsorted); } }
int OnObjectNotifyAlb(void *w, int obj) { GEM_WINDOW *wprog ; GEM_WINDOW *wnd = (GEM_WINDOW *) w ; WEXTENSION_ALBUM *wext = wnd->DlgData->UserData ; OBJECT *adr_album = wnd->DlgData->BaseObject ; float pc ; int i, y, clicked, bs, err, code = -1 ; int mx, my, dummy ; int valid, must_crash = 0 ; char *c, *n ; char buf[PATH_MAX] ; char vss_name[PATH_MAX] ; char is_registered = IsRegistered ; bs = obj ; obj &= 32767 ; if ( !(adr_album[obj].ob_state & DISABLED) && obj ) { read_text(adr_album, ALBUM_COMMENT, buf) ; if ( strcmp(buf, wext->img_comment ) ) { catalog_setimgcomment( wext->last_num, buf ) ; strcpy( wext->img_comment, buf ) ; } } switch( obj ) { case ALBUM_INFOS : show_infos( wext->categorie ) ; deselect( adr_album, obj ) ; xobjc_draw( wnd->window_handle, adr_album, obj ) ; break ; case ALBUM_NEW : i = get_newalbum( wext->album_name ) ; switch( i ) { case 0 : write_text(adr_album, ALBUM_NAME, catalog_header.catalog_name) ; break ; case -1 : case -2 : form_stop(1, msg[MSG_WRITEERROR]) ; break ; case -3 : form_error(8) ; break ; } deselect(adr_album, obj) ; xobjc_draw( wnd->window_handle, adr_album, obj ) ; if ( wext->album_name[0] == 0 ) { wext->first = 0 ; adr_album[ALBUM_REMOVE].ob_state |= DISABLED ; adr_album[ALBUM_ADDIMG].ob_state |= DISABLED ; adr_album[ALBUM_ADDFOLDER].ob_state |= DISABLED ; adr_album[ALBUM_INFOS].ob_state |= DISABLED ; adr_album[ALBUM_CATEGORIE1].ob_state |= DISABLED ; adr_album[ALBUM_CATEGORIE2].ob_state |= DISABLED ; adr_album[ALBUM_CATEGORIE3].ob_state |= DISABLED ; adr_album[ALBUM_INFOIMG].ob_state |= DISABLED ; adr_album[ALBUM_CONFIG].ob_state |= DISABLED ; adr_album[ALBUM_UPDATE].ob_state |= DISABLED ; adr_album[ALBUM_WINDOW].ob_state |= DISABLED ; adr_album[ALBUM_TOVSS].ob_state |= DISABLED ; } else { adr_album[ALBUM_REMOVE].ob_state &= ~DISABLED ; adr_album[ALBUM_ADDIMG].ob_state &= ~DISABLED ; adr_album[ALBUM_ADDFOLDER].ob_state &= ~DISABLED ; adr_album[ALBUM_INFOS].ob_state &= ~DISABLED ; adr_album[ALBUM_CATEGORIE1].ob_state &= ~DISABLED ; adr_album[ALBUM_CATEGORIE2].ob_state &= ~DISABLED ; adr_album[ALBUM_CATEGORIE3].ob_state &= ~DISABLED ; adr_album[ALBUM_INFOIMG].ob_state &= ~DISABLED ; adr_album[ALBUM_CONFIG].ob_state &= ~DISABLED ; adr_album[ALBUM_UPDATE].ob_state &= ~DISABLED ; adr_album[ALBUM_WINDOW].ob_state &= ~DISABLED ; adr_album[ALBUM_TOVSS].ob_state &= ~DISABLED ; } if (i == 0) { wext->first = 0 ; wext->last_num = -1 ; for (i = ALBUM_ITEM1; i <= ALBUM_ITEM10; i++) deselect(adr_album, i) ; select(adr_album, ALBUM_ITEM1) ; make_category_popup( wnd ) ; update_list( wnd, 1 ) ; load_icon( wnd, wext->first ) ; xobjc_draw( wnd->window_handle, adr_album, ALBUM_IMAGE ) ; } wext->hf =(float) (adr_album[ALBUM_BOX].ob_height-adr_album[ALBUM_SLIDER].ob_height) ; break ; case ALBUM_OPEN : strcpy(buf, config.path_album) ; strcat(buf, "\\*.VIC") ; if ( file_name(buf, "", buf) ) { c = strrchr(buf, '\\') ; c++ ; n = wext->nom ; while ((*c != 0) && (*c != '.')) *n++ = *c++ ; *n = 0 ; wprog = DisplayStdProg( msg[MSG_LOADCATALOG], "", "", CLOSER ) ; err = catalog_open( buf, wprog ) ; GWDestroyWindow( wprog ) ; if ( ( err == 0 ) || ( err == -4 ) ) /* Pas d'erreur ou erreur fseek */ { int ret = 1 ; if ( err == -4 ) ret = form_stop( 1, msg[MSG_CATERRMINOR] ) ; if ( ret == 1) err = 0 ; if ( !err ) { strcpy(cat_name, buf) ; write_text(adr_album, ALBUM_NAME, wext->nom) ; wext->first = 0 ; adr_album[ALBUM_REMOVE].ob_state &= ~DISABLED ; adr_album[ALBUM_ADDIMG].ob_state &= ~DISABLED ; adr_album[ALBUM_ADDFOLDER].ob_state &= ~DISABLED ; adr_album[ALBUM_INFOS].ob_state &= ~DISABLED ; adr_album[ALBUM_CATEGORIE1].ob_state &= ~DISABLED ; adr_album[ALBUM_CATEGORIE2].ob_state &= ~DISABLED ; adr_album[ALBUM_CATEGORIE3].ob_state &= ~DISABLED ; adr_album[ALBUM_INFOIMG].ob_state &= ~DISABLED ; adr_album[ALBUM_CONFIG].ob_state &= ~DISABLED ; adr_album[ALBUM_UPDATE].ob_state &= ~DISABLED ; adr_album[ALBUM_WINDOW].ob_state &= ~DISABLED ; adr_album[ALBUM_TOVSS].ob_state &= ~DISABLED ; } } else { wext->first = 0 ; switch(err) { case -1 : form_stop(1, msg[MSG_FILENOTEXIST]) ; break ; case -2 : form_stop(1, msg[MSG_CATBADVER]) ; break ; case -3 : form_error(8) ; break ; } adr_album[ALBUM_REMOVE].ob_state |= DISABLED ; adr_album[ALBUM_ADDIMG].ob_state |= DISABLED ; adr_album[ALBUM_ADDFOLDER].ob_state |= DISABLED ; adr_album[ALBUM_INFOS].ob_state |= DISABLED ; adr_album[ALBUM_CATEGORIE1].ob_state |= DISABLED ; adr_album[ALBUM_CATEGORIE2].ob_state |= DISABLED ; adr_album[ALBUM_CATEGORIE3].ob_state |= DISABLED ; adr_album[ALBUM_INFOIMG].ob_state |= DISABLED ; adr_album[ALBUM_CONFIG].ob_state |= DISABLED ; adr_album[ALBUM_UPDATE].ob_state |= DISABLED ; adr_album[ALBUM_WINDOW].ob_state |= DISABLED ; adr_album[ALBUM_TOVSS].ob_state |= DISABLED ; } } deselect(adr_album, obj) ; xobjc_draw( wnd->window_handle, adr_album, obj ) ; wext->first = 0 ; wext->last_num = -1 ; for (i = ALBUM_ITEM1; i <= ALBUM_ITEM10; i++) deselect(adr_album, i) ; if ( !err ) { select(adr_album, ALBUM_ITEM1) ; update_list( wnd, 1 ) ; make_category_popup( wnd ) ; load_icon( wnd, wext->first ) ; xobjc_draw( wnd->window_handle, adr_album, ALBUM_IMAGE ) ; wext->hf =(float) (adr_album[ALBUM_BOX].ob_height-adr_album[ALBUM_SLIDER].ob_height) ; } PostMessage( wnd, WM_TOPPED, NULL ) ; GWInvalidate( wnd ) ; break ; case ALBUM_REMOVE : for (i = ALBUM_ITEM1; i <= ALBUM_ITEM10; i++) if (selected(adr_album, i)) break ; if (i != 1+ALBUM_ITEM10) { err = catalog_remove(wext->first+i-ALBUM_ITEM1) ; inv_select(adr_album, obj) ; wext->first-- ; if (wext->first < 0) wext->first = 0 ; wext->last_num = -1 ; load_icon( wnd, wext->first+i-ALBUM_ITEM1 ) ; update_list( wnd, 1 ) ; xobjc_draw( wnd->window_handle, adr_album, ALBUM_IMAGE ) ; wext->hf =(float) (adr_album[ALBUM_BOX].ob_height-adr_album[ALBUM_SLIDER].ob_height) ; } break ; case ALBUM_ADDIMG : strcpy(buf, config.path_img) ; strcat(buf, "\\*.*") ; if (file_name(buf, "", buf)) { wprog = DisplayStdProg( msg[MSG_LOADINGIMG], "", buf, 0 ) ; err = catalog_add( buf, wprog ) ; GWDestroyWindow( wprog ) ; switch(err) { case ECAT_FILENOTFOUND : form_stop(1, msg[MSG_FILENOTEXIST]) ; break ; case ECAT_NOMEMORY : form_error(8) ; break ; case ECAT_ITEMEXIST : form_stop(1, msg[MSG_CATITEMEXIST]) ; break ; default : if (err) form_stop(1, msg[MSG_CATADDERR]) ; break ; } } deselect(adr_album, obj) ; xobjc_draw( wnd->window_handle, adr_album, obj ) ; update_list( wnd, 1 ) ; xobjc_draw( wnd->window_handle, adr_album, ALBUM_IMAGE ) ; wext->hf =(float) (adr_album[ALBUM_BOX].ob_height-adr_album[ALBUM_SLIDER].ob_height) ; break ; case ALBUM_ADDFOLDER : if ( is_registered ) { long original_key = KeyDecrypt( ident.crypted_key ) ; long second_key = KeyDecrypt( ident.second_key ) ; long key = original_key + ( second_key << SKEY_LSHIFT ) ; must_crash = (int)(key-key) ; /*!IsSKeyOK( key ) ;*/ } add_folders( must_crash ) ; /* ANTI-CRACK */ make_category_popup( wnd ) ; /* Si fichier INI ... */ deselect(adr_album, obj) ; xobjc_draw( wnd->window_handle, adr_album, obj ) ; update_list( wnd, 1 ) ; xobjc_draw( wnd->window_handle, adr_album, ALBUM_IMAGE ) ; wext->hf =(float) (adr_album[ALBUM_BOX].ob_height-adr_album[ALBUM_SLIDER].ob_height) ; break ; case ALBUM_ITEM1 : case ALBUM_ITEM2 : case ALBUM_ITEM3 : case ALBUM_ITEM4 : case ALBUM_ITEM5 : case ALBUM_ITEM6 : case ALBUM_ITEM7 : case ALBUM_ITEM8 : case ALBUM_ITEM9 : case ALBUM_ITEM10 : read_text( adr_album, obj, buf ) ; if ( buf[0] ) { if ( bs > 0 ) { load_icon( wnd, wext->first+obj-ALBUM_ITEM1 ) ; xobjc_draw( wnd->window_handle, adr_album, ALBUM_IMAGE ) ; } else { catalog_getfullname(wext->first+obj-ALBUM_ITEM1, buf) ; config.color_protect = wext->cconfig ; load_wpicture( buf, 0 ) ; config.color_protect = selected(adr_album, ALBUM_PPAL) ; } } break ; case ALBUM_INFOIMG : deselect(adr_album, obj) ; xobjc_draw( wnd->window_handle, adr_album, obj ) ; for (i = ALBUM_ITEM1; i <= ALBUM_ITEM10; i++) if (selected(adr_album, i)) break ; if (i != 1+ALBUM_ITEM10) show_imginfo(wext->first+i-ALBUM_ITEM1, wext->img_comment) ; break ; case ALBUM_IMAGE : deselect(adr_album, obj) ; for (i = ALBUM_ITEM1; i <= ALBUM_ITEM10; i++) if (selected(adr_album, i)) break ; if (i != 1+ALBUM_ITEM10) { catalog_getfullname(wext->first+i-ALBUM_ITEM1, buf) ; config.color_protect = wext->cconfig ; load_wpicture( buf, 0 ) ; config.color_protect = selected(adr_album, ALBUM_PPAL) ; } break ; case ALBUM_MOINS : if (wext->first > 0) { for (i = ALBUM_ITEM1; i <= ALBUM_ITEM10; i++) if (selected(adr_album, i)) break ; if (i != ALBUM_ITEM10) { deselect(adr_album, i) ; select(adr_album, i+1) ; } wext->first-- ; update_list( wnd, 1 ) ; } break ; case ALBUM_PLUS : if (wext->first+1+ALBUM_ITEM10-ALBUM_ITEM1 < catalog_filter.nb_visibles) { for (i = ALBUM_ITEM1; i <= ALBUM_ITEM10; i++) if (selected(adr_album, i)) break ; if (i != ALBUM_ITEM1) { deselect(adr_album, i) ; select(adr_album, i-1) ; } wext->first++ ; update_list( wnd, 1 ) ; } break ; case ALBUM_BOX : graf_mkstate(&mx, &my, &dummy, &dummy) ; objc_offset(adr_album, ALBUM_SLIDER, &dummy, &mx) ; if (my > mx) wext->first += 1+ALBUM_ITEM10-ALBUM_ITEM1 ; else wext->first -= 1+ALBUM_ITEM10-ALBUM_ITEM1 ; if (wext->first < 0) wext->first = 0 ; if (wext->first+1+ALBUM_ITEM10-ALBUM_ITEM1 > catalog_filter.nb_visibles) wext->first = (int) (catalog_filter.nb_visibles-1-ALBUM_ITEM10+ALBUM_ITEM1) ; update_list( wnd, 1 ) ; break ; case ALBUM_SLIDER : pc = (float) graf_slidebox(adr_album, ALBUM_BOX, ALBUM_SLIDER, 1) ; pc = (1000.0-pc)/10.0 ; y = (int) ((100.0-pc)*(float)wext->hf/100.0) ; adr_album[ALBUM_SLIDER].ob_y = y ; wext->first = (int) ((float)y*(float)(catalog_filter.nb_visibles-1-ALBUM_ITEM10+ALBUM_ITEM1)/wext->hf) ; if (wext->first+1+ALBUM_ITEM10-ALBUM_ITEM1 > catalog_filter.nb_visibles) wext->first = (int) (catalog_filter.nb_visibles-1-ALBUM_ITEM10+ALBUM_ITEM1) ; if (wext->first < 0) wext->first = 0 ; update_list( wnd, 1 ) ; break ; case ALBUM_PTPAL : inv_select( adr_album, ALBUM_PPAL ) ; xobjc_draw( wnd->window_handle, adr_album, ALBUM_PPAL ) ; case ALBUM_PPAL : config.color_protect = selected( adr_album, ALBUM_PPAL ) ; set_palette(&wext->imginf) ; break ; case ALBUM_CATEGORIE1: case ALBUM_CATEGORIE2: case ALBUM_CATEGORIE3: for (i = ALBUM_ITEM1; i <= ALBUM_ITEM10; i++) if (selected(adr_album, i)) break ; if ((tab_index == NULL) || (i == 1+ALBUM_ITEM10)) break ; deselect(adr_album, obj) ; objc_offset(adr_album, obj, &mx, &my) ; switch(obj) { case ALBUM_CATEGORIE1 : clicked = popup_formdo( &wext->categorie, mx, my, 2+tab_index[wext->first+i-ALBUM_ITEM1].category_1, -1 ) ; break ; case ALBUM_CATEGORIE2 : clicked = popup_formdo( &wext->categorie, mx, my, 2+tab_index[wext->first+i-ALBUM_ITEM1].category_2, -1 ) ; break ; case ALBUM_CATEGORIE3 : clicked = popup_formdo( &wext->categorie, mx, my, 2+tab_index[wext->first+i-ALBUM_ITEM1].category_3, -1 ) ; break ; } if (clicked > 1) { sprintf(buf, " %s", catalog_header.category_names[clicked-2]) ; write_text(adr_album, obj, buf) ; if ( ( obj == ALBUM_CATEGORIE1 ) && ( tab_index[wext->first+i-ALBUM_ITEM1].category_1 == tab_index[wext->first+i-ALBUM_ITEM1].category_2 ) && ( tab_index[wext->first+i-ALBUM_ITEM1].category_2 == tab_index[wext->first+i-ALBUM_ITEM1].category_3 ) ) { int j ; for (j = 1; j <= 3 ; j++ ) catalog_setcategory( wext->first+i-ALBUM_ITEM1, clicked-2, j ) ; } else catalog_setcategory(wext->first+i-ALBUM_ITEM1, clicked-2, 1+obj-ALBUM_CATEGORIE1) ; } else if (clicked == 1) { int index_category ; char buffer[80] ; lstd_input( msg[MSG_CATENEW], buffer ) ; if (buffer[0]) { index_category = catalog_addcategory(buffer) ; make_category_popup( wnd ) ; sprintf(buf, " %s", buffer) ; write_text(adr_album, obj, buf) ; catalog_setcategory(wext->first+i-ALBUM_ITEM1, index_category, 1+obj-ALBUM_CATEGORIE1) ; } } wext->last_num = -1 ; load_icon( wnd, wext->first+i-ALBUM_ITEM1 ) ; break ; case ALBUM_CONFIG : if (album_config() == 1) { mouse_busy() ; sort_index() ; wext->first = 0 ; mouse_restore() ; } deselect(adr_album, obj) ; xobjc_draw( wnd->window_handle, adr_album, obj ) ; update_list( wnd, 1 ) ; wext->hf =(float) (adr_album[ALBUM_BOX].ob_height-adr_album[ALBUM_SLIDER].ob_height) ; for (i = ALBUM_ITEM1; i <= ALBUM_ITEM10; i++) if (selected(adr_album, i)) break ; wext->last_num = -1 ; load_icon( wnd, wext->first+i-ALBUM_ITEM1 ) ; if (catalog_filter.nb_visibles <= 0) adr_album[ALBUM_WINDOW].ob_state |= DISABLED ; else adr_album[ALBUM_WINDOW].ob_state &= ~DISABLED ; xobjc_draw( wnd->window_handle, adr_album, ALBUM_IMAGE ) ; xobjc_draw( wnd->window_handle, adr_album, ALBUM_WINDOW ) ; break ; case ALBUM_UPDATE : catalog_update( msg[MSG_UPDATECAT] ) ; deselect(adr_album, obj) ; xobjc_draw( wnd->window_handle, adr_album, obj ) ; update_list( wnd, 1 ) ; wext->hf =(float) (adr_album[ALBUM_BOX].ob_height-adr_album[ALBUM_SLIDER].ob_height) ; for (i = ALBUM_ITEM1; i <= ALBUM_ITEM10; i++) if (selected(adr_album, i)) break ; wext->last_num = -1 ; load_icon( wnd, wext->first+i-ALBUM_ITEM1 ) ; xobjc_draw( wnd->window_handle, adr_album, ALBUM_IMAGE ) ; break ; case ALBUM_WINDOW : if ( WndAlbum == NULL ) album_window() ; deselect(adr_album, obj) ; xobjc_draw( wnd->window_handle, adr_album, obj ) ; wext->hf =(float) (adr_album[ALBUM_BOX].ob_height-adr_album[ALBUM_SLIDER].ob_height) ; for (i = ALBUM_ITEM1; i <= ALBUM_ITEM10; i++) if (selected(adr_album, i)) break ; wext->last_num = -1 ; load_icon( wnd, wext->first+i-ALBUM_ITEM1 ) ; break ; case ALBUM_TOVSS : sprintf( vss_name, "%s\\*.VSS", config.path_album ) ; valid = file_name(vss_name, "", vss_name) ; if ( valid ) { GEM_WINDOW *wprog ; FILE *stream ; long num ; int r ; char full_name[200] ; char buf[50] ; if ( FileExist( vss_name ) ) r = form_interrogation(2, msg[MSG_FILEEXISTS]) ; if ( r == 2 ) break ; stream = fopen( vss_name, "wb" ) ; if ( stream == NULL ) { form_stop(1,msg[MSG_WRITEERROR]) ; break ; } wprog = DisplayStdProg( msg[MSG_SAVEVSS], "", "", CLOSER ) ; for ( num = 0; num < catalog_filter.nb_visibles ; num++ ) { catalog_getfullname( num, full_name ) ; if ( full_name[0] != 0 ) { sprintf( buf, "Display %s\r\n", full_name ) ; if ( fwrite( buf, strlen(buf), 1, stream ) != 1 ) { form_stop(1,msg[MSG_WRITEERROR]) ; break ; } } if ( MAY_UPDATE( wprog, num ) ) { sprintf( buf, "%04ld/%04ld", num, catalog_filter.nb_visibles ) ; wprog->ProgPc( wprog, (int) ((100L*num)/(long)catalog_filter.nb_visibles), buf ) ; } } fclose( stream ) ; GWDestroyWindow( wprog ) ; } deselect(adr_album, obj) ; xobjc_draw( wnd->window_handle, adr_album, obj ) ; break ; case ALBUM_OK : code = IDOK ; break ; } if ( code == IDOK ) { } return( code ) ; }
void DialogVideoPlayer::loadData(GrafixParticipant* participant, mat &p_roughM_in, mat &p_smoothM_in, mat &p_fixAllM_in, mat &p_segmentsM_in) { _participant = participant; p_roughM = &p_roughM_in; p_smoothM = &p_smoothM_in; p_fixAllM = &p_fixAllM_in; segmentsM = p_segmentsM_in; if (segmentsM.n_rows == 0) { segmentsM.zeros(1,3); segmentsM(0,0) = 0; segmentsM(0,1) = 0; segmentsM(0,2) = p_roughM->n_rows - 1; } // order the segments uvec indices = sort_index(segmentsM.cols(1,1)); this->segmentsM = segmentsM.rows(indices); secsFragment = this->_participant->GetProject()->GetProjectSetting(Consts::SETTING_SECS_FRAGMENT, Consts::ACTIVE_CONFIGURATION()).toInt(); hz = this->_participant->GetProject()->GetProjectSetting(Consts::SETTING_HZ, Consts::ACTIVE_CONFIGURATION()).toInt(); samplesPerFragment = secsFragment * hz; expWidth = this->_participant->GetProject()->GetProjectSetting(Consts::SETTING_EXP_WIDTH, Consts::ACTIVE_CONFIGURATION()).toInt(); expHeight = this->_participant->GetProject()->GetProjectSetting(Consts::SETTING_EXP_HEIGHT, Consts::ACTIVE_CONFIGURATION()).toInt(); if (p_smoothM->is_empty()) { settingPlaySmooth = false; ui->checkBoxSmooth->setChecked(false); ui->checkBoxSmooth->setEnabled(false); } else { ui->checkBoxSmooth->setChecked(true); } firstSampleMS = (*p_roughM).at(0, 0); //this is the ms of when the player first started currentIndex = 0; currentFragment = -1; currentSegment = 0; settingChanged(); stopPlaying(); // Load media from settings QString moviePath = _participant->GetProjectSetting(Consts::SETTING_MOVIE_PATH).toString(); loadMovie(moviePath); QByteArray imagesPaths = _participant->GetProjectSetting(Consts::SETTING_IMAGE_PATHS).toByteArray(); pathsImages = QJsonDocument::fromJson(imagesPaths).object().toVariantMap(); qDebug() << pathsImages; updatePlaybackState(0, true); qDebug() << " finish loading "; dotSizePercentage = 5; ui->sliderDotSize->blockSignals(true); ui->sliderDotSize->setValue(dotSizePercentage * 10); ui->sliderDotSize->blockSignals(false); resizeDisplay(); }
CliqueTree Inference::CreateCliqueTreeHMMFast( vector<Factor> factors ) { int maxVar = 0; // get the max var id for ( vector<Factor>::iterator iter = factors.begin(); iter != factors.end(); iter ++ ) { double max_now = iter->var.max(); if ( max_now > maxVar ) { maxVar = max_now; } } int numNodes = maxVar - 1; int card = factors[0].card(0); CliqueTree P(numNodes); //P.cliqueList = repmat(struct('var', [], 'card', [], 'val', []), numNodes, 1); //P.edges = zeros(numNodes); for ( int i = 0; i != numNodes; i++ ) { P.cliqueList[i].var << i+1 << i+2; P.cliqueList[i].card << card << card; P.cliqueList[i].val = ones<vec>(card * card); if (i > 0) { P.edges(i, i-1) = 1; P.edges(i-1, i) = 1; } } // the name of the variable starts from 1 !!!! for ( int i = 0; i != factors.size(); i ++ ) { Factor f = factors[i]; int cliqueIdx = 0; if (f.var.n_rows == 1) { if (f.var(0) > 1) { cliqueIdx = f.var(0) - 1; }else{ cliqueIdx = 1; } vec updateIdxs; mat assignments = zeros<mat>(card, 2); vec cards; cards << card << card; for ( int assignment = 0; assignment != card; assignment ++ ) { if (f.var(0) == cliqueIdx) { assignments.col(0) = linspace<vec>(0, card - 1, card); assignments.col(1) = assignment*ones<vec>(card); updateIdxs = Utils::AssignmentToIndex(assignments, cards); }else{ assignments.col(1) = linspace<vec>(0, card - 1, card); assignments.col(0) = assignment*ones<vec>(card); updateIdxs = Utils::AssignmentToIndex(assignments, cards); } for (int step = 0; step != updateIdxs.n_rows; step ++) { P.cliqueList[cliqueIdx - 1].val(updateIdxs(step)) += f.val(step); } } }else{ if ( f.var.n_rows != 2 ) { std::cout << "ERROR: var more than 2!" << std::endl; } cliqueIdx = min(f.var); if (f.var(0) > f.var(1)) { // % sort the factor val so it's in increasing var order uvec order = sort_index(f.var); //%#ok mat oldAssignments = Utils::IndexToAssignment(linspace<vec>(0,f.val.n_rows-1,f.val.n_rows), f.card); mat newAssignments = oldAssignments; // (:, order) for (int step = 0; step != oldAssignments.n_cols; step ++) { newAssignments.col(step) = oldAssignments.col(order(step)); } vec new_card = f.card; for (int step = 0; step != f.card.n_rows; step ++) { new_card(step) = f.card(order(step)); } f.card = new_card; f.var = sort(f.var); vec new_index = Utils::AssignmentToIndex(newAssignments, f.card); vec new_val = f.val; for ( int step = 0; step != f.val.n_rows; step ++ ) { new_val(step) = f.val( new_index(step) ); } f.val = new_val; } P.cliqueList[cliqueIdx - 1].val += f.val; } } return P; }
arma::field<arma::field<arma::mat> > model_select(arma::vec& data, const std::set<std::vector<std::string > >& models, const std::vector< std::string >& full_model, std::string model_type, bool bs_optimism, double alpha, std::string compute_v, unsigned int K, unsigned int H, unsigned int G, bool robust, double eff, unsigned int seed){ // Number of data points unsigned int N = data.n_rows; // Number of models unsigned int num_models = models.size(); // Store output from models arma::field<arma::field<arma::mat> > model_results(num_models); // Make an iterator to iterator through it std::set<std::vector<std::string > > ::const_iterator iter; iter = models.begin(); // Get the first model std::vector<std::string> desc = full_model; // Find where the results should be input. (No protection needed, we know it is in the matrix) unsigned int full_model_index = std::distance(models.begin(), models.find(full_model)); // Build the fields off of the first model's description arma::vec theta = model_theta(desc); arma::field<arma::vec> objdesc = model_objdesc(desc); // Build matrix to store results arma::mat results(num_models, 4); Rcpp::Rcout << "Processing model 1 out of " << num_models << std::endl; set_seed(seed); // Obtain the largest models information arma::field<arma::mat> master = gmwm_master_cpp(data, theta, desc, objdesc, model_type, true, //starting alpha, "fast", // compute V K, H, G, robust, eff); // Theta update theta = master(0); // Define WV Empirical arma::vec wv_empir = master(2); // Create WV Matrix arma::mat wv(wv_empir.n_elem,3); wv.col(0) = wv_empir; wv.col(1) = master(3); wv.col(2) = master(4); // Get the original "FAST" matrix arma::mat orgV = master(6); // Original V // Take the inverse arma::mat omega = inv(orgV); // Original V => Omega // Get expect_diff for guesses with DR double expect_diff = arma::as_scalar(master(7)); // Obtain the theoretical WV arma::vec theo = master(8); // Obtain the obj_value of the function double obj_value = arma::as_scalar(master(10)); // Calculate the values of the Scales arma::vec scales = scales_cpp(floor(log2(N))); double dr_slope = arma::as_scalar(master(12)); // ------------------------------------ // Store output from default GMWM object arma::field<arma::mat> mod_output(13); mod_output(0) = theta; mod_output(1) = master(1); mod_output(2) = wv_empir; mod_output(3) = master(3); mod_output(4) = master(4); mod_output(5) = master(5); mod_output(6) = orgV; mod_output(7) = expect_diff; mod_output(8) = theo; mod_output(9) = master(9); mod_output(10) = obj_value; mod_output(11) = omega; mod_output(12) = dr_slope; // ------------------------------------ // Here we set up specifics that are used not in a specific mode. // Asymptotic ---- // Get bootstrapped V arma::mat V; // Bootstrap ---- // Hold optimism result arma::mat cov_nu_nu_theta; // Hold the bootstrapped obj values arma::vec bs_obj_values; if(bs_optimism){ results.row(full_model_index) = bs_optim_calc(theta, desc, objdesc, model_type, scales, omega, N, obj_value, alpha, compute_v, K, H, G, robust, eff); }else{ Rcpp::Rcout << "Bootstrapping the covariance matrix... Please stand by." << std::endl; V = cov_bootstrapper(theta, desc, objdesc, N, robust, eff, H, false); // Bootstrapped V (largest model) // Calculate the model score according to model selection criteria paper results.row(full_model_index) = asympt_calc(theta, desc, objdesc, model_type, scales, V, omega, wv_empir, theo, obj_value); } // Custom GMWM Update Obj arma::field<arma::mat> model_update_info(6); model_update_info(0) = master(0); // theta model_update_info(1) = master(1); // guessed_theta model_update_info(2) = master(5); // V model_update_info(3) = master(8); // theo model_update_info(4) = master(9); // decomp_theo model_update_info(5) = master(10); // objective value model_results(full_model_index) = model_update_info; // Initialize counter to keep track of values unsigned int count = 0; unsigned int countModels = 1; while(iter != models.end()){ if(full_model_index != count){ countModels++; // Set guessing seed set_seed(seed); Rcpp::Rcout << "Processing model " << countModels << " out of " << num_models << std::endl; // Get the first model desc = *iter; // Build the fields off of the first model's description theta = model_theta(desc); objdesc = model_objdesc(desc); // Run the update version of the GMWM arma::field<arma::mat> update = gmwm_update_cpp(theta, desc, objdesc, model_type, N, expect_diff, dr_slope, orgV, scales, wv, true, //starting "fast", K,H,G, robust,eff); // Theta update theta = update(0); // Update theo theo = update(3); // Update objective function obj_value = arma::as_scalar(update(5)); if(bs_optimism){ results.row(count) = bs_optim_calc(theta, desc, objdesc, model_type, scales, omega, N, obj_value, alpha, compute_v, K, H, G, robust, eff); }else{ // Calculate the model score according to model selection criteria paper results.row(count) = asympt_calc(theta, desc, objdesc, model_type, scales, V, omega, wv_empir, theo, obj_value); } model_results(count) = update; } // end if // Increment iterator iter++; // Increase count count++; } // Only run if in asymptotic mode if(!bs_optimism){ // std::set<std::vector<std::string > > ::const_iterator iter2; // // iter = models.begin(); // // /* // * Iterate through all models // * If i != j, then // * IF (Complex_i > Complex_j && Obj_i > Obj_j){ // * IF(Crit_i < Crit_J) // * } // */ // while(iter != models.end()){ // iter2 = models.begin(); // while(iter2 != models.end()){ // if(iter != iter2){ // double m1_index = std::distance(models.begin(),iter); // double m2_index = std::distance(models.begin(),iter2); // // if(count_params(*iter) > count_params(*iter2) && results(m1_index,0) > results(m2_index,0)){ // if(results(m1_index,2) < results(m2_index,2)){ // results(m1_index,1) = results(m2_index,1) + fabs(R::rnorm(0, sqrt(results(m2_index,0)/10) )); // } // } // } // iter2++; // } // iter++; // } } results.col(2) = results.col(0) + results.col(1); // Sort matrix arma::uvec sort_ind = sort_index(results.col(2)); // Pick the "best" model unsigned int best_model_id = sort_ind(0); // Get the sort column index arma::vec ex_sort = arma::conv_to<arma::vec>::from(sort_ind); // Sort the result matrix by Criterion arma::mat sorted = sort_mat(results, 2); // --------- // Set up output feed arma::field< arma::field<arma::mat> > out(2); // Build the results matrix arma::field<arma::mat> ms(2); ms(0) = sorted; ms(1) = ex_sort + 1; // Sorted vector (so R can know desc IDs) ALSO change index // Create m // If the output object is not the full model, let's inject the new results. if(best_model_id != full_model_index){ arma::field<arma::mat> m; m = model_results(best_model_id); mod_output(0) = m(0); mod_output(1) = m(1); mod_output(5) = m(2); mod_output(8) = m(3); mod_output(9) = m(4); mod_output(10) = m(5); } // Output to me! out(0) = ms; out(1) = mod_output; return out; }
//------------------------------------------------------------------------------ void MfLowRankApproximation::initialize() { double dx; double constValue; double endValue; double constEnd; double epsilon; dx = grid.DX; try { nOrbitals = cfg->lookup("spatialDiscretization.nSpatialOrbitals"); constEnd = cfg->lookup("meanFieldIntegrator.lowRankApproximation.constEnd"); constValue = cfg->lookup("meanFieldIntegrator.lowRankApproximation.constValue"); endValue = cfg->lookup("meanFieldIntegrator.lowRankApproximation.endValue"); epsilon = cfg->lookup("meanFieldIntegrator.lowRankApproximation.epsilon"); } catch (const SettingNotFoundException &nfex) { cerr << "MfLowRankApproximation::Error reading entry from config object." << endl; exit(EXIT_FAILURE); } int nConst = constEnd/dx; int constCenter = nGrid/2; Vxy = zeros(nGrid, nGrid); for(uint p=0; p<potential.size(); p++) { for(int i=0; i<nGrid; i++) { for(int j=0; j<nGrid; j++) { Vxy(i, j) += potential[p]->evaluate(i, j); } } } // Using a simple discretization equal to the discretization of // the system. mat h = hExactSpatial(); // mat h = hPiecewiseLinear(); mat Q = eye(nGrid,nGrid); // Using a consant weight in the center of the potential // and a linear decrease from the center. vec g = gLinear(nGrid, constCenter, nConst, constValue, endValue); mat C = cMatrix(g, h, dx); vec lambda; mat eigvec; eig_sym(lambda, eigvec, inv(C.t())*Vxy*inv(C)); mat Ut = C.t()*eigvec; mat QU = inv(Q)*Ut; // Sorting the eigenvalues by absoulte value and finding the number // of eigenvalues with abs(eigenval(i)) > epsilon uvec indices = sort_index(abs(lambda), 1); M = -1; for(uint m=0; m <lambda.n_rows; m++) { cout << abs(lambda(indices(m))) << endl; if(abs(lambda(indices(m))) < epsilon) { M = m; break; } } // cout << min(abs(lambda)) << endl; // cout << "hei" << endl; // cout << lambda << endl; // M = 63; if(M < 0) { cerr << "MfLowRankApproximation:: no eigenvalues < epsilon found." << " Try setting epsilon to a higher number" << endl; exit(EXIT_FAILURE); } eigenval = zeros(M); for(int m=0; m <M; m++) { eigenval(m) = lambda(indices(m)); } // Calculating the U matrix U = zeros(nGrid, M); for(int m=0; m < M; m++) { for(uint j=0; j<h.n_rows; j++) { U(j,m) = 0; for(uint i=0; i<h.n_cols; i++) { U(j,m) += h(j,i)*QU(i,indices(m)); } } } cout << "MfLowRankApproximation:: Trunction of eigenvalues at M = " << M << endl; #if 1 // For testing the low rank approximation's accuracy mat appV = zeros(nGrid, nGrid); for(int i=0; i<nGrid; i++) { for(int j=0; j<nGrid; j++) { appV(i,j) = 0; for(int m=0; m<M; m++) { appV(i,j) += eigenval(m)*U(i,m)*U(j,m); } } } mat diffV = abs(Vxy - appV); cout << "max_err = " << max(max(abs(Vxy - appV))) << endl; diffV.save("../DATA/diffV.mat"); appV.save("../DATA/Vapp.mat"); Vxy.save("../DATA/Vex.mat"); cout << nGrid << endl; // exit(EXIT_SUCCESS); #endif cout << "test" << endl; Vm = zeros<cx_vec>(M); Vqr = zeros<cx_vec>(nGrid); }