void printTour(deque<int> tour) { printf("Tour: "); for(deque<int>::iterator it=tour.begin(); it!=tour.end(); it++) printf("%d ",*it); printf("\n"); }

int build_subgraph(deque<set<int> > & E, const deque<int> & nodes, const deque<int> & degrees) { /* cout<<"nodes"<<endl; prints(nodes); cout<<"degrees"<<endl; prints(degrees); */ if(degrees.size()<3) { cerr<<"it seems that some communities should have only 2 nodes! This does not make much sense (in my opinion) Please change some parameters!"<<endl; return -1; } // this function is to build a network with the labels stored in nodes and the degree seq in degrees (correspondence is based on the vectorial index) // the only complication is that you don't want the nodes to have neighbors they already have // labels will be placed in the end deque<set<int> > en; // this is the E of the subgraph { set<int> first; for(int i=0; i<nodes.size(); i++) en.push_back(first); } multimap <int, int> degree_node; for(int i=0; i<degrees.size(); i++) degree_node.insert(degree_node.end(), make_pair(degrees[i], i)); int var=0; while (degree_node.size() > 0) { multimap<int, int>::iterator itlast= degree_node.end(); itlast--; multimap <int, int>::iterator itit= itlast; deque <multimap<int, int>::iterator> erasenda; int inserted=0; for (int i=0; i<itlast->first; i++) { if(itit!=degree_node.begin()) { itit--; en[itlast->second].insert(itit->second); en[itit->second].insert(itlast->second); inserted++; erasenda.push_back(itit); } else break; } for (int i=0; i<erasenda.size(); i++) { if(erasenda[i]->first>1) degree_node.insert(make_pair(erasenda[i]->first - 1, erasenda[i]->second)); degree_node.erase(erasenda[i]); } var+= itlast->first - inserted; degree_node.erase(itlast); } // ---------------------------------------------------------- deque<int> degree_list; for(int kk=0; kk<degrees.size(); kk++) for(int k2=0; k2<degrees[kk]; k2++) degree_list.push_back(kk); // this is to randomize the subgraph ------------------------------------------------------------------- for(int run=0; run<10; run++) for(int node_a=0; node_a<degrees.size(); node_a++) for(int krm=0; krm<en[node_a].size(); krm++) { int random_mate=degree_list[irand(degree_list.size()-1)]; while (random_mate==node_a) random_mate=degree_list[irand(degree_list.size()-1)]; if (en[node_a].insert(random_mate).second) { deque <int> out_nodes; for (set<int>::iterator it_est=en[node_a].begin(); it_est!=en[node_a].end(); it_est++) if ((*it_est)!=random_mate) out_nodes.push_back(*it_est); int old_node=out_nodes[irand(out_nodes.size()-1)]; en[node_a].erase(old_node); en[random_mate].insert(node_a); en[old_node].erase(node_a); deque <int> not_common; for (set<int>::iterator it_est=en[random_mate].begin(); it_est!=en[random_mate].end(); it_est++) if ((old_node!=(*it_est)) && (en[old_node].find(*it_est)==en[old_node].end())) not_common.push_back(*it_est); int node_h=not_common[irand(not_common.size()-1)]; en[random_mate].erase(node_h); en[node_h].erase(random_mate); en[node_h].insert(old_node); en[old_node].insert(node_h); } } // now I try to insert the new links into the already done network. If some multiple links come out, I try to rewire them deque < pair<int, int> > multiple_edge; for (int i=0; i<en.size(); i++) { for(set<int>::iterator its=en[i].begin(); its!=en[i].end(); its++) if(i<*its ) { bool already = !(E[nodes[i]].insert(nodes[*its]).second); // true is the insertion didn't take place if (already) multiple_edge.push_back(make_pair(nodes[i], nodes[*its])); else E[nodes[*its]].insert(nodes[i]); } } //cout<<"multiples "<<multiple_edge.size()<<endl; for (int i=0; i<multiple_edge.size(); i++) { int &a = multiple_edge[i].first; int &b = multiple_edge[i].second; // now, I'll try to rewire this multiple link among the nodes stored in nodes. int stopper_ml=0; while (true) { stopper_ml++; int random_mate=nodes[degree_list[irand(degree_list.size()-1)]]; while (random_mate==a || random_mate==b) random_mate=nodes[degree_list[irand(degree_list.size()-1)]]; if(E[a].find(random_mate)==E[a].end()) { deque <int> not_common; for (set<int>::iterator it_est=E[random_mate].begin(); it_est!=E[random_mate].end(); it_est++) if ((b!=(*it_est)) && (E[b].find(*it_est)==E[b].end()) && (binary_search(nodes.begin(), nodes.end(), *it_est))) not_common.push_back(*it_est); if(not_common.size()>0) { int node_h=not_common[irand(not_common.size()-1)]; E[random_mate].insert(a); E[random_mate].erase(node_h); E[node_h].erase(random_mate); E[node_h].insert(b); E[b].insert(node_h); E[a].insert(random_mate); break; } } if(stopper_ml==2*E.size()) { cout<<"sorry, I need to change the degree distribution a little bit (one less link)"<<endl; break; } } } return 0; }

Segment* Segment::new_segment(MorphoStream &ms, TransferRules* tr, TaggerData &td) { TaggerWord *word=NULL; set<TTag> tags; set<TTag>::iterator itag; vector<TTag> auxvec; static int index_start=1; static deque<TaggerWord> wordsbuffer; static bool first_call=true; static bool end_of_corpus_reached=false; if (first_call) { TaggerWord eosword; eosword.add_tag(td.getTagIndex()[L"TAG_SENT"], L"", td.getPreferRules()); wordsbuffer.push_back(eosword); //Fill the buffer of words while (wordsbuffer.size()<TAGGER_WORD_BUFFER_SIZE) { word=ms.get_next_word(); if(word==NULL) { end_of_corpus_reached=true; break; } wordsbuffer.push_back(*word); delete word; } first_call=false; } /* cerr<<"BUFFER (begining): "; for (int i=0; i<wordsbuffer.size(); i++) { cerr<<"["<<wordsbuffer[i].get_superficial_form()<<"] "; } cerr<<"\n"; cerr<<"Buffer size (begining): "<<wordsbuffer.size()<<"\n"; cerr<<"Index start (begining): "<<index_start<<"\n"; */ Segment* seg=new Segment(); int number_of_paths=1; int segmentation_point=-1; int advance; //Number of word that can be skipped when looking for a segmentation point for(size_t i=index_start; i<wordsbuffer.size(); i++) { if (tr->is_segmentation_point(tag_index[L"TAG_kEOF"], wordsbuffer, i, advance)) { segmentation_point=i; break; } else{ i+=advance; } } if ((segmentation_point==-1) && (!end_of_corpus_reached)) { cerr<<"Error: No segmentation point was found.\n"; cerr<<"Try making the buffer longer, current maximum size is "<<TAGGER_WORD_BUFFER_SIZE<<"\n"; cerr<<"See Segment.H, TAGGER_WORD_BUFFER_SIZE constant\n"; exit(EXIT_FAILURE); } //cerr<<"Segmentation point: "<<segmentation_point<<"\n"; //The segment to return is from index_start to segmentation_point for(int i=index_start; i<=segmentation_point; i++) { tags=wordsbuffer[i].get_tags(); seg->contador_caminos.push_back(auxvec); if (tags.size()>0) { number_of_paths*=tags.size(); for(itag=tags.begin(); itag!=tags.end(); itag++) seg->contador_caminos.back().push_back(*itag); } else { //seg->contador_caminos.back().push_back(-1); //Palabra desconocida tags=td.getOpenClass(); number_of_paths*=tags.size(); for(itag=tags.begin(); itag!=tags.end(); itag++) seg->contador_caminos.back().push_back(*itag); } seg->vwords.push_back(wordsbuffer[i]); } //Calculate which words can be removed from the buffer, we need some //words before the segment being return, more concretely, from the //last non-ambiguous word until the first word of the segment being //returned int preserve_word_from=-1; for (int i=(index_start-1); i>=0; i--) { if (wordsbuffer[i].get_tags().size()==1) { preserve_word_from=i; break; } } //cerr<<"Preserve words from index: "<<preserve_word_from<<"\n"; for(int i=0; i<preserve_word_from; i++) { wordsbuffer.pop_front(); segmentation_point--; index_start--; } /* cerr<<"BUFFER (after removing words): "; for (int i=0; i<wordsbuffer.size(); i++) { cerr<<"["<<wordsbuffer[i].get_superficial_form()<<"] "; } cerr<<"\n"; cerr<<"Buffer size (after removing words): "<<wordsbuffer.size()<<"\n"; cerr<<"Index start (after removing words): "<<index_start<<"\n"; cerr<<"Segmention point (after removing words): "<<segmentation_point<<"\n"; */ //Refill the buffer if (!end_of_corpus_reached) { while (wordsbuffer.size()<TAGGER_WORD_BUFFER_SIZE) { word=ms.get_next_word(); if(word==NULL) { end_of_corpus_reached=true; break; } wordsbuffer.push_back(*word); delete word; } } /* cerr<<"BUFFER (after refill): "; for (int i=0; i<wordsbuffer.size(); i++) { cerr<<"["<<wordsbuffer[i].get_superficial_form()<<"] "; } cerr<<"\n"; cerr<<"Buffer size (after refill): "<<wordsbuffer.size()<<"\n"; cerr<<"Index start (after refill): "<<index_start<<"\n"; cerr<<"Segmention point (after refill): "<<segmentation_point<<"\n"; */ //Now we retrieve words before and after this segment, for the //calculus of the alphas and betas in the pruning method for (int i=0; i<index_start; i++) seg->vwords_before.push_back(wordsbuffer[i]); bool found_forward=false; for(size_t i=segmentation_point+1; i<wordsbuffer.size(); i++) { seg->vwords_after.push_back(wordsbuffer[i]); if (wordsbuffer[i].get_tags().size()==1) { found_forward=true; break; } } if (!found_forward) { if (!end_of_corpus_reached) { cerr<<"Error: No unambiguous word was found when looking fordward.\n"; cerr<<"Try making the buffer longer, current maximum size is "<<TAGGER_WORD_BUFFER_SIZE<<"\n"; cerr<<"See Segment.H, TAGGER_WORD_BUFFER_SIZE constant\n"; exit(EXIT_FAILURE); } else { TaggerWord eosword; eosword.add_tag(td.getTagIndex()[L"TAG_SENT"], L"", td.getPreferRules()); seg->vwords_after.push_back(eosword); } } index_start=segmentation_point+1; //For the next search //We have the total number of disambiguation paths for this segment. //Now we initialize the structure used to retrieve all the paths in //an efficient way. (nfijos_caminos = nº de veces que se tiene que //usar una etiqueta antes de pasar a la siguiente) for(size_t i=0; i<seg->contador_caminos.size(); i++) { int fijo=1; for(size_t j=i+1; j<seg->contador_caminos.size(); j++) { fijo*=seg->contador_caminos[j].size(); } seg->nfijo_caminos.push_back(fijo); } if(seg->vwords.size()==0) //That's all folks seg->npaths=0; else seg->npaths=number_of_paths; return seg; }

int erase_links(deque<set<int> > & E, const deque<deque<int> > & member_list, const bool excess, const bool defect, const double mixing_parameter) { int num_nodes= member_list.size(); int eras_add_times=0; if (excess) { for (int i=0; i<num_nodes; i++) { while ( (E[i].size()>1) && double(internal_kin(E, member_list, i))/E[i].size() < 1 - mixing_parameter) { //--------------------------------------------------------------------------------- cout<<"degree sequence changed to respect the option -sup ... "<<++eras_add_times<<endl; deque<int> deqar; for (set<int>::iterator it_est=E[i].begin(); it_est!=E[i].end(); it_est++) if (!they_are_mate(i, *it_est, member_list)) deqar.push_back(*it_est); if(deqar.size()==E[i].size()) { // this shouldn't happen... cerr<<"sorry, something went wrong: there is a node which does not respect the constraints. (option -sup)"<<endl; return -1; } int random_mate=deqar[irand(deqar.size()-1)]; E[i].erase(random_mate); E[random_mate].erase(i); } } } if (defect) { for (int i=0; i<num_nodes; i++) while ( (E[i].size()<E.size()) && double(internal_kin(E, member_list, i))/E[i].size() > 1 - mixing_parameter) { //--------------------------------------------------------------------------------- cout<<"degree sequence changed to respect the option -inf ... "<<++eras_add_times<<endl; int stopper_here=num_nodes; int stopper_=0; int random_mate=irand(num_nodes-1); while ( ( (they_are_mate(i, random_mate, member_list)) || E[i].find(random_mate)!=E[i].end()) && (stopper_<stopper_here) ) { random_mate=irand(num_nodes-1); stopper_++; } if(stopper_==stopper_here) { // this shouldn't happen... cerr<<"sorry, something went wrong: there is a node which does not respect the constraints. (option -inf)"<<endl; return -1; } E[i].insert(random_mate); E[random_mate].insert(i); } } //------------------------------------ Erasing links ------------------------------------------------------ return 0; }

int build_bipartite_network(deque<deque<int> > & member_matrix, const deque<int> & member_numbers, const deque<int> &num_seq) { // this function builds a bipartite network with num_seq and member_numbers which are the degree sequences. in member matrix links of the communities are stored // this means member_matrix has num_seq.size() rows and each row has num_seq[i] elements deque<set<int> > en_in; // this is the Ein of the subgraph deque<set<int> > en_out; // this is the Eout of the subgraph { set<int> first; for(int i=0; i<member_numbers.size(); i++) { en_in.push_back(first); } } { set<int> first; for(int i=0; i<num_seq.size(); i++) { en_out.push_back(first); } } multimap <int, int> degree_node_out; deque<pair<int, int> > degree_node_in; for(int i=0; i<num_seq.size(); i++) degree_node_out.insert(make_pair(num_seq[i], i)); for(int i=0; i<member_numbers.size(); i++) degree_node_in.push_back(make_pair(member_numbers[i], i)); sort(degree_node_in.begin(), degree_node_in.end()); deque<pair<int, int> >::iterator itlast = degree_node_in.end(); /* for (int i=0; i<degree_node_in.size(); i++) cout<<degree_node_in[i].first<<" "<<degree_node_in[i].second<<endl; */ while (itlast != degree_node_in.begin()) { itlast--; multimap <int, int>::iterator itit= degree_node_out.end(); deque <multimap<int, int>::iterator> erasenda; for (int i=0; i<itlast->first; i++) { if(itit!=degree_node_out.begin()) { itit--; en_in[itlast->second].insert(itit->second); en_out[itit->second].insert(itlast->second); erasenda.push_back(itit); } else return -1; } //cout<<"degree node out before"<<endl; //prints(degree_node_out); for (int i=0; i<erasenda.size(); i++) { if(erasenda[i]->first>1) degree_node_out.insert(make_pair(erasenda[i]->first - 1, erasenda[i]->second)); degree_node_out.erase(erasenda[i]); } //cout<<"degree node out after"<<endl; //prints(degree_node_out); } // this is to randomize the subgraph ------------------------------------------------------------------- deque<int> degree_list; for(int kk=0; kk<member_numbers.size(); kk++) for(int k2=0; k2<member_numbers[kk]; k2++) degree_list.push_back(kk); for(int run=0; run<10; run++) for(int node_a=0; node_a<num_seq.size(); node_a++) for(int krm=0; krm<en_out[node_a].size(); krm++) { int random_mate=degree_list[irand(degree_list.size()-1)]; if (en_out[node_a].find(random_mate)==en_out[node_a].end()) { deque <int> external_nodes; for (set<int>::iterator it_est=en_out[node_a].begin(); it_est!=en_out[node_a].end(); it_est++) external_nodes.push_back(*it_est); int old_node=external_nodes[irand(external_nodes.size()-1)]; deque <int> not_common; for (set<int>::iterator it_est=en_in[random_mate].begin(); it_est!=en_in[random_mate].end(); it_est++) if (en_in[old_node].find(*it_est)==en_in[old_node].end()) not_common.push_back(*it_est); if (not_common.empty()) break; int node_h=not_common[irand(not_common.size()-1)]; en_out[node_a].insert(random_mate); en_out[node_a].erase(old_node); en_in[old_node].insert(node_h); en_in[old_node].erase(node_a); en_in[random_mate].insert(node_a); en_in[random_mate].erase(node_h); en_out[node_h].erase(random_mate); en_out[node_h].insert(old_node); } } member_matrix.clear(); deque <int> first; for (int i=0; i<en_out.size(); i++) { member_matrix.push_back(first); for (set<int>::iterator its=en_out[i].begin(); its!=en_out[i].end(); its++) member_matrix[i].push_back(*its); } return 0; }

void push(deque<p>& q,uc x,uc y){ p p1;p1.x=x;p1.y=y;q.push_back(p1); }

void convexHull4d::createNewFacets(deque<long>& horizonRidges, vertex4d* furthest, vector<long>& facetIdList, deque<long>& bucketLessVertices, double testNormal[4]) { // cout<<"size of horizon ridgeS when creating:"<<horizonRidges.size()<<endl; for(deque<long>::iterator hrit=horizonRidges.begin(); hrit!= horizonRidges.end(); hrit++) { vector<long> vertexIndices; vector<long> ridgeIdsForFacet(4); vertexIndices.push_back(tempRidges.find((*hrit))->second.getVertexList()[0]); vertexIndices.push_back(tempRidges.find((*hrit))->second.getVertexList()[1]); vertexIndices.push_back(tempRidges.find((*hrit))->second.getVertexList()[2]); vertexIndices.push_back(furthest->getId()); sort(vertexIndices.begin(), vertexIndices.end()); long facetId = generateId(&vertexIndices); vertexIndices.clear(); facet *newFacet = new facet(); newFacet->setId(facetId); tempFacets.insert(pair<long,facet>(facetId, *newFacet)); newFacet=&tempFacets.find(facetId)->second; if(tempRidges.find((*hrit))->second.getNeighbour1()) { tempRidges.find((*hrit))->second.setNeighbour2(newFacet->getId()); newFacet->insertContaining2dSimplex(*hrit); } else { tempRidges.find((*hrit))->second.setNeighbour1(newFacet->getId()); newFacet->insertContaining2dSimplex(*hrit); } for(int i=0; i<3; i++) { for(int j=0,k=0; k<2; j++,k++) { if(j==i) { k--; continue; } vertexIndices.push_back(tempRidges.find((*hrit))->second.getVertexList()[j]); } vertexIndices.push_back(furthest->getId()); sort(vertexIndices.begin(),vertexIndices.end()); ridge *newRidge; // newRidge->setId(&vertexIndices); long tempId = generateId(&vertexIndices); if(tempRidges.find(tempId)==tempRidges.end()) { newRidge = new ridge(); newRidge->setId(tempId); tempRidges.insert(pair<long,ridge>(tempId,*newRidge)); newRidge = &tempRidges.find(tempId)->second; for(vector<long>::iterator viter = vertexIndices.begin(); viter!=vertexIndices.end(); viter++) { newRidge->getVertexList().push_back(*viter); } } else { newRidge = &tempRidges.find(tempId)->second; } vertexIndices.clear(); if(newRidge->getNeighbour1()==0) newRidge->setNeighbour1(newFacet->getId()); else newRidge->setNeighbour2(newFacet->getId()); newFacet->insertContaining2dSimplex(newRidge->getId()); } deque<vertex4d>::pointer v[4]; v[0]= &(verticesOfHull.find(furthest->getId())->second); for(int i=1; i<4; i++) { v[i]=&(verticesOfHull.find(tempRidges.find(*hrit)->second.getVertexList()[i-1])->second); } newFacet->calcNormOffset(v, centroid); facetIdList.push_back(newFacet->getId()); for(deque<long>::iterator blvit=bucketLessVertices.begin(); blvit!=bucketLessVertices.end(); blvit++) { if(!verticesOfHull.find(*blvit)->second.getBucketAssignmentStatus() &&verticesOfHull.find(*blvit)->second.isAbove(newFacet)) { newFacet->putInBucket((*blvit)); verticesOfHull.find(*blvit)->second.insertVisibleFacet(newFacet->getId()); verticesOfHull.find(*blvit)->second.setAssignedToBucket(true); } } setFurthestPoint(newFacet->getId()); } for(deque<long>::iterator blvit=bucketLessVertices.begin(); blvit!=bucketLessVertices.end(); blvit++) { if(verticesOfHull.find(*blvit)->second.getBucketAssignmentStatus()==false) { verticesOfHull.find(*blvit)->second.getVisibleFacets().clear(); verticesOfHull.find(*blvit)->second.setAssignedToBucket(true); } } }

int main(int argc, char* argv[]) { const int test_case = 2; signal(SIGINT, &signal_handler); #ifndef WIN32 void* (*AppServer[test_case])(void*); #else DWORD (WINAPI *AppServer[test_case])(LPVOID); #endif AppServer[0] = AppServer_TCP; AppServer[1] = AppServer_UDT; cout << "Start AppServer Mode # Callee" << endl; UDT::startup(); #ifndef WIN32 pthread_t srv_udt, srv_tcp; pthread_create(&srv_tcp, NULL, AppServer[0], NULL); pthread_create(&srv_udt, NULL, AppServer[1], NULL); //pthread_join(srv_udt, NULL); //pthread_join(srv_tcp, NULL); #else HANDLE srv_udt, srv_tcp; srv_tcp = CreateThread(NULL, 0, AppServer[0], NULL, 0, NULL); srv_udt = CreateThread(NULL, 0, AppServer[1], NULL, 0, NULL); //WaitForSingleObject(srv_udt, INFINITE); //WaitForSingleObject(srv_tcp, INFINITE); #endif //////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////// cout << "Run Task loop ...\n"; main_running = 1; while (main_running) { if (!taskQueue.empty()) { switch (taskQueue.front()->header.cmd) { case CMD_C_DISCONNECT: { connectMap_iter = connectMapKeyC.find(taskQueue.front()->header.cliFD); if (connectMap_iter != connectMapKeyC.end()) { UDT::epoll_remove_ssock(tcp_eid, connectMap_iter->second); #ifndef WIN32 close(connectMap_iter->second); #else closesocket(connectMap_iter->second); #endif } taskQueue.pop_front(); } break; case CMD_CONNECT: { pTcp_sock = new SYSSOCKET; if (createTCPSocket(*pTcp_sock, 0) < 0) { cout << "\tcan't create tcp socket!" << endl; } map_insert(&connectMapKeyC, taskQueue.front()->header.cliFD, *pTcp_sock); map_insert(&connectMapKeyS, *pTcp_sock, taskQueue.front()->header.cliFD); if (tcp_connect(*pTcp_sock, REMOTE_PORT) < 0) { printf("\tCan't connect local port 80\n"); } UDT::epoll_add_ssock(tcp_eid, *pTcp_sock); taskQueue.pop_front(); } break; case CMD_S_DISCONNECT: { char* buftmp = (char*)(taskQueue.front()); int res = 0; int ssize = 0; //UDT::perfmon(client, &trace); while (ssize < udtsize) { //int scv_size; //int var_size = sizeof(int); //UDT::getsockopt(client, 0, UDT_SNDDATA, &scv_size, &var_size); if (UDT::ERROR == (res = UDT::send(client, buftmp + ssize, udtsize - ssize, 0))) { cout << "send:" << UDT::getlasterror().getErrorMessage() << endl; break; } ssize += res; } //printf("ok.[%d]\n", res); //UDT::perfmon(client, &trace); //cout << "\tspeed = " << trace.mbpsSendRate << "Mbits/sec" << endl; taskQueue.pop_front(); } break; case CMD_DATA_S2T: { connectMap_iter = connectMapKeyC.find(taskQueue.front()->header.cliFD); if (connectMap_iter != connectMapKeyC.end()) { int rs = send(connectMap_iter->second, taskQueue.front()->payload.buf, taskQueue.front()->payload.len, 0); if (0 > rs) cout << "\t CMD_DATA_S2T error1.\n"; else if (rs == 0) printf("\t CMD_DATA_S2T disconnect.\n"); } taskQueue.pop_front(); } break; default: break; } } } //////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////// UDT::cleanup(); cout << "AppServer # Callee " << " end." << endl; return 0; }

int getMin() { //Returns minimum of current existing elements of queue //Complexity - O(1) return Min.front(); }

deque<deque<int>> center_mat(deque<deque<int>> src_mat){ deque<deque<int>> t_mat; deque<int> vec_zero; int marge_gauche=0; int marge_droite=0; int marge_haut=0; int marge_bas=0; int delta_x = 0; int delta_y = 0; int temp_size; bool stop; stop = false; //Marge Gauche for(int i=0;i<src_mat.size();i++){ for(int j=0;j<src_mat[i].size();j++){ if(!stop && src_mat[j][i]){ marge_gauche = i; stop = true; } } } stop = false; //Marge Droite for(int i=src_mat.size()-1;i>=0;i--){ for(int j=0;j<src_mat[i].size();j++){ if(!stop && src_mat[j][i]){ marge_droite = src_mat.size()-i; stop = true; } } } stop = false; //Marge Haut for(int i=0;i<src_mat.size();i++){ for(int j=0;j<src_mat[i].size();j++){ if(!stop && src_mat[i][j]){ marge_haut = i; stop = true; } } } stop = false; //Marge Bas for(int i=src_mat.size()-1;i>=0;i--){ for(int j=0;j<src_mat[i].size();j++){ if(!stop && src_mat[i][j]){ marge_bas = src_mat.size()-i; stop = true; } } } delta_x = (marge_droite-marge_gauche)/2; delta_y = (marge_bas-marge_haut)/2; cout << delta_x << endl; cout << delta_y << endl; vec_zero.resize(src_mat.size()); temp_size = src_mat.size(); // Lignes de zeros if(delta_y>0){ for(int i=0;i<delta_y;i++){ src_mat.push_front(vec_zero); } src_mat.resize(temp_size); }else{ for(int i=0;i<-delta_y+1;i++){ src_mat.push_back(vec_zero); } src_mat.erase(src_mat.begin(),src_mat.begin()-delta_y); } // Colonnes de zeros if(delta_x>0){ for (int i=0; i<src_mat.size(); i++){ for(int j=0;j<delta_x;j++){ src_mat[i].push_front(0); } src_mat[i].resize(temp_size); } }else{ for (int i=0; i<src_mat.size(); i++){ for(int j=0;j<-delta_x+1;j++){ src_mat[i].push_back(0); src_mat[i].erase(src_mat[i].begin()); } } } return src_mat; }

/* * flightLoop * 1) Initialise copter systems * 2) Wait for user allowance to fly. * 3) Read in list of waypoints * 4) Fly to first waypoint, wait, fly to next, etc.. * 5) If the end is reached, stop. * * The user may stop the flight at any time. It will continue if the user resumes. At any * point, the user may stop the current flight path and change the waypoint configuration. Upon * resuming flight, the copter will read in the new list of waypoints and start at the * beginning. */ void waypoints_loop1(hardware &hardware_list, Logger &log, deque<coord> &waypoints_list, string config_filename) { cout << "\033[1;32m[WAYPTS]\033[0m Waypoints thread initiated, travelling to the following waypoints:" << endl; char str_buf[BUFSIZ]; log.clearLog(); time_t start, now, last_displayed; time(&start); time(&now); time(&last_displayed); //Grab references to hardware FlightBoard *fb = hardware_list.fb; GPS *gps = hardware_list.gps; IMU *imu = hardware_list.imu; bool useimu = hardware_list.IMU_Working; double yaw = 0; //Configure configurable variables (if file is given) if(!config_filename.empty()) { loadParameters(config_filename); } //Construct PID controller PID controller = PID(-Kp, -Ki, -Kd, MAIN_LOOP_DELAY, 3, 0.95); //Construct buzzer Buzzer cowbell; cowbell.needs_more(); usleep((int)(BUZZER_DURATION*1.1)*1000*1000); //Print list of waypoints for(size_t i = 0; i != waypoints_list.size(); i++) { cout << " " << i+1 << ": (" << setprecision(6) << waypoints_list[i].lat << ", " << setprecision(6) << waypoints_list[i].lon << ")" << endl; } //Wait here for auto mode and conduct bearing test if necessary state = 6; cout << "\033[1;33m[WAYPTS]\033[0m Waiting for auto mode." << endl; while ( !gpio::isAutoMode() && !exitProgram) usleep(500*1000); cout << "\033[1;31m[WAYPTS]\033[0m Auto mode engaged." << endl; if (!useimu && !exitProgram) { cowbell.playBuzzer(0.25, 10, 100); cout << "\033[1;31m[WAYPTS]\033[0m Conducting bearing test..." << endl; state = 5; yaw = inferBearing(fb, gps); cout << "\033[1;31m[WAYPTS]\033[0m Bearing test complete." << endl; } state = 1; //Initialise loop variables coord currentCoord = {-1, -1}; double distanceToNextWaypoint; double bearingToNextWaypoint; FB_Data course = {0, 0, 0, 0}; int pastState = -1; velocity flightVector = {-1, -1}; cout << "\033[1;32m[WAYPTS]\033[0m Starting main loop." << endl; try { // Check for any errors, and stop the copter. while(!exitProgram) { currentCoord = getCoord(gps); //Write data for Michael time(&now); if (!waypoints_list.empty()) { sprintf(str_buf, "%.f,%3.6f,%3.6f,%3.6f,%3.6f", difftime(now, start), currentCoord.lat, currentCoord.lon, waypoints_list[wp_it].lat, waypoints_list[wp_it].lon); } else { sprintf(str_buf, "%.f,%3.6f,%3.6f,,", difftime(now, start), currentCoord.lat, currentCoord.lon); } log.writeLogLine(str_buf, false); if(!waypoints_list.empty()) { distanceToNextWaypoint = calculate_distance(currentCoord, waypoints_list[wp_it]); bearingToNextWaypoint = calculate_bearing(currentCoord, waypoints_list[wp_it]); } if (useimu) yaw = getYaw(imu); /* State 4: Manual mode. */ if (!gpio::isAutoMode()) { state = 4; wp_it = 0; exitProgram = true; /* State 0: All stop */ } else if (waypoints_list.empty() || wp_it == waypoints_list.size() || userState == 0 ) { state = 11; userState = 0; wp_it = 0; exitProgram = true; /* State 3: Error. */ } else if (state == 3 || !checkInPerth(¤tCoord)) { state = 3; exitProgram = true; /* State 2: At waypoint. */ } else if (distanceToNextWaypoint < WAYPOINT_RADIUS) { state = 2; /* State 1: Travelling to waypoint. */ } else { state = 1; } /* Only give output if the state changes. Less spamey.. */ /* Edit: or if travelling to waypoint. Print details every second */ if (pastState != state || (state == 1 && difftime(now, last_displayed) >0.9)) { switch (state) { case 0: cout << "\033[1;32m[WAYPTS]\033[0m All stop." << endl; break; case 1: cout << "\033[1;32m[WAYPTS]\033[0m Travelling to waypoint " << wp_it << ", at (" << waypoints_list[wp_it].lat << "," << waypoints_list[wp_it].lon << ")" << endl; break; case 2: cout << "\033[1;32m[WAYPTS]\033[0m At waypoint" << wp_it << "." << endl; break; case 3: cout << "\033[31m[WAYPTS]\033[0m Error reading GPS." << endl; case 4: cout << "\033[31m[WAYPTS]\033[0m Manual mode engaged." << endl; break; } cout << "\033[1;33m[WAYPTS]\033[0m In state " << state << "." << endl; cout << "\033[1;33m[WAYPTS]\033[0m Facing " << setprecision(6) << yaw << ", at coordinates (" << currentCoord.lat << ", " << currentCoord.lon << ")" << endl; cout << "\033[1;33m[WAYPTS]\033[0m The next waypoint is at (" << setprecision(6) << waypoints_list[wp_it].lat << ", " << waypoints_list[wp_it].lon << ")" << endl; cout << "\033[1;33m[WAYPTS]\033[0m It is " << setprecision(7) << distanceToNextWaypoint << "m away, at a bearing of " << bearingToNextWaypoint << "." << endl; pastState = state; last_displayed = now; } switch(state) { case 0: //Case 0: Not in auto mode, standby fb->setFB_Data(&stop); //Stop moving /* log.writeLogLine("\033[1;32m[WAYPTS]\033[0m Manual mode"); sprintf(str_buf, "[WAYPTS] Currently at %f %f.", currentCoord.lat, currentCoord.lon); log.writeLogLine(str_buf); */ break; case 1: flightVector = get_velocity(&controller, distanceToNextWaypoint, bearingToNextWaypoint, SPEED_LIMIT_); setCourse(&course, flightVector, yaw); fb->setFB_Data(&course); //Give command to flight boars /* sprintf(str_buf, "[WAYPTS] Aileron is %d, Elevator is %d", course.aileron, course.elevator); log.writeLogLine(str_buf); sprintf(str_buf, "[WAYPTS] Moving to next waypoint. It has latitude %f and longitude %f.", waypoints_list[wp_it].lat, waypoints_list[wp_it].lon); log.writeLogLine(str_buf); sprintf(str_buf, "[WAYPTS] Currently at %f %f, moving %f m at a bearing of %f degrees.", currentCoord.lat, currentCoord.lon, distanceToNextWaypoint, bearingToNextWaypoint); log.writeLogLine(str_buf); */ break; case 2: fb->setFB_Data(&stop); cowbell.needs_more(); /* log.writeLogLine("\033[1;32m[WAYPTS]\033[0m Reached waypoint, stopping"); */ wp_it++; if(repeatLoop && wp_it == waypoints_list.size()) { wp_it = 0; } usleep(WAIT_AT_WAYPOINTS*1000); controller.clear(); cout << "\033[1;32m[WAYPTS]\033[0m Moving to next waypoint." << endl; break; case 3: default: fb->setFB_Data(&stop); /* log.writeLogLine("\033[31m[WAYPTS]\033[0m Error reading GPS, stopping"); */ break; } usleep(MAIN_LOOP_DELAY*1000); } } catch (...) { cout << "\033[31m[WAYPTS]\033[0m Error encountered. Stopping copter." << endl; fb->setFB_Data(&stop); state = 3; } cout << "\033[1;32m[WAYPTS]\033[0m Waypoints flight loop terminating." << endl; cowbell.I_got_a_fever(); usleep(2100*1000); }

vector<float> extract_variables(deque<deque<int>> img){ vector<float> variables; vector<float> variables_temp_pi; deque<deque<int>> m_img = mirror_mat_horizontal(img); int sumHist = 0; //Horizontal Histogram for(int i=0;i<img.size();i++){ for(int j=0;j<img.size();j++){ sumHist+=img[i][j]; } variables.push_back(sumHist); sumHist = 0; } //Vertical Histogram for(int i=0;i<img.size();i++){ for(int j=0;j<img.size();j++){ sumHist+=img[j][i]; } variables.push_back(sumHist); sumHist = 0; } //+pi/4 Histogram for (int i = 0; i < 2 * 8 - 1; ++i) { int z = i < 8 ? 0 : i - 8 + 1; for (int j = z; j <= i - z; ++j) { sumHist+=img[j][i - j]; } variables_temp_pi.push_back(sumHist); sumHist = 0; } reverse(variables_temp_pi.begin(),variables_temp_pi.end()); variables.insert(variables.end(),variables_temp_pi.begin(),variables_temp_pi.end()); variables_temp_pi.clear(); //-pi/4 Histogram for (int i = 0; i < 2 * 8 - 1; ++i) { int z = i < 8 ? 0 : i - 8 + 1; for (int j = z; j <= i - z; ++j) { sumHist+=m_img[j][i - j]; } variables_temp_pi.push_back(sumHist); sumHist = 0; } reverse(variables_temp_pi.begin(),variables_temp_pi.end()); variables.insert(variables.end(),variables_temp_pi.begin(),variables_temp_pi.end()); //quadrans for(int i=0;i<2;i++){ for(int j=0;j<2;j++){ for(int k=0;k<4;k++){ for(int l=0;l<4;l++){ sumHist+=img[4*i+k][4*j+l]; } } variables.push_back(sumHist); sumHist = 0; } } //taux de presence for(int i=0;i<img.size();i++){ for(int j=0;j<img.size();j++){ if(img[i][j]){ sumHist+=img[i][j]; } } } variables.push_back(sumHist/1024.0); //Deletes useless variables (all zero) variables.erase(variables.begin() + 45); variables.erase(variables.begin() + 39); variables.erase(variables.begin() + 31); variables.erase(variables.begin() + 30); variables.erase(variables.begin() + 17); variables.erase(variables.begin() + 16); variables.erase(variables.begin() + 15); variables.erase(variables.begin() + 7); return variables; }

void f(deque<Card>& dc, My_rand& r) { random_shuffle(dc.begin(), dc.end(), r); }

int putIntoTour(int length, int **adjacencyMatrix, const int &n, int vertex) { tour.insert(findClosest(vertex, adjacencyMatrix),vertex); return 0; }

bool operator==(n_t a) { if(number.size() > 15) return(0); else return(this->regular() == a); }

int main(){ scanf("%d %d",&n,&l); for (int i=0; i<n; i++) { scanf("%d %d",&a[i].first, &a[i].second); a[i].second = abs(a[i].second); } sort(a, a+n); for (int i=0; i<n; ) { int e = i; while(e < n && a[e].first == a[i].first) e++; while (stk.size() >= 2 && cross(stk[stk.size()-2], stk.back()) > cross(stk.back(), a[i])) { stk.pop_back(); } stk.push_back(a[i]); i = e; } double ret = 0; while(stk.size() >= 2 && cross(stk[0], stk[1]) < 0) stk.pop_front(); while(stk.size() >= 2 && cross(stk[stk.size()-2], stk.back()) > l) stk.pop_back(); ret = max(ret, solve(0, cross(stk[0], stk[1]), stk[0])); ret = max(ret, solve(cross(stk[stk.size()-2], stk.back()), l, stk.back())); for(int i=1; i+1<stk.size(); i++){ ret = max(ret, solve(cross(stk[i-1], stk[i]), cross(stk[i], stk[i+1]), stk[i])); } printf("%lf",ret); }

unsigned int size() { return(number.size()); }

int main(){ int n; int i,j; int u,v; int flag; int count; int f,s; char c; int r; int lc; node nn,cn; int ma,lim; count=0; while(true){ scanf("%d",&n); if(n==0){ break; } if(count!=0){ printf("\n"); } count=1; sl.clear(); for(i=0;i<n;i++){ scanf("%s",str[i]); u=strlen(str[i]); l[i]=u; for(j=0;j<u;j++){ nn.idx=i; nn.os=j; nn.f=0; nn.s=0; sl.push_back(nn); } } sort(sl.begin(),sl.end(),cmpa); u=sl.size(); c=0; v=0; for(i=0;i<u;i++){ if(str[sl[i].idx][sl[i].os]!=c){ v++; c=str[sl[i].idx][sl[i].os]; } ra[sl[i].idx][sl[i].os]=v; } r=1; while(true){ flag=0; for(i=0;i<u;i++){ sl[i].f=ra[sl[i].idx][sl[i].os]; if((sl[i].os+r)<l[sl[i].idx]){ sl[i].s=ra[sl[i].idx][sl[i].os+r]; flag=1; }else{ sl[i].s=0; } } if(flag==0){ break; } sort(sl.begin(),sl.end(),cmpb); v=0; f=-1; s=-1; for(i=0;i<u;i++){ if(sl[i].f!=f || sl[i].s!=s){ v++; f=sl[i].f; s=sl[i].s; } ra[sl[i].idx][sl[i].os]=v; } r*=2; } for(i=0;i<u;i++){ ra[sl[i].idx][sl[i].os]=i; } for(i=0;i<n;i++){ lc=0; for(j=0;j<l[i];j++){ if(ra[i][j]==0){ lcp[i][j]=2147483647; }else{ v=ra[i][j]-1; if(lc>0){ lc--; } while((j+lc)<l[i] && (sl[v].os+lc)<l[sl[v].idx]){ if(str[i][j+lc]!=str[sl[v].idx][sl[v].os+lc]){ break; } lc++; } lcp[i][j]=lc; } } } for(i=0;i<n;i++){ lmap[i]=0; } for(i=0;i<u;i++){ hemap[i]=0; } he.clear(); de.clear(); v=0; flag=0; out.clear(); ma=0; for(i=0;i<u;i++){ if(lmap[sl[i].idx]==0){ v++; } lmap[sl[i].idx]++; if(i>0){ he.push_back(i); push_heap(he.begin(),he.end(),cmpc); } de.push_back(i); while(!de.empty()){ if(lmap[sl[de.front()].idx]>1){ hemap[de.front()]=1; lmap[sl[de.front()].idx]--; de.pop_front(); }else if(lmap[sl[de.front()].idx]==1 && (v-1)*2>n && v>2){ v--; hemap[de.front()]=1; lmap[sl[de.front()].idx]--; de.pop_front(); }else{ break; } } hemap[de.front()]=1; while(!he.empty()){ if(hemap[he.front()]==1){ pop_heap(he.begin(),he.end(),cmpc); he.pop_back(); }else{ break; } } if(v*2>n && v>=2){ cn=sl[he.front()]; lim=lcp[cn.idx][cn.os]; if(lim>ma){ out.clear(); out.push_back(cn); flag=1; ma=lim; }else if(lim==ma){ if(flag==0){ out.push_back(cn); flag=1; } }else{ flag=0; } }else{ flag=0; } } /*for(i=0;i<u;i++){ printf(" %d %s %d\n",sl[i].idx,&str[sl[i].idx][sl[i].os],lcp[sl[i].idx][sl[i].os]); }*/ if(ma==0){ printf("?\n"); }else{ u=out.size(); for(i=0;i<u;i++){ c=str[out[i].idx][out[i].os+ma]; str[out[i].idx][out[i].os+ma]=0; printf("%s\n",&str[out[i].idx][out[i].os]); str[out[i].idx][out[i].os+ma]=c; } } } return 0; }

void clear(void) { LockGuard guard(mutex_); data_buffer_.clear(); intensity_data_.length_data.clear(); }

void LinkMap::printRegions(ostream &os, deque<Region *> ®ions, Offset globalOffset) { deque<Region *>::iterator reg_it; for(reg_it = regions.begin(); reg_it != regions.end(); ++reg_it) { printRegion(os, *reg_it, globalOffset); } }

int connect_all_the_parts(deque<set<int> > & E, const deque<deque<int> > & member_list, const deque<deque<int> > & link_list) { deque<int> degrees; for(int i=0; i<link_list.size(); i++) degrees.push_back(link_list[i][link_list[i].size()-1]); deque<set<int> > en; // this is the en of the subgraph { set<int> first; for(int i=0; i<member_list.size(); i++) en.push_back(first); } multimap <int, int> degree_node; for(int i=0; i<degrees.size(); i++) degree_node.insert(degree_node.end(), make_pair(degrees[i], i)); int var=0; while (degree_node.size() > 0) { multimap<int, int>::iterator itlast= degree_node.end(); itlast--; multimap <int, int>::iterator itit= itlast; deque <multimap<int, int>::iterator> erasenda; int inserted=0; for (int i=0; i<itlast->first; i++) { if(itit!=degree_node.begin()) { itit--; en[itlast->second].insert(itit->second); en[itit->second].insert(itlast->second); inserted++; erasenda.push_back(itit); } else break; } for (int i=0; i<erasenda.size(); i++) { if(erasenda[i]->first>1) degree_node.insert(make_pair(erasenda[i]->first - 1, erasenda[i]->second)); degree_node.erase(erasenda[i]); } var+= itlast->first - inserted; degree_node.erase(itlast); } // this is to randomize the subgraph ------------------------------------------------------------------- // ---------------------------------------------------------- deque<int> degree_list; for(int kk=0; kk<degrees.size(); kk++) for(int k2=0; k2<degrees[kk]; k2++) degree_list.push_back(kk); for(int run=0; run<10; run++) for(int node_a=0; node_a<degrees.size(); node_a++) for(int krm=0; krm<en[node_a].size(); krm++) { int random_mate=degree_list[irand(degree_list.size()-1)]; while (random_mate==node_a) random_mate=degree_list[irand(degree_list.size()-1)]; if (en[node_a].insert(random_mate).second) { deque <int> out_nodes; for (set<int>::iterator it_est=en[node_a].begin(); it_est!=en[node_a].end(); it_est++) if ((*it_est)!=random_mate) out_nodes.push_back(*it_est); int old_node=out_nodes[irand(out_nodes.size()-1)]; en[node_a].erase(old_node); en[random_mate].insert(node_a); en[old_node].erase(node_a); deque <int> not_common; for (set<int>::iterator it_est=en[random_mate].begin(); it_est!=en[random_mate].end(); it_est++) if ((old_node!=(*it_est)) && (en[old_node].find(*it_est)==en[old_node].end())) not_common.push_back(*it_est); int node_h=not_common[irand(not_common.size()-1)]; en[random_mate].erase(node_h); en[node_h].erase(random_mate); en[node_h].insert(old_node); en[old_node].insert(node_h); } } // now there is a rewiring process to avoid "mate nodes" (nodes with al least one membership in common) to link each other int var_mate=0; for(int i=0; i<degrees.size(); i++) for(set<int>::iterator itss= en[i].begin(); itss!=en[i].end(); itss++) if(they_are_mate(i, *itss, member_list)) { var_mate++; } //cout<<"var mate = "<<var_mate<<endl; int stopper_mate=0; int mate_trooper=10; while(var_mate>0) { //cout<<"var mate = "<<var_mate<<endl; int best_var_mate=var_mate; // ************************************************ rewiring for(int a=0; a<degrees.size(); a++) for(set<int>::iterator its= en[a].begin(); its!=en[a].end(); its++) if(they_are_mate(a, *its, member_list)) { int b=*its; int stopper_m=0; while (true) { stopper_m++; int random_mate = degree_list[irand(degree_list.size()-1)]; while (random_mate==a || random_mate==b) random_mate = degree_list[irand(degree_list.size()-1)]; if(!(they_are_mate(a, random_mate, member_list)) && (en[a].find(random_mate)==en[a].end())) { deque <int> not_common; for (set<int>::iterator it_est=en[random_mate].begin(); it_est!=en[random_mate].end(); it_est++) if ((b!=(*it_est)) && (en[b].find(*it_est)==en[b].end())) not_common.push_back(*it_est); if(not_common.size()>0) { int node_h=not_common[irand(not_common.size()-1)]; en[random_mate].erase(node_h); en[random_mate].insert(a); en[node_h].erase(random_mate); en[node_h].insert(b); en[b].erase(a); en[b].insert(node_h); en[a].insert(random_mate); en[a].erase(b); if(!they_are_mate(b, node_h, member_list)) var_mate-=2; if(they_are_mate(random_mate, node_h, member_list)) var_mate-=2; break; } } if(stopper_m==en[a].size()) break; } break; // this break is done because if you erased some link you have to stop this loop (en[i] changed) } // ************************************************ rewiring if(var_mate==best_var_mate) { stopper_mate++; if(stopper_mate==mate_trooper) break; } else stopper_mate=0; //cout<<"var mate = "<<var_mate<<endl; } //cout<<"var mate = "<<var_mate<<endl; for (int i=0; i<en.size(); i++) { for(set<int>::iterator its=en[i].begin(); its!=en[i].end(); its++) if(i<*its) { E[i].insert(*its); E[*its].insert(i); } } return 0; }

pair<bi_node, bi_node> expand_queue( deque<bi_node>& q_expand, deque<bi_node>& q_exist, bi_node **s, int m, int n, int **visited, int flag) {//对q_expand队列的头节点的所有邻节点进行扩展 //在将某个邻节点加入队列q_expand之前，先检查该点是否已经被q_expand队列访问过 //或者查找该点是否已经存在于q_exist队列中 //若已经存在，则q_expand的头节点与q_exist中该邻节点是相邻的，即两队列相遇 //用flag标志这两个队列中哪个是q_beg，哪个是q_end //返回两相遇节点，first是q_beg中节点，second是q_end中节点 deque<bi_node>::iterator pos; bi_node p = q_expand.front(); q_expand.pop_front(); //扩展q_expand头节点的四个方向上的邻节点 if(p.b_x - 1 >= 0 && !visited[p.b_y][p.b_x - 1]){ //判断矩阵边界与是否已经被访问过 //C++算法find需要结构体bi_node提供比较操作operator== //在search.h中该操作操作定义两节点的xy坐标相等即为同一点，不考虑父节点指针 if((pos = find(q_exist.begin(), q_exist.end(), s[p.b_y][p.b_x - 1])) != q_exist.end()){ //若在q_exist中找到q_expand头节点的该邻节点，则返回相遇的两节点 //flag == 1标志本次扩展的队列是q_beg //返回的pair中first是q_beg中节点，second是q_end中节点 if(flag == 1) return(pair<bi_node, bi_node>(p, *pos)); //flag == 2标志本次扩展的队列是q_end //返回的节点顺序与flag == 1是相反的 if(flag == 2) return(pair<bi_node, bi_node>(*pos, p)); } //若没有在q_exist中找到该邻节点则两队列未在此节点处相遇 //将q_expand队列扩展至该邻节点，并标记其父节点指针 s[p.b_y][p.b_x - 1].b_fa.first = p.b_x; s[p.b_y][p.b_x - 1].b_fa.second = p.b_y; q_expand.push_back(s[p.b_y][p.b_x - 1]); visited[p.b_y][p.b_x - 1] = 1; } if(p.b_x + 1 < n && !visited[p.b_y][p.b_x + 1]){ if((pos = find(q_exist.begin(), q_exist.end(), s[p.b_y][p.b_x + 1])) != q_exist.end()){ if(flag == 1) return(pair<bi_node, bi_node>(p, *pos)); if(flag == 2) return(pair<bi_node, bi_node>(*pos, p)); } s[p.b_y][p.b_x + 1].b_fa.first = p.b_x; s[p.b_y][p.b_x + 1].b_fa.second = p.b_y; q_expand.push_back(s[p.b_y][p.b_x + 1]); visited[p.b_y][p.b_x + 1] = 1; } if(p.b_y - 1 >= 0 && !visited[p.b_y - 1][p.b_x]){ if((pos = find(q_exist.begin(), q_exist.end(), s[p.b_y - 1][p.b_x])) != q_exist.end()){ if(flag == 1) return(pair<bi_node, bi_node>(p, *pos)); if(flag == 2) return(pair<bi_node, bi_node>(*pos, p)); } s[p.b_y - 1][p.b_x].b_fa.first = p.b_x; s[p.b_y - 1][p.b_x].b_fa.second = p.b_y; q_expand.push_back(s[p.b_y - 1][p.b_x]); visited[p.b_y - 1][p.b_x] = 1; } if(p.b_y + 1 < m && !visited[p.b_y + 1][p.b_x]){ if((pos = find(q_exist.begin(), q_exist.end(), s[p.b_y + 1][p.b_x])) != q_exist.end()){ if(flag == 1) return(pair<bi_node, bi_node>(p, *pos)); if(flag == 2) return(pair<bi_node, bi_node>(*pos, p)); } s[p.b_y + 1][p.b_x].b_fa.first = p.b_x; s[p.b_y + 1][p.b_x].b_fa.second = p.b_y; q_expand.push_back(s[p.b_y + 1][p.b_x]); visited[p.b_y + 1][p.b_x] = 1; } //一次扩展只是从q_expand队列的头节点向外扩展四个邻节点 //若这次扩展中两队列未相遇则返回q_expand的尾部迭代器 return(pair<bi_node, bi_node>(*q_expand.end(), *q_expand.end())); }

int print_network(deque<set<int> > & E, const deque<deque<int> > & member_list, const deque<deque<int> > & member_matrix, deque<int> & num_seq) { int edges=0; int num_nodes=member_list.size(); deque<double> double_mixing; for (int i=0; i<E.size(); i++) { double one_minus_mu = double(internal_kin(E, member_list, i))/E[i].size(); double_mixing.push_back(1.- one_minus_mu); edges+=E[i].size(); } //cout<<"\n----------------------------------------------------------"<<endl; //cout<<endl; double density=0; double sparsity=0; for (int i=0; i<member_matrix.size(); i++) { double media_int=0; double media_est=0; for (int j=0; j<member_matrix[i].size(); j++) { double kinj = double(internal_kin_only_one(E[member_matrix[i][j]], member_matrix[i])); media_int+= kinj; media_est+=E[member_matrix[i][j]].size() - double(internal_kin_only_one(E[member_matrix[i][j]], member_matrix[i])); } double pair_num=(member_matrix[i].size()*(member_matrix[i].size()-1)); double pair_num_e=((num_nodes-member_matrix[i].size())*(member_matrix[i].size())); if(pair_num!=0) density+=media_int/pair_num; if(pair_num_e!=0) sparsity+=media_est/pair_num_e; } density=density/member_matrix.size(); sparsity=sparsity/member_matrix.size(); ofstream out1("network.dat"); for (int u=0; u<E.size(); u++) { set<int>::iterator itb=E[u].begin(); while (itb!=E[u].end()) out1<<u+1<<"\t"<<*(itb++)+1<<endl; } out1.close(); ofstream out2("community.dat"); for (int i=0; i<member_list.size(); i++) { out2<<i+1<<"\t"; for (int j=0; j<member_list[i].size(); j++) out2<<member_list[i][j]+1<<" "; out2<<endl; } out2.close(); cout<<"\n\n---------------------------------------------------------------------------"<<endl; cout<<"network of "<<num_nodes<<" vertices and "<<edges/2<<" edges"<<";\t average degree = "<<double(edges)/num_nodes<<endl; cout<<"\naverage mixing parameter: "<<average_func(double_mixing)<<" +/- "<<sqrt(variance_func(double_mixing))<<endl; cout<<"p_in: "<<density<<"\tp_out: "<<sparsity<<endl; ofstream statout("statistics.dat"); deque<int> degree_seq; for (int i=0; i<E.size(); i++) degree_seq.push_back(E[i].size()); statout<<"degree distribution (probability density function of the degree in logarithmic bins) "<<endl; log_histogram(degree_seq, statout, 10); statout<<"\ndegree distribution (degree-occurrences) "<<endl; int_histogram(degree_seq, statout); statout<<endl<<"--------------------------------------"<<endl; statout<<"community distribution (size-occurrences)"<<endl; int_histogram(num_seq, statout); statout<<endl<<"--------------------------------------"<<endl; statout<<"mixing parameter"<<endl; not_norm_histogram(double_mixing, statout, 20, 0, 0); statout<<endl<<"--------------------------------------"<<endl; statout.close(); cout<<endl<<endl; return 0; }

long_() { number.clear(); }

int internal_degree_and_membership (double mixing_parameter, int overlapping_nodes, int max_mem_num, int num_nodes, deque<deque<int> > & member_matrix, bool excess, bool defect, deque<int> & degree_seq, deque<int> &num_seq, deque<int> &internal_degree_seq, bool fixed_range, int nmin, int nmax, double tau2) { if(num_nodes< overlapping_nodes) { cerr<<"\n***********************\nERROR: there are more overlapping nodes than nodes in the whole network! Please, decrease the former ones or increase the latter ones"<<endl; return -1; } // member_matrix.clear(); internal_degree_seq.clear(); deque<double> cumulative; // it assigns the internal degree to each node ------------------------------------------------------------------------- int max_degree_actual=0; // maximum internal degree for (int i=0; i<degree_seq.size(); i++) { double interno=(1-mixing_parameter)*degree_seq[i]; int int_interno=int(interno); if (ran4()<(interno-int_interno)) int_interno++; if (excess) { while ( ( double(int_interno)/degree_seq[i] < (1-mixing_parameter) ) && (int_interno<degree_seq[i]) ) int_interno++; } if (defect) { while ( ( double(int_interno)/degree_seq[i] > (1-mixing_parameter) ) && (int_interno>0) ) int_interno--; } internal_degree_seq.push_back(int_interno); if (int_interno>max_degree_actual) max_degree_actual=int_interno; } // it assigns the community size sequence ----------------------------------------------------------------------------- powerlaw(nmax, nmin, tau2, cumulative); if (num_seq.empty()) { int _num_=0; if (!fixed_range && (max_degree_actual+1)>nmin) { _num_=max_degree_actual+1; // this helps the assignment of the memberships (it assures that at least one module is big enough to host each node) num_seq.push_back(max_degree_actual+1); } while (true) { int nn=lower_bound(cumulative.begin(), cumulative.end(), ran4())-cumulative.begin()+nmin; if (nn+_num_<=num_nodes + overlapping_nodes * (max_mem_num-1) ) { num_seq.push_back(nn); _num_+=nn; } else break; } num_seq[min_element(num_seq.begin(), num_seq.end()) - num_seq.begin()]+=num_nodes + overlapping_nodes * (max_mem_num-1) - _num_; } //cout<<"num_seq"<<endl; //prints(num_seq); int ncom=num_seq.size(); //cout<<"\n----------------------------------------------------------"<<endl; /* cout<<"community sizes"<<endl; for (int i=0; i<num_seq.size(); i++) cout<<num_seq[i]<<" "; cout<<endl<<endl; //*/ /* deque <int> first; for (int i=0; i<ncom; i++) member_matrix.push_back(first); // it puts the overlapping_nodes inside cout<<ncom<<endl; for (int i=degree_seq.size() - overlapping_nodes; i<degree_seq.size(); i++) { cout<<i<<endl; set<int> members; int hh=0; while(members.size()<max_mem_num) { int random_module=irand(ncom-1); if(member_matrix[random_module].size()!=num_seq[random_module]) members.insert(random_module); hh++; if(hh>3*num_nodes) { cerr<<"it seems that the overlapping nodes need more communities that those I provided. Please increase the number of communities or decrease the number of overlapping nodes"<<endl; return -1; } } for (set<int>::iterator its=members.begin(); its!=members.end(); its++) member_matrix[*its].push_back(i); } // it decides the memberships for the not overlapping nodes int moment_module=0; for (int i=0; i<num_nodes - overlapping_nodes; i++) { while(member_matrix[moment_module].size()==num_seq[moment_module]) moment_module++; member_matrix[moment_module].push_back(i); } */ // I have to assign the degree to the nodes deque<int> member_numbers; for(int i=0; i<overlapping_nodes; i++) member_numbers.push_back(max_mem_num); for(int i=overlapping_nodes; i<degree_seq.size(); i++) member_numbers.push_back(1); //prints(member_numbers); //prints(num_seq); if(build_bipartite_network(member_matrix, member_numbers, num_seq)==-1) { cerr<<"it seems that the overlapping nodes need more communities that those I provided. Please increase the number of communities or decrease the number of overlapping nodes"<<endl; return -1; } //printm(member_matrix); //cout<<"degree_seq"<<endl; //prints(degree_seq); //cout<<"internal_degree_seq"<<endl; //prints(internal_degree_seq); deque<int> available; for (int i=0; i<num_nodes; i++) available.push_back(0); for (int i=0; i<member_matrix.size(); i++) { for (int j=0; j<member_matrix[i].size(); j++) available[member_matrix[i][j]]+=member_matrix[i].size()-1; } //cout<<"available"<<endl; //prints(available); deque<int> available_nodes; for (int i=0; i<num_nodes; i++) available_nodes.push_back(i); deque<int> map_nodes; // in the position i there is the new name of the node i for (int i=0; i<num_nodes; i++) map_nodes.push_back(0); for (int i=degree_seq.size()-1; i>=0; i--) { int & degree_here=internal_degree_seq[i]; int try_this = irand(available_nodes.size()-1); int kr=0; while (internal_degree_seq[i] > available[available_nodes[try_this]]) { kr++; try_this = irand(available_nodes.size()-1); if(kr==3*num_nodes) { if(change_community_size(num_seq)==-1) { cerr<<"\n***********************\nERROR: this program needs more than one community to work fine"<<endl; return -1; } cout<<"it took too long to decide the memberships; I will try to change the community sizes"<<endl; cout<<"new community sizes"<<endl; for (int i=0; i<num_seq.size(); i++) cout<<num_seq[i]<<" "; cout<<endl<<endl; return (internal_degree_and_membership(mixing_parameter, overlapping_nodes, max_mem_num, num_nodes, member_matrix, excess, defect, degree_seq, num_seq, internal_degree_seq, fixed_range, nmin, nmax, tau2)); } } map_nodes[available_nodes[try_this]]=i; available_nodes[try_this]=available_nodes[available_nodes.size()-1]; available_nodes.pop_back(); } for (int i=0; i<member_matrix.size(); i++) { for (int j=0; j<member_matrix[i].size(); j++) member_matrix[i][j]=map_nodes[member_matrix[i][j]]; } for (int i=0; i<member_matrix.size(); i++) sort(member_matrix[i].begin(), member_matrix[i].end()); return 0; }

void append(d_t d) { number.push_back(d); }

int build_subgraphs(deque<set<int> > & E, const deque<deque<int> > & member_matrix, deque<deque<int> > & member_list, deque<deque<int> > & link_list, const deque<int> & internal_degree_seq, const deque<int> & degree_seq, const bool excess, const bool defect) { E.clear(); member_list.clear(); link_list.clear(); int num_nodes=degree_seq.size(); //printm(member_matrix); { deque<int> first; for (int i=0; i<num_nodes; i++) member_list.push_back(first); } for (int i=0; i<member_matrix.size(); i++) for (int j=0; j<member_matrix[i].size(); j++) member_list[member_matrix[i][j]].push_back(i); //printm(member_list); for (int i=0; i<member_list.size(); i++) { deque<int> liin; for (int j=0; j<member_list[i].size(); j++) { compute_internal_degree_per_node(internal_degree_seq[i], member_list[i].size(), liin); liin.push_back(degree_seq[i] - internal_degree_seq[i]); } link_list.push_back(liin); } // now there is the check for the even node (it means that the internal degree of each group has to be even and we want to assure that, otherwise the degree_seq has to change) ---------------------------- // ------------------------ this is done to check if the sum of the internal degree is an even number. if not, the program will change it in such a way to assure that. for (int i=0; i<member_matrix.size(); i++) { int internal_cluster=0; for (int j=0; j<member_matrix[i].size(); j++) { int right_index= lower_bound(member_list[member_matrix[i][j]].begin(), member_list[member_matrix[i][j]].end(), i) - member_list[member_matrix[i][j]].begin(); internal_cluster+=link_list[member_matrix[i][j]][right_index]; } if(internal_cluster % 2 != 0) { bool default_flag=false; if(excess) default_flag=true; else if(defect) default_flag=false; else if (ran4()>0.5) default_flag=true; if(default_flag) { // if this does not work in a reasonable time the degree sequence will be changed for (int j=0; j<member_matrix[i].size(); j++) { int random_mate=member_matrix[i][irand(member_matrix[i].size()-1)]; int right_index= lower_bound(member_list[random_mate].begin(), member_list[random_mate].end(), i) - member_list[random_mate].begin(); if ((link_list[random_mate][right_index]<member_matrix[i].size()-1) && (link_list[random_mate][link_list[random_mate].size()-1] > 0 )) { link_list[random_mate][right_index]++; link_list[random_mate][link_list[random_mate].size()-1]--; break; } } } else { for (int j=0; j<member_matrix[i].size(); j++) { int random_mate=member_matrix[i][irand(member_matrix[i].size()-1)]; int right_index= lower_bound(member_list[random_mate].begin(), member_list[random_mate].end(), i) - member_list[random_mate].begin(); if (link_list[random_mate][right_index] > 0 ) { link_list[random_mate][right_index]--; link_list[random_mate][link_list[random_mate].size()-1]++; break; } } } } } // ------------------------ this is done to check if the sum of the internal degree is an even number. if not, the program will change it in such a way to assure that. { set<int> first; for(int i=0; i<num_nodes; i++) E.push_back(first); } for (int i=0; i<member_matrix.size(); i++) { deque<int> internal_degree_i; for (int j=0; j<member_matrix[i].size(); j++) { int right_index= lower_bound(member_list[member_matrix[i][j]].begin(), member_list[member_matrix[i][j]].end(), i) - member_list[member_matrix[i][j]].begin(); internal_degree_i.push_back(link_list[member_matrix[i][j]][right_index]); } if(build_subgraph(E, member_matrix[i], internal_degree_i)==-1) return -1; } return 0; }

bool operator>=(n_t a) { if(number.size() > 15) return(1); else return(this->regular() >= a); }

void TreeAnalyzer::Analyze(int iEvent) { chain->GetEntry(iEvent); int run = fTreeRecord.run; if(mRunCnt.find(run) == mRunCnt.end()) { int ms = mRunCnt.size(); mRunCnt[run] = ms; RatioRecord.push_back(RATIO_RECORD()); RatioRecord.back().run = run; RatioRecord.back().NEvents = 0; RatioRecord.back().NSatEvents = 0; RatioRecord.back().NShiftedTS = 0; // statistics char buf[128]; sprintf(buf,"hTotSatEvt_%d",run); RatioRecord.back().hTotSatEvt = new TH2F(buf,"",14,0,14,16,0,16); sprintf(buf,"hSatEvtRatio_%d",run); RatioRecord.back().hSatEvtRatio = new TH2F(buf,"",14,0,14,16,0,16); } int runidx = mRunCnt.find(run)->second; RatioRecord[runidx].NEvents++; bool bSatEvent = false; bool bShiftedTS = false; for(int i=0; i<14; i++) for(int j=0; j<16; j++) { // calculate ratio and sum of the 2 TS for every event and channel double ratio = fTreeRecord.signal[i][j][5] / fTreeRecord.signal[i][j][4]; double sum = fTreeRecord.signal[i][j][4] + fTreeRecord.signal[i][j][5]; // commment: often the analysis only use the first five channels // therefor the cut on mod < 5 // check if saturation bit was set in the new RecHit reco if(/*i < 5 && */fTreeRecord.newRHs[i][j] != 0) { bSatEvent = true; RatioRecord[runidx].hTotSatEvt->Fill(i,j); RatioRecord[runidx].hSatEvtRatio->Fill(i,j); } // check if there is a event with shifted TS // but not in the noise region => Cut on ADC > 80 if(i < 5 && fTreeRecord.signalADC[i][j][5] > 80 && fTreeRecord.signal[i][j][4] < fTreeRecord.signal[i][j][5]) bShiftedTS = true; // go to the high energy region and save ratios // but be sure not to save saturated events if(fTreeRecord.signalADC[i][j][4] > 110 && fTreeRecord.signalADC[i][j][4] < 127 && fTreeRecord.signalADC[i][j][5] < fTreeRecord.signalADC[i][j][4]) { RatioRecord[runidx].vHighEnergyRatioTS[i][j].push_back(ratio); RatioRecord[runidx].vHighEnergySumTS[i][j].push_back(sum); RatioRecord[runidx].vHighEnergyTS4ADC[i][j].push_back(fTreeRecord.signalADC[i][j][4]); /****DEBUG**** if(runidx == 0 && i == 0 && j == 11) cout << "Run: " << run << "\t" << "Mod: " << i << " Sec: " << j << "\t" << "Ratio: " << ratio << " Sum: " << sum << endl; ****DEBUG****/ } // save ration and sum of all events // limit number to 1000 because of memspace if(RatioRecord[runidx].vgrTSRatio[i][j].size() < 1000 && fTreeRecord.signalADC[i][j][4] > 0 && fTreeRecord.signalADC[i][j][5] > 0 && ratio > 0 && ratio < 1) { RatioRecord[runidx].vgrTSRatio[i][j].push_back(ratio); RatioRecord[runidx].vgrTSSum[i][j].push_back(sum); RatioRecord[runidx].vgrTS4ADC[i][j].push_back(fTreeRecord.signalADC[i][j][4]); } } // Loop over Module & Sector // count number of saturated and shifted events if(bSatEvent) RatioRecord[runidx].NSatEvents++; if(bShiftedTS) RatioRecord[runidx].NShiftedTS++; }

void max() { if(!val.empty()) cout<<maxV.front()<<endl; }