POINT WFD_Opt::calcNext(POINT &currPosition, int **map, int width, int height, int index) { cerr << "*********************** check calcGRID " << endl; _scanList = *(_scanLists[index]); //set current robot position _currentPos = currPosition; FRONTIER_LIST found; // NOTE: Optimization disabled: _frontiers.clear(); static ofstream f_out; struct timeval startTime; struct timeval endTime; struct rusage ru; getrusage(RUSAGE_SELF, &ru); startTime = ru.ru_utime; found = findFrontiers(_currentPos, map, width, height); getrusage(RUSAGE_SELF, &ru); endTime = ru.ru_utime; double tS = startTime.tv_sec*1000000.0 + (startTime.tv_usec); double tE = endTime.tv_sec*1000000.0 + (endTime.tv_usec); double result = tE - tS; if (result != 0) { // f_out.open("exploration_execution_grid.txt", ios::app); f_out.open(_logFile, ios::app); f_out << tE - tS << endl; f_out.close(); } list<POINT_LIST >::iterator frontierItr; //insert all found frontiers for (frontierItr = found.begin(); frontierItr != found.end(); ++frontierItr) _frontiers.push_back(*frontierItr); _scanList.clear(); //cout << "DEBUG: total frontiers detected: " << _frontiers.size() << endl; //check if there's nothing left to explore if (_frontiers.size() == 0) return _currentPos; //get the lowest cost centroid return findBestCentroid(_frontiers, map, width, height); // FRONTIER_LIST::iterator itr = _frontiers.begin(); // POINT currCentroid, bestCentroid; // // bestCentroid = currCentroid = calcCentroid((*itr)); // maxScore = currScore = itr->size() / euclidianDist(currCentroid, _currentPos); // POINT_LIST::iterator j = itr->begin(); // cout << "DEBUG: Frontier (" << (*j).x << "," << (*j).y << ") size = " << std::fixed << std::setw(4) << itr->size() << " dist = " << std::setw(5) << std::setprecision(0) << euclidianDist(currCentroid, _currentPos) << " score = " << std::setw(5) << std::setprecision(2) << currScore << endl; // ++itr; // // // for (; itr != _frontiers.end(); ++itr) { // currCentroid = calcCentroid((*itr)); // currScore = itr->size() / euclidianDist(currCentroid, _currentPos); // j = itr->begin(); // cout << "DEBUG: Frontier (" << (*j).x << "," << (*j).y << ") size = " << std::fixed << std::setw(4) << itr->size() << " dist = " << std::setw(5) << std::setprecision(0) << euclidianDist(currCentroid, _currentPos) << " score = " << std::setw(5) << std::setprecision(2) << currScore << endl; // if (currScore > maxScore) { // maxScore = currScore; // bestCentroid = currCentroid; // } // } // //DEBUG // cout << "frontiers are: " << endl; // for (itr = _frontiers.begin(); itr != _frontiers.end(); ++itr) { // cout << "{ " ; // // POINT_LIST::iterator j = itr->begin(); //// for (; j != itr->end(); ++j) //// cout << "(" << (*j).x << "," << (*j).y << ") " ; // // cout << "(" << (*j).x << "," << (*j).y << ") " ; // // cout << "} size = " << itr->size() << endl; // } //return bestCentroid; *(_scanLists[index]) = _scanList; }
int main (int argc, char* argv[]) { int listSize = 0; int inversions = 0; string filename = "list"; string sort_type = ""; if (argc < 3) { cerr << USAGE_MESSAGE << endl; return -1; } // get the list size listSize = atoi(argv[1]); if (listSize <= 0) { cerr << "List size must be larger then zero." << endl; return -1; } // get the base filename filename = argv[2]; // seed the random number generator srand(time(NULL)); // open up the sorted and unsorted file streams sorted_list.open((filename + ".sorted").c_str()); unsorted_list.open((filename + ".unsorted").c_str()); // process rest of the command line based on the list type sort_type = argv[3]; if (sort_type == "random") { // generate a random list cout << "Generating a random list." << endl; generate_random(listSize); } else if (sort_type == "inorder") { // generate a list in order cout << "Generating an in-order list." << endl; generate_inorder(listSize); } else if (sort_type == "sortaorder") { // generate a list that's mostly in order if (argc != 5) { cerr << USAGE_MESSAGE_SORTAORDER << endl; return -1; } cout << "Generating a sorted list with random inversions." << endl; inversions = atoi(argv[4]); generate_sortaorder(listSize,inversions); } else if (sort_type == "revorder") { // generate a list in reverse order cout << "Generating a reverse in-order list." << endl; generate_inorder(listSize,true); } else if (sort_type == "revsortaorder") { // generate a list that's mostly in reverse order if (argc != 5) { cerr << USAGE_MESSAGE_REVSORTAORDER << endl; return -1; } cout << "Generating a reverse sorted list with random inversions." << endl; inversions = atoi(argv[4]); generate_sortaorder(listSize,inversions,true); } else { cerr << "Couldn't understand list type. Possible values are " << "random,inorder,sortaorder,revorder,revsortaorder." << endl; return -2; } // close the file streams sorted_list.close(); unsorted_list.close(); return 0; }
int main(int argv,char*argc[]) { int n,i; int op[10]; fin >> n; for(i=0; i <=n; ++i) op[i] = 0; op[n] = 2; i=1; int res,p,tmp; while(i>=1) { op[i]++; if(op[i]>3) { op[i] = 0; i--; } else if(i<n-1) { i++; } else { res = 0; p = 2; tmp = 0; for(int j=1;j<=n;++j) { tmp = tmp*10+j; if(op[j]!=1) { if(p==2) { res += tmp; } else { res -= tmp; } p = op[j]; tmp = 0; } } if(res==0) { for(int j=1;j<=n;++j) { fout << j; if(j<n) { if(op[j]==1) fout << ' '; else if(op[j]==2) fout << '+'; else if(op[j]==3) fout << '-'; } } fout << endl; } } } fin.close(); fout.close(); return 0; }
int main( int argc, char** argv ) { try { // Give usage information if no command line arguments were given if( argc == 1 ) { cerr << "Usage: " << argv[0] << " [filename]" << endl; return 0; } // pass input filename to the initialization function initializeScanner( argv[1] ); // Prepare output file initializeOutput(); // Check status of input and output files if( inFile.good() == false ) { cerr << "Error opening input file." << endl; return 0; } if( outFile.good() == false ) { cerr << "Error opening file for output." << endl; inFile.close(); return 0; } readProgram(); } catch( exception& e ) { cerr << e.what() << endl; } // If there were warnings and/or errors, leave a blank line before printing the summary. if( warningCount > 0 || errorCount > 0 ) { cerr << endl; } // Output summary of number of lines read, number of errors, and number of warnings cout << "Summary" << endl; cout << "=======" << endl; cout << "Lines Read: " << lineNumber << endl; cout << "Errors: " << errorCount << endl; cout << "Warnings: " << warningCount << endl; inFile.close(); outFile.close(); if( errorCount > 0 ) { remove( "narcomp_output.c" ); } // Empty Symbol Tables // Global Symbol Table Entries for( SymbolTable::iterator janitor = globalSymbolTable.begin(); janitor != globalSymbolTable.end(); janitor++ ) { delete janitor->second; } globalSymbolTable.clear(); // Local Symbol Table Entries for( int i = 0; i < localSymbolTable.size(); i++ ) { for( SymbolTable::iterator janitor = localSymbolTable[i].begin(); janitor != localSymbolTable[i].end(); janitor++ ) { delete janitor->second; } } localSymbolTable.clear(); return 0; }
int run(int argc, char* argv[]) { delayFile.open(DELAY_OUTPUT_FILE_NAME); // setting default parameters for PointToPoint links and channels Config::SetDefault("ns3::PointToPointNetDevice::DataRate", StringValue("1000Mbps")); Config::SetDefault("ns3::PointToPointChannel::Delay", StringValue("10ms")); Config::SetDefault("ns3::DropTailQueue::MaxPackets", StringValue("4294967295")); // Read optional command-line parameters (e.g., enable visualizer with ./waf --run=<> --visualize CommandLine cmd; cmd.Parse(argc, argv); // Creating nodes NodeContainer nodes; nodes.Create(NUM_OF_CONSUMERS + NUM_OF_ROUTERS + NUM_OF_PRODUCER); // Connecting nodes using two links // Connecting nodes using two links PointToPointHelper p2p; // Connecting consumers to edge routers int g = 0; for (int i = 0; i < GROUP_SIZE; i++, g++) p2p.Install (nodes.Get (g), nodes.Get (0 + NUM_OF_CONSUMERS)); // C0 <--> R0 for (int i = 0; i < GROUP_SIZE; i++, g++) p2p.Install (nodes.Get (g), nodes.Get (1 + NUM_OF_CONSUMERS)); // C1 <--> R1 for (int i = 0; i < GROUP_SIZE; i++, g++) p2p.Install (nodes.Get (g), nodes.Get (3 + NUM_OF_CONSUMERS)); // C2 <--> R3 for (int i = 0; i < GROUP_SIZE; i++, g++) p2p.Install (nodes.Get (g), nodes.Get (5 + NUM_OF_CONSUMERS)); // C3 <--> R5 for (int i = 0; i < GROUP_SIZE; i++, g++) p2p.Install (nodes.Get (g), nodes.Get (6 + NUM_OF_CONSUMERS)); // C4 <--> R6 for (int i = 0; i < GROUP_SIZE; i++, g++) p2p.Install (nodes.Get (g), nodes.Get (10 + NUM_OF_CONSUMERS)); // C5 <--> R10 for (int i = 0; i < GROUP_SIZE; i++, g++) p2p.Install (nodes.Get (g), nodes.Get (8 + NUM_OF_CONSUMERS)); // C6 <--> R8 for (int i = 0; i < GROUP_SIZE; i++, g++) p2p.Install (nodes.Get (g), nodes.Get (11 + NUM_OF_CONSUMERS)); // C7 <--> R11 for (int i = 0; i < GROUP_SIZE; i++, g++) p2p.Install (nodes.Get (g), nodes.Get (12 + NUM_OF_CONSUMERS)); // C8 <--> R12 for (int i = 0; i < GROUP_SIZE; i++, g++) p2p.Install (nodes.Get (g), nodes.Get (18 + NUM_OF_CONSUMERS)); // C9 <--> R18 for (int i = 0; i < GROUP_SIZE; i++, g++) p2p.Install (nodes.Get (g), nodes.Get (17 + NUM_OF_CONSUMERS)); // C10 <--> R17 for (int i = 0; i < GROUP_SIZE; i++, g++) p2p.Install (nodes.Get (g), nodes.Get (20 + NUM_OF_CONSUMERS)); // C11 <--> R20 for (int i = 0; i < GROUP_SIZE; i++, g++) p2p.Install (nodes.Get (g), nodes.Get (24 + NUM_OF_CONSUMERS)); // C12 <--> R24 for (int i = 0; i < GROUP_SIZE; i++, g++) p2p.Install (nodes.Get (g), nodes.Get (29 + NUM_OF_CONSUMERS)); // C13 <--> R2 for (int i = 0; i < GROUP_SIZE; i++, g++) p2p.Install (nodes.Get (g), nodes.Get (28 + NUM_OF_CONSUMERS)); // C14 <--> R28 for (int i = 0; i < GROUP_SIZE; i++, g++) p2p.Install (nodes.Get (g), nodes.Get (21 + NUM_OF_CONSUMERS)); // C15 <--> R21 // Connect routers p2p.Install (nodes.Get (0 + NUM_OF_CONSUMERS), nodes.Get (9 + NUM_OF_CONSUMERS)); // R0 <--> R9 p2p.Install (nodes.Get (1 + NUM_OF_CONSUMERS), nodes.Get (15 + NUM_OF_CONSUMERS)); // R1 <--> R15 p2p.Install (nodes.Get (2 + NUM_OF_CONSUMERS), nodes.Get (9 + NUM_OF_CONSUMERS)); // R2 <--> R9 p2p.Install (nodes.Get (3 + NUM_OF_CONSUMERS), nodes.Get (4 + NUM_OF_CONSUMERS)); // R3 <--> R4 p2p.Install (nodes.Get (4 + NUM_OF_CONSUMERS), nodes.Get (7 + NUM_OF_CONSUMERS)); // R4 <--> R7 p2p.Install (nodes.Get (4 + NUM_OF_CONSUMERS), nodes.Get (14 + NUM_OF_CONSUMERS)); // R4 <--> R14 p2p.Install (nodes.Get (4 + NUM_OF_CONSUMERS), nodes.Get (9 + NUM_OF_CONSUMERS)); // R4 <--> R9 p2p.Install (nodes.Get (4 + NUM_OF_CONSUMERS), nodes.Get (16 + NUM_OF_CONSUMERS)); // R4 <--> R16 p2p.Install (nodes.Get (4 + NUM_OF_CONSUMERS), nodes.Get (25 + NUM_OF_CONSUMERS)); // R4 <--> R25 p2p.Install (nodes.Get (5 + NUM_OF_CONSUMERS), nodes.Get (13 + NUM_OF_CONSUMERS)); // R5 <--> R13 p2p.Install (nodes.Get (6 + NUM_OF_CONSUMERS), nodes.Get (7 + NUM_OF_CONSUMERS)); // R6 <--> R7 p2p.Install (nodes.Get (7 + NUM_OF_CONSUMERS), nodes.Get (9 + NUM_OF_CONSUMERS)); // R7 <--> R9 p2p.Install (nodes.Get (7 + NUM_OF_CONSUMERS), nodes.Get (14 + NUM_OF_CONSUMERS)); // R7 <--> R14 p2p.Install (nodes.Get (7 + NUM_OF_CONSUMERS), nodes.Get (22 + NUM_OF_CONSUMERS)); // R7 <--> R22 p2p.Install (nodes.Get (7 + NUM_OF_CONSUMERS), nodes.Get (23 + NUM_OF_CONSUMERS)); // R7 <--> R23 p2p.Install (nodes.Get (8 + NUM_OF_CONSUMERS), nodes.Get (9 + NUM_OF_CONSUMERS)); // R8 <--> R9 p2p.Install (nodes.Get (9 + NUM_OF_CONSUMERS), nodes.Get (13 + NUM_OF_CONSUMERS)); // R9 <--> R13 p2p.Install (nodes.Get (9 + NUM_OF_CONSUMERS), nodes.Get (14 + NUM_OF_CONSUMERS)); // R9 <--> R14 p2p.Install (nodes.Get (9 + NUM_OF_CONSUMERS), nodes.Get (22 + NUM_OF_CONSUMERS)); // R9 <--> R22 p2p.Install (nodes.Get (9 + NUM_OF_CONSUMERS), nodes.Get (25 + NUM_OF_CONSUMERS)); // R9 <--> R25 p2p.Install (nodes.Get (9 + NUM_OF_CONSUMERS), nodes.Get (27 + NUM_OF_CONSUMERS)); // R9 <--> R27 p2p.Install (nodes.Get (10 + NUM_OF_CONSUMERS), nodes.Get (14 + NUM_OF_CONSUMERS)); // R10 <--> R14 p2p.Install (nodes.Get (11 + NUM_OF_CONSUMERS), nodes.Get (13 + NUM_OF_CONSUMERS)); // R11 <--> R13 p2p.Install (nodes.Get (12 + NUM_OF_CONSUMERS), nodes.Get (13 + NUM_OF_CONSUMERS)); // R12 <--> R13 p2p.Install (nodes.Get (13 + NUM_OF_CONSUMERS), nodes.Get (14 + NUM_OF_CONSUMERS)); // R13 <--> R14 p2p.Install (nodes.Get (13 + NUM_OF_CONSUMERS), nodes.Get (22 + NUM_OF_CONSUMERS)); // R13 <--> R22 p2p.Install (nodes.Get (13 + NUM_OF_CONSUMERS), nodes.Get (25 + NUM_OF_CONSUMERS)); // R13 <--> R25 p2p.Install (nodes.Get (13 + NUM_OF_CONSUMERS), nodes.Get (27 + NUM_OF_CONSUMERS)); // R13 <--> R27 p2p.Install (nodes.Get (14 + NUM_OF_CONSUMERS), nodes.Get (15 + NUM_OF_CONSUMERS)); // R14 <--> R15 p2p.Install (nodes.Get (14 + NUM_OF_CONSUMERS), nodes.Get (18 + NUM_OF_CONSUMERS)); // R14 <--> R18 p2p.Install (nodes.Get (14 + NUM_OF_CONSUMERS), nodes.Get (19 + NUM_OF_CONSUMERS)); // R14 <--> R19 p2p.Install (nodes.Get (15 + NUM_OF_CONSUMERS), nodes.Get (16 + NUM_OF_CONSUMERS)); // R15 <--> R16 p2p.Install (nodes.Get (15 + NUM_OF_CONSUMERS), nodes.Get (19 + NUM_OF_CONSUMERS)); // R15 <--> R19 p2p.Install (nodes.Get (15 + NUM_OF_CONSUMERS), nodes.Get (21 + NUM_OF_CONSUMERS)); // R15 <--> R21 p2p.Install (nodes.Get (15 + NUM_OF_CONSUMERS), nodes.Get (22 + NUM_OF_CONSUMERS)); // R15 <--> R22 p2p.Install (nodes.Get (15 + NUM_OF_CONSUMERS), nodes.Get (23 + NUM_OF_CONSUMERS)); // R15 <--> R23 p2p.Install (nodes.Get (15 + NUM_OF_CONSUMERS), nodes.Get (25 + NUM_OF_CONSUMERS)); // R15 <--> R25 p2p.Install (nodes.Get (15 + NUM_OF_CONSUMERS), nodes.Get (27 + NUM_OF_CONSUMERS)); // R15 <--> R27 p2p.Install (nodes.Get (16 + NUM_OF_CONSUMERS), nodes.Get (23 + NUM_OF_CONSUMERS)); // R16 <--> R23 p2p.Install (nodes.Get (16 + NUM_OF_CONSUMERS), nodes.Get (27 + NUM_OF_CONSUMERS)); // R16 <--> R27 p2p.Install (nodes.Get (17 + NUM_OF_CONSUMERS), nodes.Get (23 + NUM_OF_CONSUMERS)); // R17 <--> R23 // 18 done p2p.Install (nodes.Get (19 + NUM_OF_CONSUMERS), nodes.Get (22 + NUM_OF_CONSUMERS)); // R19 <--> R22 p2p.Install (nodes.Get (20 + NUM_OF_CONSUMERS), nodes.Get (25 + NUM_OF_CONSUMERS)); // R20 <--> R25 p2p.Install (nodes.Get (21 + NUM_OF_CONSUMERS), nodes.Get (22 + NUM_OF_CONSUMERS)); // R21 <--> R22 p2p.Install (nodes.Get (21 + NUM_OF_CONSUMERS), nodes.Get (27 + NUM_OF_CONSUMERS)); // R21 <--> R27 p2p.Install (nodes.Get (22 + NUM_OF_CONSUMERS), nodes.Get (23 + NUM_OF_CONSUMERS)); // R22 <--> R23 p2p.Install (nodes.Get (22 + NUM_OF_CONSUMERS), nodes.Get (28 + NUM_OF_CONSUMERS)); // R22 <--> R28 p2p.Install (nodes.Get (22 + NUM_OF_CONSUMERS), nodes.Get (29 + NUM_OF_CONSUMERS)); // R22 <--> R29 p2p.Install (nodes.Get (23 + NUM_OF_CONSUMERS), nodes.Get (24 + NUM_OF_CONSUMERS)); // R23 <--> R24 p2p.Install (nodes.Get (23 + NUM_OF_CONSUMERS), nodes.Get (25 + NUM_OF_CONSUMERS)); // R23 <--> R25 p2p.Install (nodes.Get (23 + NUM_OF_CONSUMERS), nodes.Get (27 + NUM_OF_CONSUMERS)); // R23 <--> R27 // 24 done // 25 done p2p.Install (nodes.Get (26 + NUM_OF_CONSUMERS), nodes.Get (27 + NUM_OF_CONSUMERS)); // R26 <--> R27 // 27 done // 28 done // 29 done // Connecting producer(s) int producerId = 0 + NUM_OF_CONSUMERS + NUM_OF_ROUTERS; p2p.Install (nodes.Get (producerId), nodes.Get (0 + NUM_OF_CONSUMERS)); // P0 <--> R0 // Install NDN stack without cache ndn::StackHelper ndnHelperNoCache; // ndnHelperNoCache.SetDefaultRoutes(true); ndnHelperNoCache.SetOldContentStore("ns3::ndn::cs::Nocache"); // no cache // Install on consumers for (int i = 0; i < NUM_OF_CONSUMERS; i++) { ndnHelperNoCache.Install(nodes.Get(i)); } // Install on producer(s) ndnHelperNoCache.Install(nodes.Get(0 + NUM_OF_CONSUMERS + NUM_OF_ROUTERS)); // Install NDN stack with cache ndn::StackHelper ndnHelperWithCache; // ndnHelperWithCache.SetDefaultRoutes(true); ndnHelperWithCache.SetOldContentStore("ns3::ndn::cs::Freshness::Lru", "MaxSize", "0"); // Install on routers for (int i = NUM_OF_CONSUMERS; i < NUM_OF_CONSUMERS + NUM_OF_ROUTERS; i++) { ndnHelperWithCache.InstallWithCallback(nodes.Get(i), (size_t)&ForwardingDelay, i, USE_PINT); } // Consumers ndn::AppHelper consumerHelperHonest("ns3::ndn::AccountingEncrConsumer"); // Consumer will request /prefix/A/0, /prefix/A/1, ... consumerHelperHonest.SetAttribute("Frequency", StringValue("1")); // 10 interests a second consumerHelperHonest.SetAttribute("Randomize", StringValue("uniform")); consumerHelperHonest.SetAttribute("StartSeq", IntegerValue(0)); for(int i=0; i < NUM_OF_CONSUMERS; i++) { consumerHelperHonest.SetPrefix("/prefix/A/" + std::to_string(i)); ApplicationContainer consumer = consumerHelperHonest.Install(nodes.Get(i)); consumer.Start(Seconds(0)); std::ostringstream node_id; node_id << i; Config::ConnectWithoutContext("/NodeList/" + node_id.str() + "/ApplicationList/0/ReceivedMeaningfulContent", MakeCallback(ReceivedMeaningfulContent)); } // Producer ndn::AppHelper producerHelper("ns3::ndn::AccountingEncrProducer"); // Producer will reply to all requests starting with /prefix/A. For /prefix/B we expect NACK producerHelper.SetPrefix("/prefix/A"); producerHelper.SetAttribute("PayloadSize", StringValue("1024")); producerHelper.Install(nodes.Get(producerId)); ndn::GlobalRoutingHelper ndnGlobalRoutingHelper; ndnGlobalRoutingHelper.Install(nodes); std::string prefix = "/prefix/A"; ndnGlobalRoutingHelper.AddOrigins(prefix, nodes.Get(producerId)); ndn::GlobalRoutingHelper::CalculateRoutes(); // Traces ndn::L3RateTracer::InstallAll(RATE_OUTPUT_FILE_NAME, Seconds(1.0)); Simulator::Stop(Seconds(SIMULATION_DURATION)); Simulator::Run(); Simulator::Destroy(); delayFile.close(); return 0; }
//______________________________________ void Close() { gPeaksFile.close(); exit(-1); }
~SampleFastaFile(void) { write(""); // flush fastafile << linebuffer << endl; fastafile.close(); }
z main(){ z map[50][50], M, N; for(z i=0;i<50;i++)for(z j=0;j<50;j++)r[i][j]=NULL; if(!in.good()){cerr<<"Couldn't open fiel.\n";return 1;} in>>N; in>>M; for(z i=0;i<M;i++){ for(z j=0;j<N;j++){ z t; in>>t; map[i][j] = 0x1111; if(t>=8){t-=8;map[i][j]&=~0x0001;} //S if(t>=4){t-=4;map[i][j]&=~0x0010;} //E if(t>=2){t-=2;map[i][j]&=~0x0100;} //N if(t>=1){t-=1;map[i][j]&=~0x1000;} //W //cerr<< hex << map[i][j] << ' '; } //cerr<<endl; } for(z i=0;i<M;i++){ for(z j=0;j<N;j++){ if(map[i][j]&0x1000 && (map[i][j]&0x0100) ) {//no N or W //cerr << "NW! "; r[i][j]=r[i-1][j]; r[i][j]->addRoom(i,j); if(r[i][j]!=r[i][j-1]) r[i][j]->merge(r[i][j-1]); } else if(map[i][j]&0x0100){//no N //cerr << "N ! "; r[i][j]=r[i-1][j]; r[i][j]->addRoom(i,j); if(j)r[i][j-1]->addNeighbour(i+1,j,1,r[i][j]); } else if(map[i][j]&0x1000){//no W //cerr << "W ! "; r[i][j]=r[i][j-1]; r[i][j]->addRoom(i,j); if(i)r[i-1][j]->addNeighbour(i+1,j+1,0,r[i][j]); } else { //out << i+1 << ' ' << j+1 << endl; //cerr << " ! "; r[i][j]=new Room; r[i][j]->addRoom(i,j); if(j) r[i][j-1]->addNeighbour(i+1,j,1,r[i][j]); if(i) r[i-1][j]->addNeighbour(i+1,j+1,0,r[i][j]); } } //cerr<<endl; } out << dec << rc << endl; z rmax=0; z pmax=0,ta,tb,tc; for(z i=0;i<50;i++){ z a,b,c; if(!u[i])continue; if(u[i])rmax=max(u[i]->getSize(),rmax); if(u[i]){ z x =u[i]->getRWSize(a,b,c); if(x>pmax){ ta=a;tb=b;tc=c; pmax=x; } else if(x==pmax && (a<ta ||(ta==a&&b>tb)) ){ ta=a;tb=b;tc=c; } } } out<< rmax<<endl; out<< pmax<<endl; if(!tc) { out<< tb << ' ' << ta << ' '; out<<"N\n"; } else { out<< tb << ' ' << ta << ' '; out<<"E\n"; } /*for(z i=0;i<M;i++){ for(z j=0;j<N;j++){ out<<r[i][j]->id<< ' '; } out<<endl; }*/ out.close(); //system("pause"); }
int main() { clock_t start,finish; double totaltime; start=clock(); time_t nowTime=time(0); struct tm* nowTimeStruct=localtime(&nowTime); output<<"系统当前时间:"<<1900+nowTimeStruct->tm_year<<"."<<nowTimeStruct->tm_mon<<"."<< nowTimeStruct->tm_mday<<" "<<nowTimeStruct->tm_hour<<":"<<nowTimeStruct->tm_min<<":"<<nowTimeStruct->tm_sec<<endl; try { output<<">>>>>>>>>>>>>>数据区<<<<<<<<<<<<<<<"<<endl; define_data(env);//首先初始化全局变量 output<<">>>>>>>>>>>>>>数据区结束<<<<<<<<<<<<<<<"<<endl; /*************************************************************目标函数*******************************************************/ IloNumExpr Cost(env); for(IloInt i=0; i<NG; ++i) //运行成本及其线性化(青华姐论文) for(IloInt l=0; l<NL; ++l) for(IloInt t=0; t<NT; ++t) { Master_Model.add(Deta[i][l][t]<=Z[i][l+1]-Z[i][l]); } for(IloInt i=0; i<NG; ++i) for(IloInt t=0; t<NT; ++t) { IloNumExpr Deta_Sum(env); for(IloInt l=0; l<NL; ++l) { Deta_Sum+=Deta[i][l][t]; } Master_Model.add(P[i][t]==Deta_Sum+Unit[i][1]*I[i][t]); Deta_Sum.end(); } for(IloInt i=0; i<NG; ++i) { for(IloInt t=0; t<NT; ++t) { IloNumExpr f1(env); f1+=(Unit[i][10]+Unit[i][9]*Unit[i][1]+Unit[i][8]*Unit[i][1]*Unit[i][1])*I[i][t]; for(IloInt l=0; l<NL; ++l) f1+=Betaa[i][l]*Deta[i][l][t]; Cost+=f1*Unit[i][11]; f1.end(); } } for(IloInt i=0; i<NG; ++i)//开机成本 for(IloInt t=1; t<NT; ++t) { Cost+=Unit[i][11]*Unit[i][7]*I[i][t]*(1-I[i][t-1]); } for(IloInt i=0; i<NG; ++i)//停机成本 for(IloInt t=1; t<NT; ++t) { Cost+=Unit[i][11]*Unit[i][7]*I[i][t-1]*(1-I[i][t]); } Master_Model.add(IloMinimize(env,Cost)); /********************************************************机组出力上下限约束**************************************************/ for(IloInt i=0; i<NG; ++i) for(IloInt t=0; t<NT; ++t) { Master_Model.add(P[i][t]<=Unit[i][2]*I[i][t]);//最好分开写 Master_Model.add(P[i][t]>=Unit[i][1]*I[i][t]); } /*********************************************************机组爬坡约束******************************************************/ for(IloInt i=0; i<NG; ++i) for(IloInt t=1; t<NT; ++t) { Master_Model.add(P[i][t]-P[i][t-1]<=(1-I[i][t]*(1-I[i][t-1]))*Unit[i][5]+I[i][t]*(1-I[i][t-1])*Unit[i][1]); Master_Model.add(P[i][t-1]-P[i][t]<=(1-I[i][t-1]*(1-I[i][t]))*Unit[i][6]+I[i][t-1]*(1-I[i][t])*Unit[i][1]); } /*********************************************************机组功率平衡约束**************************************************/ for(IloInt t=0; t<NT; ++t) { IloNumExpr fire(env); IloNum wind(0); for(IloInt i=0; i<NG; ++i) { fire+=P[i][t]; } for(IloInt w=0;w<NW;++w) { wind+=Pwind[t][w]; } Master_Model.add(fire==Pload[t]-wind); fire.end(); } /**********************************************************备用约束********************************************************/ for(IloInt t=0; t<NT; ++t) //条件不全 { IloNumExpr expr(env); for(IloInt i=0; i<NG; ++i) { expr+=Unit[i][2]*I[i][t]; } Master_Model.add(expr>=R[t]+Pload[t]); expr.end(); } /**********************************************************安全约束********************************************************/ ////求每个节点的注入功率 for(IloInt t=0; t<NT; ++t) { IloExprArray Pf(env,Branch);//潮流 IloExprArray Psp(env,Node-1);//注入功率 IloExprArray Theta(env,Node);//相角 Theta[Node-1]=IloExpr(env); for(IloInt k=0; k<Node-1; ++k) { Psp[k]=IloExpr(env); IloInt i=0; for(;i<NG;++i) { if(Unit[i][0]-1==k)break; } if(i<NG) { Psp[k] +=P[i][t]; } if(Sw[k]>=0) Psp[k] += Pwind[t][ Sw[k] ] ; Psp[k] -= Sl[k]*Pload[t]; } IloMutiply(env,B0l,Psp,Theta,Node-1); //计算潮流 for(IloInt h=0; h<Branch; ++h) { Pf[h]=IloExpr(env); Pf[h]+=(Theta[(IloInt)Info_Branch[h][0]-1]-Theta[(IloInt)Info_Branch[h][1]-1])/Info_Branch[h][3]; Master_Model.add(Pf[h]<=Info_Branch[h][4]); Master_Model.add(Pf[h]>=-Info_Branch[h][4]); } Pf.end(); Psp.end(); Theta.end(); } /************************************************************最小开机时间约束*****************************************************/ for(IloInt i=0; i<NG; ++i) { IloNumExpr expr1(env); for(IloInt t=0; t<=Unit[i][3]-1; ++t) { expr1+=I[i][t]; } Master_Model.add((expr1-I[i][0]*Unit[i][3])>=0); expr1.end(); for(IloInt t=1; t<=NT-Unit[i][3]; ++t) { IloNumExpr expr2(env); for(IloInt k=t; k<=t+Unit[i][3]-1; ++k) { expr2+=I[i][k]; } Master_Model.add(expr2>=Unit[i][3]*(I[i][t]-I[i][t-1])); expr2.end(); } for(IloInt t=NT-(IloInt)Unit[i][3]+1; t<=NT-1; ++t) { IloNumExpr expr2(env); for(IloInt h=t; h<=NT-1; ++h) { expr2+=(I[i][h]-(I[i][t]-I[i][t-1])); } Master_Model.add(expr2>=0); expr2.end(); } } /*******************************************************最小停机时间约束******************************************************/ for(IloInt i=0; i<NG; ++i) { IloNumExpr expr1(env); for(IloInt t=0; t<=Unit[i][4]-1; ++t) { expr1+=(1-I[i][t]); } Master_Model.add((expr1-(1-I[i][0])*Unit[i][4])>=0); expr1.end(); for(IloInt t=1; t<=NT-Unit[i][4]; ++t) { IloNumExpr expr1(env); for(IloInt k=t; k<=t+Unit[i][4]-1; ++k) { expr1+=(1-I[i][k]); } Master_Model.add(expr1>=Unit[i][4]*(I[i][t-1]-I[i][t])); expr1.end(); } for(IloInt t=NT-(IloInt)Unit[i][4]+1; t<=NT-1; ++t) { IloNumExpr expr2(env); for(IloInt h=t; h<=NT-1; ++h) { expr2+=(1-I[i][h]-(I[i][t-1]-I[i][t])); } Master_Model.add(expr2>=0); expr2.end(); } } /*******************************************************以下是场景相关约束******************************************************/ for(IloInt s=0;s<Set;++s) { for(IloInt t=0;t<NT;++t)//功率平衡约束 { IloNumExpr fire(env); for(IloInt i=0; i<NG; ++i) { fire+=Ps[s][i][t]; } IloNum wind(0); for(IloInt w=0;w<NW;++w) wind+=Pswind[s][t][w]; Master_Model.add(fire==Pload[t]-wind); fire.end(); } for(IloInt i=0; i<NG; ++i)//机组出力上下限约束 for(IloInt t=0; t<NT; ++t) { Master_Model.add(Ps[s][i][t]<=Unit[i][2]*I[i][t]);//最好分开写 Master_Model.add(Ps[s][i][t]>=Unit[i][1]*I[i][t]); } for(IloInt i=0; i<NG; ++i)//建议行为约束 for(IloInt t=0; t<NT; ++t) { Master_Model.add(Ps[s][i][t]-P[i][t]<=ddtt[i]); Master_Model.add(-Ps[s][i][t]+P[i][t]<=ddtt[i]); } for(IloInt t=0; t<NT; ++t)//安全约束 { IloExprArray Pf(env,Branch);//潮流 IloExprArray Psp(env,Node-1);//注入功率 IloExprArray Theta(env,Node);//相角 Theta[Node-1]=IloExpr(env); for(IloInt k=0; k<Node-1; ++k) { Psp[k]=IloExpr(env); IloInt i=0; for(;i<NG;++i) { if(Unit[i][0]-1==k)break; } if(i<NG) { Psp[k] +=Ps[s][i][t]; } if(Sw[k]>=0) Psp[k] += Pswind[s][t][ Sw[k] ]; Psp[k] -= Sl[k]*Pload[t]; } IloMutiply(env,B0l,Psp,Theta,Node-1); //计算潮流 for(IloInt h=0; h<Branch; ++h) { Pf[h]=IloExpr(env); Pf[h]+=(Theta[(IloInt)Info_Branch[h][0]-1]-Theta[(IloInt)Info_Branch[h][1]-1])/Info_Branch[h][3]; Master_Model.add(Pf[h]<=Info_Branch[h][4]); Master_Model.add(Pf[h]>=-Info_Branch[h][4]); } Pf.end(); Psp.end(); Theta.end(); } } Master_Cplex.solve(); /************************************************************输出显示过程**************************************************/ if (Master_Cplex.getStatus() == IloAlgorithm::Infeasible)//输出结果 output << "No Solution" << endl; output<<"Cost:"<<Master_Cplex.getObjValue()<<endl; for(IloInt i=0; i<NG; ++i) { for(IloInt t=0; t<NT; ++t) { output<<"机组 "<<i+1<<" 第 "<<t+1<<" 时段状态:"<<Master_Cplex.getValue(I[i][t])<<" 出力:"; output<<Master_Cplex.getValue(P[i][t])<<endl; } output<<endl; } Master_Model.end(); Master_Cplex.end(); env.end(); } catch(IloException& ex)//异常捕获 { cerr<<"Error: "<<ex<<endl; } catch(...) { cerr << "Error: Unknown exception caught!" << endl; } finish=clock(); totaltime=(double)(finish-start)/CLOCKS_PER_SEC; output<<"totaltime: "<<totaltime<<"s"<<endl<<endl; output.close(); return 0; }
static VOID Fini(INT32 code, VOID *v) { outstream.close(); }
Application::~Application() { if (g_debug.good()) { g_debug.close(); } }
/* close_if_open closes the given output file stream if it is open parameters: file: a pointer to the output file stream to close returns: nothing notes: todo: TODO: check if this function is still being used */ void close_if_open (ofstream& file) { if (file.is_open()) { file.close(); } }
/* Explore the Windows Multimedia Audio Mixers (mixerXxx) API, side-effecting the file system with some results. Call this from plugin initialization or some such. */ void qDeviceExplorationHook() { // Get a place to stash results. qout.open("QwaqDeviceExploration.log", fstream::out | fstream::app); /* int nDevices, i; char * name; double volume; nDevices = getNumberOfSoundPlayerDevices(); qout << nDevices << " player devices:" << endl; for (i = 0; i<nDevices; i++) { name = getSoundPlayerDeviceName(i); qout << " " << name; volume = getSoundPlayerVolume(name); setSoundPlayerVolume(volume + 0.1, name); qout << " was " << volume << " now " << getSoundPlayerVolume(name) << endl;; } //setDefaultSoundPlayer(getSoundPlayerDeviceName(0)); nDevices = getNumberOfSoundRecorderDevices(); qout << nDevices << " recorder devices:" << endl; for (i = 0; i<nDevices; i++) { char * name = getSoundRecorderDeviceName(i); qout << " " << name; volume = getSoundRecorderVolume(name); qout << " was " << volume; if (volume < 0) volume = 0.5; qout << " set to " << setSoundRecorderVolume(volume + 0.1, name); qout << " now " << getSoundRecorderVolume(name) << endl; } //setDefaultSoundRecorder(getSoundPlayerDeviceName(0)); */ const ALCchar * devices; ALCchar * ptr; devices = alcGetString(NULL, ALC_DEFAULT_DEVICE_SPECIFIER); qout << endl << "default openAL device " << devices; devices = alcGetString(NULL, ALC_DEVICE_SPECIFIER); ptr = (ALCchar *) devices; while (!!*ptr) { qout << endl << " " << ptr; while (!!*ptr++); } devices = alcGetString(NULL, ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER); qout << endl << "default openAL capture device " << devices; devices = alcGetString(NULL, ALC_CAPTURE_DEVICE_SPECIFIER); ptr = (ALCchar *) devices; while (!!*ptr) { qout << endl << " " << ptr; while (!!*ptr++); } qout << endl; //if (FAILED(DirectSoundEnumerate((LPDSENUMCALLBACK)DSEnumProc,(VOID*)" output"))) qout << "output enumeration failed" << endl; //if (FAILED(DirectSoundCaptureEnumerate((LPDSENUMCALLBACK)DSEnumProc,(VOID*) " capture"))) qout << "output enumeration failed" << endl; qout << endl; // cleanup qout.close(); }
POINT WFD_Opt::calcNext(POINT &currPosition, const MAP &map) { cerr << "*********************** check calcNextGUI " << endl; static ofstream f_out; f_out.open("exploration_execution_rafael.txt", ios::app); //set current robot position _currentPos = currPosition; FRONTIER_LIST found; if (_flgFirstTime) { struct timeval startTime; struct timeval endTime; struct rusage ru; getrusage(RUSAGE_SELF, &ru); startTime = ru.ru_utime; //for (int i = 0; i < 1; ++i) { // NOTE: Optimization disabled: _frontiers.clear(); found = findFrontiers(_currentPos, map); list<POINT_LIST >::iterator frontierItr; //insert all found frontiers for (frontierItr = found.begin(); frontierItr != found.end(); ++frontierItr) _frontiers.push_back(*frontierItr); // _flgFirstTime = false; _scanList.clear(); //} getrusage(RUSAGE_SELF, &ru); endTime = ru.ru_utime; double tS = startTime.tv_sec*1000000 + (startTime.tv_usec); double tE = endTime.tv_sec*1000000 + (endTime.tv_usec); f_out << (tE - tS) << endl; f_out.close(); } else { FRONTIER_LIST::iterator i; FRONTIER_LIST::iterator j; //DEBUG //int counter = 0; //for (i = _frontiers.begin(); i != _frontiers.end(); ++i) { // cout << "frontier" << counter++ << " size = " << i->size() << endl; //} //scan each detected frontier FRONTIER_LIST newFrontiers; for (i = _frontiers.begin(); i != _frontiers.end(); ++i) { unMarkFrontier(*i); //scan each point in current frontier for (POINT_LIST::iterator itr = i->begin(); itr != i->end(); ++itr) { POINT p = *itr; struct timeval startTime; struct timeval endTime; struct rusage ru; getrusage(RUSAGE_SELF, &ru); startTime = ru.ru_utime; //flood fill from current frontier found = findFrontiers(p, map); double tS = startTime.tv_sec*1000000 + (startTime.tv_usec); double tE = endTime.tv_sec*1000000 + (endTime.tv_usec); getrusage(RUSAGE_SELF, &ru); endTime = ru.ru_utime; //f_out << tE - tS << endl; //f_out.close(); //insert all found frontiers for (j = found.begin(); j != found.end(); ++j) newFrontiers.push_back(*j); } } _frontiers = newFrontiers; //found = findFrontiers(_currentPos, map); } f_out.close(); //cout << "DEBUG: total frontiers detected: " << _frontiers.size() << endl; //check if there's nothing left to explore if (_frontiers.size() == 0) return _currentPos; //get the lowest cost centroid // matan POINT dummy; return dummy; return findBestCentroidGUI(_frontiers); // double maxScore, currScore; // // FRONTIER_LIST::iterator itr = _frontiers.begin(); // POINT currCentroid, bestCentroid; // // bestCentroid = currCentroid = calcCentroid((*itr)); // maxScore = currScore = itr->size() / euclidianDist(currCentroid, _currentPos); // POINT_LIST::iterator j = itr->begin(); // cout << "DEBUG: Frontier (" << (*j).x << "," << (*j).y << ") size = " << std::fixed << std::setw(4) << itr->size() << " dist = " << std::setw(5) << std::setprecision(0) << euclidianDist(currCentroid, _currentPos) << " score = " << std::setw(5) << std::setprecision(2) << currScore << endl; // // ++itr; // //// cout << "DEBUG: frontiers found: " << _frontiers.size() << endl; // // for (; itr != _frontiers.end(); ++itr) { // // currCentroid = calcCentroid((*itr)); // currScore = itr->size() / euclidianDist(currCentroid, _currentPos); // j = itr->begin(); // cout << "DEBUG: Frontier (" << (*j).x << "," << (*j).y << ") size = " << std::fixed << std::setw(4) << itr->size() << " dist = " << std::setw(5) << std::setprecision(0) << euclidianDist(currCentroid, _currentPos) << " score = " << std::setw(5) << std::setprecision(2) << currScore << endl; // if (currScore > maxScore) { // maxScore = currScore; // bestCentroid = currCentroid; // } // } // //// //DEBUG //// cout << "frontiers are: " << endl; //// for (itr = _frontiers.begin(); itr != _frontiers.end(); ++itr) { //// cout << "{ " ; //// //// POINT_LIST::iterator j = itr->begin(); ////// for (; j != itr->end(); ++j) ////// cout << "(" << (*j).x << "," << (*j).y << ") " ; //// //// cout << "(" << (*j).x << "," << (*j).y << ") " ; //// //// cout << "} size = " << itr->size() << endl; //// } // // return bestCentroid; }
void dataWrite(int writer, int flag, double data1, double data2, double data3, double data4, double data5, double data6, double data7, double data8) { if(writer==1) { //Initialization Writing if(flag==0) { myfile.open("ballbeamdata.txt"); myfile << "DATA FROM BALL BEAM SIMULATION\n------------------------------\n"; myfile << "The data in this file is in the following order:\n"; myfile << "Time of simulation, delta T for each step, Pink ball X, Pink ball Y, Orange ball X, Orange ball Y, Green ball X, Green ball Y, error, derivative error, integral error, control (u), motor encoder value.\n\n\n"; myfile << "motor speed (deg/sec) = "; myfile << data1; myfile << "\nK = "; myfile << data2; myfile << "\nKdiff = "; myfile << data3; myfile << "\nKint = "; myfile << data4; } //Calibration (offset angle) Writing if(flag==1) { myfile << "\nInitial angle offset = "; myfile << data1; myfile << "\n\n\n"; } //Experimental Data Writing pt 1 (ball position info, time info) if(flag==2) { myfile << data1; myfile << ", "; myfile << data2; myfile << ", "; myfile << data3; myfile << ", "; myfile << data4; myfile << ", "; myfile << data5; myfile << ", "; myfile << data6; myfile << ", "; myfile << data7; myfile << ", "; myfile << data8; myfile << ", "; } //Experimental Data Writing pt 2 (controller info) if(flag==3) { myfile << data1; myfile << ", "; myfile << data2; myfile << ", "; myfile << data3; myfile << ", "; myfile << data4; myfile << ", "; } //Experimental Data Writing pt 3 (motor encoder info) if(flag==4) { myfile << data1; myfile << "\n"; } //Close Output File When Done if(flag==5) { myfile.close(); cout << "\nfile written!\n"; } } }
core::~core() { userFile.close(); saveFile.close(); }
~Simulator() { util_file.close(); latency_file.close(); log_file.close(); }
VOID Fini(INT32 code, VOID *v) { trace << "#eof" << endl; trace.close(); }
void setup_debug(int level, const string &filename, const string &prefix) { debug_level = level; logfile_prefix = prefix; logfile_filename = filename; if (logfile_file.is_open()) { logfile_file.close(); } ostream *output = 0; if (filename.length()) { logfile_file.clear(); logfile_file.open(filename.c_str(), fstream::out | fstream::app); #ifdef __linux__ string fname = filename; if (fname[0] != '/') { char buf[PATH_MAX]; if (getcwd(buf, sizeof(buf))) { fname.insert(0, "/"); fname.insert(0, buf); } } setenv("SEGFAULT_OUTPUT_NAME", fname.c_str(), false); #endif output = &logfile_file; } else if( const char* ccache_err_fd = getenv( "UNCACHED_ERR_FD" )) { output = ccache_stream( atoi( ccache_err_fd )); } else { output = &cerr; } #ifdef __linux__ (void) dlopen("libSegFault.so", RTLD_NOW | RTLD_LOCAL); #endif if (debug_level >= Debug) { logfile_trace = output; } else { logfile_trace = &logfile_null; } if (debug_level >= Info) { logfile_info = output; } else { logfile_info = &logfile_null; } if (debug_level >= Warning) { logfile_warning = output; } else { logfile_warning = &logfile_null; } if (debug_level >= Error) { logfile_error = output; } else { logfile_error = &logfile_null; } signal(SIGHUP, reset_debug_signal_handler); }
//~FileTarget() { ofile.close(); } void Close() override { ofile.close(); }
extern "C" __declspec( dllexport ) void Fini2() { outfile.close(); }
void prepare_fasta_output_distribution(ifstream& fp_input, ofstream& fp_fasta, ofstream& fp_detail, string& reference, meta_data& meta_details) { ofstream condense_log; condense_log.open("condense_log.tsv", ofstream::out); vector<map<char,int>> mutationStats; //baslragsh; string read_name, cigar, alignment, quality, len; string alignment_string, quality_score, detail; int total_score, average_score, opt, reflength; int i, k, count, refindex, readindex; int fprimer_length, except_primer; unordered_map<string, int> umap; vector< pair<string, string>> sequences; double exponent; int raw_sequence_count = 0;//debug purposes only fp_detail << "###############################################Sequence Anaysis Starts##############################################" << endl; distribution error_correction[reference.length()]; for(i = 0; i < reference.length(); i++) { mutationStats.push_back(map<char,int>()); mutationStats[i]['A'] = 0; mutationStats[i]['C'] = 0; mutationStats[i]['G'] = 0; mutationStats[i]['T'] = 0; mutationStats[i]['N'] = 0; for(k = 0; k < ILLUMINA_SCORE; k++) error_correction[i].qscore[k] = 0; error_correction[i].matching_base = 0; error_correction[i].mismatch = 0; error_correction[i].expected_mismatch = 0.0; error_correction[i].standard_deviation = 0.0; } condense_log << "Observed,Expected,zscore,correct,raw pval,A,C,G,T,N,%mutated" << endl; fprimer_length = meta_details.fprimer.length(); except_primer = reference.length() - meta_details.fprimer.length(); while(getline(fp_input, read_name)) { raw_sequence_count++; getline(fp_input, cigar); getline(fp_input, alignment_string); getline(fp_input, quality_score); total_score = 0; for(i = 0; i < quality_score.length(); i++) { total_score += quality_score.at(i) - '!'; } average_score = total_score / quality_score.length(); fp_detail << endl << "Global Average Score = " << average_score << endl; if(average_score < GLOBAL_QSCORE) continue; refindex = fprimer_length; i = readindex = 0; alignment = ""; quality = ""; len = ""; fp_detail << "CIGAR = " << cigar << endl; while(i < cigar.length()) { if(cigar.at(i) >= '0' && cigar.at(i) <= '9') len += cigar.at(i); else { opt = cigar.at(i); count = atoi(len.c_str()); fp_detail << "Count = " << count << ", and Option = " << opt << endl; len = ""; //fp_detail << "Reference = " << reference << endl; //fp_detail << "Alignment = " << alignment_string << endl; if(opt == 'M' || opt == 'X') { for(k = 0; k < count; k++) { if(alignment_string.at(readindex) == reference.at(refindex)) { error_correction[refindex].matching_base += 1; } else { error_correction[refindex].mismatch += 1; mutationStats[refindex][alignment_string.at(readindex)] += 1; char blah = alignment_string.at(readindex); //if(!(alignment_string.at(readindex) == 'A') && (alignment_string.at(readindex) != 'C') && (alignment_string.at(readindex) != 'G') && (alignment_string.at(readindex) != 'T')){ //if((blah != 'A') && (blah != 'C') && (blah != 'G') && (blah != 'T')){ fp_detail << "BASE Mismatch is Found at = " << refindex << endl; } error_correction[refindex].qscore[quality_score.at(readindex) - '!'] += 1; //fp_detail << k << "= (" << refindex << ", " << readindex << ") = " // "(" << reference.at(refindex) << ", " << alignment_string.at(readindex) << ")" << endl; refindex += 1; readindex += 1; } } else if(opt == 'I') { readindex += count; } else if(opt == 'D') { refindex += count; } else { assert(false); } } i += 1; } } fp_detail << endl; for(i = 0; i < reference.length(); i++) { fp_detail << "Showing Analysis for Index = " << i << endl; if(error_correction[i].mismatch + error_correction[i].matching_base == 0) continue; for(k = 0; k < ILLUMINA_SCORE; k++) { if(error_correction[i].qscore[k] == 0) continue; exponent = pow(10, -1 * k * 0.1); fp_detail << "QSCORE = " << k << ", and COUNT = " << error_correction[i].qscore[k] << ", and Exponent = " << exponent << endl; error_correction[i].expected_mismatch += (error_correction[i].qscore[k] * exponent); error_correction[i].standard_deviation += (error_correction[i].qscore[k] * exponent * (1 - exponent)); fp_detail << "Expected Number of Mismatch = " << error_correction[i].expected_mismatch; fp_detail << ", and Standard Deviation = " << error_correction[i].standard_deviation << endl; } error_correction[i].standard_deviation = sqrt(error_correction[i].standard_deviation); error_correction[i].zscore = (error_correction[i].mismatch + 0.5 - error_correction[i].expected_mismatch) / error_correction[i].standard_deviation; error_correction[i].pvalue = 1-c_norm(error_correction[i].zscore); cout << "A pvalue is: " << error_correction[i].pvalue << endl; fp_detail << "Error Correction At Position = " << i - fprimer_length << endl; fp_detail << "Mismatch = " << error_correction[i].mismatch << ", and Matching BASE = " << error_correction[i].matching_base << endl; fp_detail << "Expected Number of Mismatch = " << error_correction[i].expected_mismatch; fp_detail << ", and Standard Deviation = " << error_correction[i].standard_deviation << endl; fp_detail << "Finally calculated ZSCORE = " << error_correction[i].zscore << endl; fp_detail << "Finally p-value is = " << error_correction[i].pvalue << endl; fp_detail << "Fail to reject null hypothesis is = " << (error_correction[i].reject_by_bh_threshold ? "0" : "1")<< endl; fp_detail << endl; //if(error_correction[i].mismatch > 0) // assert(false); } set_reject_flags(error_correction, reference.length()); for(i = 0; i < reference.length(); i++){ if(error_correction[i].mismatch + error_correction[i].matching_base == 0) continue; condense_log << error_correction[i].mismatch << "," << error_correction[i].expected_mismatch << "," << error_correction[i].zscore; condense_log << "," << (error_correction[i].reject_by_bh_threshold ? "0" : "1"); condense_log << "," << (error_correction[i].pvalue) << ","; condense_log << mutationStats[i]['A'] << ","; condense_log << mutationStats[i]['C'] << ","; condense_log << mutationStats[i]['G'] << ","; condense_log << mutationStats[i]['T'] << ","; condense_log << mutationStats[i]['N'] << ","; condense_log << "," << double((double)error_correction[i].mismatch / (double)raw_sequence_count) << endl; if(error_correction[i].reject_by_bh_threshold){ fp_detail << "No Correcting at position " << i << endl; } else { fp_detail << "Correcting at position " << i << endl; } } //condense_log.close(); fp_input.clear(); fp_input.seekg(0, fp_input.beg); while(getline(fp_input, read_name)) { getline(fp_input, cigar); getline(fp_input, alignment_string); getline(fp_input, quality_score); total_score = 0; for(i = 0; i < quality_score.length(); i++) { total_score += quality_score.at(i) - '!'; } average_score = total_score / quality_score.length(); fp_detail << endl << "Global Average Score = " << average_score << endl; if(average_score < GLOBAL_QSCORE) continue; refindex = meta_details.fprimer.length(); i = readindex = 0; alignment = ""; quality = ""; len = ""; fp_detail << "CIGAR = " << cigar << endl; while(i < cigar.length()) { if(cigar.at(i) >= '0' && cigar.at(i) <= '9') len += cigar.at(i); else { opt = cigar.at(i); count = atoi(len.c_str()); fp_detail << "Count = " << count << ", and Option = " << opt << endl; len = ""; fp_detail << "Reference = " << reference << endl; fp_detail << "Alignment = " << alignment_string << endl; if(opt == 'M' || opt == 'X') { for(k = 0; k < count; k++) { /*if(error_correction[refindex].reject_by_bh_threshold){ cout << "Rejectin null hypothesis whooo at " << refindex << endl; } else { cout << "Acceptin null hypothesis =( " << refindex << endl; }*/ if(alignment_string.at(readindex) != reference.at(refindex) && //error_correction[refindex].zscore < ZSCORE && !error_correction[refindex].reject_by_bh_threshold) { fp_detail << endl << "Error CORRECTION Point at " << readindex << endl; fp_detail << "ZSCORE at this point = " << error_correction[refindex].zscore << endl; fp_detail << "Changin " << alignment_string.at(readindex) << " To " << reference.at(readindex) << endl; alignment += reference.at(refindex); quality += quality_score.at(readindex); } else { fp_detail << endl << "No correction at " << refindex; alignment += alignment_string.at(readindex); quality += quality_score.at(readindex); } //fp_detail << k << "= (" << refindex << ", " << readindex << ")" << endl; refindex += 1; readindex += 1; } } else if(opt == 'I') { for(k = 0; k < count; k++) { alignment += alignment_string.at(readindex); quality += quality_score.at(readindex); readindex += 1; } } else if(opt == 'D') { refindex += count; } else { assert(false); } } i += 1; } detail = cigar + "\n" + alignment; if(umap.find(detail) == umap.end()) { //umap[alignment] = 1; sequences.push_back(make_pair(read_name, detail)); umap[detail] = 1; } else { umap[detail] += 1; } /* fp_fasta << ">" << read_name; fp_fasta << "|DUPCOUNT=1"; fp_fasta << "|CIGAR=" << cigar << endl; fp_fasta << alignment << endl; */ } for(i = 0; i < sequences.size(); i++) { fp_fasta << ">" << sequences[i].first; fp_fasta << "|DUPCOUNT=" << umap[sequences[i].second]; fp_fasta << "|CIGAR=" << sequences[i].second << endl; //fp_fasta << alignment << endl; } fp_input.close(); fp_fasta.close(); condense_log.close(); return; }
int main(int argc, char *argv[]) { initialize(); int sock; struct sockaddr_in servAddr; struct sockaddr_in clientAddr; unsigned int fromSize;// in-out of address size for recvfrom char recvBuffer[MAX_PACKET_SIZE + 1]; /* Create a datagram/UDP socket */ if ((sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) error("socket () failed"); /* Construct the server address structure */ memset(&servAddr, 0, sizeof(servAddr)); servAddr.sin_family = AF_INET; servAddr.sin_addr.s_addr = inet_addr(serverIP); servAddr.sin_port = htons(servPort); fd_set readfds; FD_SET(sock, &readfds); struct timeval tv; tv.tv_sec = 1; int n = sock + 1; int last_seqno = 0; bool acked = false; packet* p = new packet; // wait for first packet while (!acked) { p->seqno = 0; strcpy(p->data, filename.c_str()); p->len = strlen(filename.c_str()); int bytes_sent = sendto(sock, (char*) p, sizeof(packet), 0, (struct sockaddr *) &servAddr, sizeof(servAddr)); /* Send the request to the server */ if (bytes_sent != sizeof(packet)) error("sendto() sent a different number of bytes than expected"); printf("Request sent to (%s) on port(%d) requesting file(%s)\n", inet_ntoa(servAddr.sin_addr), ntohs(servAddr.sin_port), filename.c_str()); cout << "selecting now" << endl; int rv = select(n, &readfds, NULL, NULL, &tv); cout << "never returned" << endl; if (rv == -1) { error("select"); // error occurred in select() } else if (rv == 0) {// time out cout << "Time Out Reciving the first packet" << endl; // will repeat loop and resend request } else { unsigned int cliAddrLen = sizeof(clientAddr); if ((recv_msg_size = recvfrom(sock, recv_msg, MAX_PACKET_SIZE, 0, (struct sockaddr *) &clientAddr, &cliAddrLen)) < 0) error("recvfrom() failed"); else acked = true; } } bool repeat = false; do { p = (packet*) recv_msg; bool stop = (p->data[p->len - 1] == EOF); if (!repeat) { // for (int i = 0; i < recv_msg_size && recv_msg[i] != EOF; i++) { // cout << recv_msg[i]; // } // cout << endl; int total_bytes = (stop) ? p->len - 1 : p->len; output.write(p->data, total_bytes); } cout << "Receive Msg: seq " << p->seqno << " len " << p->len << endl << endl; // << p->data << endl; // send ack of recieved packet ack_packet * ack = new ack_packet; ack->ackno = last_seqno; ack->len = p->len; if (sendto(sock, (char*) ack, sizeof(ack_packet), 0, (struct sockaddr *) &servAddr, sizeof(servAddr)) != sizeof(ack_packet)) { error("sendto() failed while sending an ack packet"); } cout << "is EOF" << stop << endl; if (stop) break; FD_SET(sock, &readfds); int rv = select(n, &readfds, NULL, NULL, &tv); if (rv == -1) { error("select"); // error occurred in select() } else if (rv == 0) {// time out cout << "Time Out Reciving the first packet" << endl; repeat = true; // will repeat loop and resend request } else { unsigned int cliAddrLen = sizeof(clientAddr); if ((recv_msg_size = recvfrom(sock, recv_msg, MAX_PACKET_SIZE, 0, (struct sockaddr *) &clientAddr, &cliAddrLen)) < 0) error("recvfrom() failed"); else { packet* p = (packet *) recv_msg; if (p->seqno == last_seqno + 1) { acked = true; repeat = false; last_seqno++; cout << "Receive Msg: seq " << p->seqno << " len " << p->len << endl << p->data << endl; } else { repeat = true; } } } /* code */ } while (true); output.close(); cout << "recieved" << endl; close(sock); return 0; }
/** * Define an optimization problem that finds a set of muscle controls to maximize * the vertical jump height of a model. */ int main() { try { std::clock_t startTime = std::clock(); // Ensures all components are printed out to the model file. Object::setSerializeAllDefaults(true); // Create a new OpenSim model from file Model osimModel("jumper10dof24musc.osim"); /* Get the muscle set, then double MaxIsometricForce and/or MaxContractionVelocity for each muscle. */ const Set<Muscle> &muscleSet = osimModel.getMuscles(); //// Double maximum isometric force of all muscles: COMMENT OUT TWO LINES BELOW IF YOU DO NOT WANT TO DO THIS //for (int i=0; i < muscleSet.getSize(); i++) { // muscleSet[i].setMaxIsometricForce(muscleSet[i].getMaxIsometricForce()*2); //} // Double maximum contraction velocity of all muscles: COMMENT OUT TWO LINES BELOW IF YOU DO NOT WANT TO DO THIS for (int i=0; i < muscleSet.getSize(); i++) { muscleSet[i].setMaxContractionVelocity(muscleSet[i].getMaxContractionVelocity()*2); } // The number of parameters is the number of actuators const Set<Actuator> &actuatorSet = osimModel.getActuators(); int numActuators = actuatorSet.getSize(); optLog << "numActuators = " << numActuators << endl; int numParameters = numActuators; /* Define initial values for controllerParameters. Each controller has two parameters, an initial time, and a duration for bang-bang control. There are as many controls as there are actuators because we assume symmetry (but each controller has two parameters). controllerParameters = [ti_0 duration_0 ti_1 duration_1 ... ]' */ Vector controllerParameters(numParameters, 0.05); // initialize initial times controllerParameters[0] = 0.107863; //hamstrings controllerParameters[2] = 0.00069462; //bifmesh controllerParameters[4] = 0.296889; //glut_max controllerParameters[6] = 0.0533121; //iliopsoas controllerParameters[8] = 0.166427; //rect_fem controllerParameters[10] = 0.277592; //vasti controllerParameters[12] = 0.344144; //gastroc controllerParameters[14] = 0.315376; //soleus controllerParameters[16] = 0.0857591; //tib_ant controllerParameters[18] = 0.149644; //ercspn controllerParameters[20] = 0.468741; //intobl controllerParameters[22] = 0.455184; //extobl // initialize durations controllerParameters[1] = 0.429072; //hamstrings controllerParameters[3] = 0.120626; //bifemsh controllerParameters[5] = 0.39246; //glut_max controllerParameters[7] = 0.0303192; //iliopsoas controllerParameters[9] = 0.370385; //rect_fem controllerParameters[11] = 0.3; //vasti controllerParameters[13] = 0.343613; //gastroc controllerParameters[15] = 0.350808; //soleus controllerParameters[17] = 0.0277077; //tib_ant controllerParameters[19] = 0.243332; //ercspn controllerParameters[21] = 0.160016; //intobl controllerParameters[23] = 0.15192; //extobl // Add prescribed controllers to each muscle. Need to only loop numActuators/2 times since we are enforcing symmetry. // It is assumed that all actuators are listed for one side of the model first, then the other side, in the same order. for(int i=0; i < numActuators/2; i++) { // make a piecewise constant function for both sides PiecewiseConstantFunction bangBangControl; bangBangControl.addPoint(initialTime,0); bangBangControl.addPoint(controllerParameters[2*i],1); bangBangControl.addPoint(controllerParameters[2*i]+controllerParameters[2*i+1],0); // add controller to right side PrescribedController *actuatorController_r = new PrescribedController(); Set<Actuator> actuator_r; actuator_r.insert(0,osimModel.getActuators().get(i)); actuatorController_r->setName(actuatorSet.get(i).getName()); actuatorController_r->setActuators(*actuator_r.clone()); actuatorController_r->prescribeControlForActuator(osimModel.getActuators().get(i).getName(), bangBangControl.clone()); osimModel.addController(actuatorController_r); // add controller to left side PrescribedController *actuatorController_l = new PrescribedController(); Set<Actuator> actuator_l; actuator_l.insert(0,osimModel.getActuators().get(i + numActuators/2)); actuatorController_l->setName(actuatorSet.get(i + numActuators/2).getName()); actuatorController_l->setActuators(*actuator_l.clone()); actuatorController_l->prescribeControlForActuator(osimModel.getActuators().get(i + numActuators/2).getName(), bangBangControl.clone()); osimModel.addController(actuatorController_l); } // Create the OptimizationSystem. Initialize the objective function value "f". JumpingOptimizationSystem sys(numParameters, osimModel); Real f = NaN; // Set lower and upper bounds. Vector lower_bounds(numParameters, initialTime); Vector upper_bounds(numParameters, finalTime); // Limit the duration of the "bang" to be at least a certain value for (int i = 1; i<numParameters; i+=2) { lower_bounds[i] = 0.0001; } sys.setParameterLimits( lower_bounds, upper_bounds ); // Create an optimizer. Pass in our OptimizerSystem // and the name of the optimization algorithm. optLog << "using LBFGSB" << endl; Optimizer opt(sys, SimTK::LBFGSB); //LBFGSB was found to be beter for this problem //optLog << "using IPOPT" << endl; Optimizer opt(sys, InteriorPoint); // Specify settings for the optimizer opt.setConvergenceTolerance(0.01); opt.useNumericalGradient(true); opt.setMaxIterations(1000); opt.setLimitedMemoryHistory(500); //opt.setDiagnosticsLevel(4); // First level that gives outer loop information for IPOPT // Optimize it! optLog << "Optimizing!" << endl; optLog << "Initial controllerParameters: " << controllerParameters << endl; optLog << "lower_bounds: " << lower_bounds << endl; optLog << "upper_bounds: " << upper_bounds << endl; f = opt.optimize(controllerParameters); optLog << "Elapsed time = " << (std::clock()-startTime)/CLOCKS_PER_SEC << "s" << endl; optLog << "OpenSim example completed successfully. Look in bestSoFarLog.txt for best solution.\n"; optLog.close(); bestSoFarLog.close(); verboseLog.close(); debugLog.close(); } catch (const std::exception& ex) { std::cout << ex.what() << std::endl; return 1; } // End of main() routine. return 0; }
int main(int argc, char** argv) { //connect to server, given as the first argument string usage = string(argv[0]) + " <server> <port> [game #]"; if(argc < 3) { cerr << usage << endl; return 0; } bool end_game = false; bool start_game = true; if(argc == 4) { // they specified a game number, // do something different? start_game = false; //cout << "Trying to joing game #" << argv[3] << endl; } // we got enough command-line arguments, // start tying to connect: int sock_server = open_server_connection(argv[1], argv[2]); if(sock_server == -1) { return 0; } // create an instance of the player's AI class myAI gameAI; string comm_buffer; sexp_t* sexp; // log into the server, using the AI's team name string whos_turn; my_user_id = login_to_server(sock_server, gameAI.PlayerName() ); // setup the logging filename ostringstream stream; tm* myTime; time_t theTime = time(NULL); myTime = localtime(&theTime); stream << myTime->tm_hour << "." << myTime->tm_min; string name = string(argv[0]); for(int i=name.size()-1; i >=0; i--) { if(name[i] == ' ' || name[i] == '/' || name[i] == '\\' || name[i] == '.' || name[i] == ':') { name.erase(i,1); } } string log_filename = stream.str() + "-" + name + string(".gamelog"); cout << "Filename: " << log_filename << endl; #ifdef DEBUG cout << "DEBUG: logged in as user #" << my_user_id << endl; #endif // okay, we've succesfully logged in, // now start or join a game if(start_game) { // create a new game: string game_number = create_game(sock_server); gameAI.playerNumber = 1; gameAI.myBase = coordinate(0,0); gameAI.enemyBase = coordinate(25,25); } else { gameAI.playerNumber = 2; gameAI.myBase = coordinate(0,0); gameAI.enemyBase = coordinate(25,25); // join an existing game cout << "Trying to join game " << argv[3] << "..." << endl; string join_string = "(join-game " + string(argv[3]) + ")"; send_string(sock_server, join_string); sexp = rec_sexp(sock_server); if(!check_sexp(sexp, "join-accepted")) { cout << "Unabled to join game " << argv[3] << endl; goto GAME_SHUTDOWN; } // we should only try to start the game if we're the // player that just joined; otherwise, the server // will sorta freak out... send_string(sock_server, "(game-start)"); } // the server is going to spit a ton of SEXP's at us; // wade through them until we get a "new-turn" msg. sexp = rec_sexp(sock_server); while(!check_sexp(sexp, "new-turn")) { // okay, what kind of data have we gotten from the server, // and what are we supposed to do about it? if(check_sexp(sexp, "game-start-accepted")) { // the server accepted our reqeust to begin the game; // we don't care, because earlier we just assumed // that it worked :| } if(check_sexp(sexp, "unit-types")){ // this should be sent only during this initialization: // it contains the details of each type of unit #ifdef DEBUG cout << "DEBUG: updating unit types" << endl; #endif update_unit_types((myAI*)&gameAI, sexp); } if(check_sexp(sexp, "status")) { // An actual game-status message: this might not // mean much right now, but try to parse it anyway. // Don't bail if it fails, but warn us. if(!game_status(gameAI, sexp, my_user_id)) { cout << "WARN: error parsing game status" << endl; } } // get another S-expression to test: sexp = rec_sexp(sock_server); } // okay, now sexp should contain a "new-turn" message // pull out who's turn it is, then start the main game loop whos_turn = string(sexp->list->next->val); #ifdef DEBUG cout << "DEBUG: got all our pregame stuff, starting main loop!" << endl; #endif while(!end_game) { // ask the server for an update: //send_string(sock_server, "(game-status)"); //sexp = rec_sexp(sock_server); // we're not guaranteed to get a "status" message, // so handle anything unexpected before we get to // the main game loop while(!check_sexp(sexp, "status")) { #ifdef DEBUG cout << "DEBUG: waiting for game status, got \"" << sexp->list->val << "\" message" << endl; #endif if(check_sexp(sexp, "game-over")) { cout << "Game Over: "; string winner = string( sexp->list->next->val ); if( winner == my_user_id ) cout << "You Win!"; else cout << "You Lose..."; cout << endl; end_game = true; goto GAME_SHUTDOWN; } if(check_sexp(sexp, "new-turn")) { whos_turn = string(sexp->list->next->val); #ifdef DEBUG cout << "DEBUG: It's player " << whos_turn << "'s turn" << endl; #endif } sexp = rec_sexp(sock_server); } if(!check_sexp(sexp, "status")) { cerr << "WARN: expected 'status', got '" << sexp->list->val << "'" << endl; } if(!game_status(gameAI, sexp, my_user_id)) { cerr << "WARN: couldn't parse game status!" << endl; } // update the turn number gameAI.turnNumber = atoi( sexp->list->next->list->val); if(whos_turn == my_user_id) { //cout << endl << "Starting my turn... "; // 4a. Run their custom 'Play()' function gameAI.Play(); // 4b. Send their orders to the server while( gameAI.orders.size() != 0){ string myOrder = gameAI.orders.front().s_expression; gameAI.orders.pop(); // send this command to the server send_string(sock_server, myOrder); // there's no need to listen for an incoming message; // we assume errors will be handled at the beginning // of the next loop. } // let the server know we've finished out turn send_string(sock_server, "(end-turn)"); //cout << "done with my turn" << endl; } else { // it's not your turn, so take it easy for a second //cout << "Not my turn, waiting...." << endl; #ifndef WIN32 // the usleep function insn't avaible in Windows //usleep(100000); // this helps prevent climbing to 100% CPU usage #endif } // get another sexp to jump-start the next iteration of the loop sexp = rec_sexp(sock_server); } GAME_SHUTDOWN: cout << "Shutting down..." << endl; send_string(sock_server, "(leave-game)"); sexp = rec_sexp(sock_server); send_string(sock_server, "(logout)"); sexp = rec_sexp(sock_server); //End of game #ifdef WIN32 closesocket(sock_server); #else close(sock_server); #endif log_file.open(log_filename.c_str()); if(log_file.fail()) { cout << "Error writing to log file" << endl; } else { log_file << log_stream.str(); log_file.close(); } return 0; }
int main(int argc, char *argv[], char *envp[]) { string ccCmd; int optionsOK = parseOptions(argc, argv); if (optionsOK < 0) return -1; cppShellCmd += inputFile; cppShellCmd += " "; /* ccCmd = "mv "; ccCmd += outputFile; ccCmd += " "; ccCmd += outputFile; ccCmd += ".c; "; ccCmd += ccShellCmd; if (genSharedLib) ccCmd += "-shared "; ccCmd += "-o "; ccCmd += outputFile;*/ if ((yyin = popen(cppShellCmd.c_str(), "r")) == NULL) { cerr << "Unexpected error in reading input file\n"; return 1; } #ifdef TEST_LEXER int token; while (token = yylex()) { if (token == TOK_SYNTAX_ERROR) { cout << yyfilename << ":" << yylinenum << ": Error: Unrecognized token `" << yytext << "'\n"; } else { cout << "Token: " << token << " "; switch(token) { case TOK_UINTNUM: cout << "Attribute: (int) " << yylval.uVal; break; case TOK_DOUBLENUM: cout << "Attribute: (float) " << yylval.dVal; break; case TOK_STRCONST: cout << "Attribute: (string) " << yylval.cVal; break; case TOK_ID: cout << "Attribute: (id) " << yylval.cVal; break; default: break; } cout << endl; } } return 0; #else // yydebug = 1; any = new EventEntry("any"); if (stm.insert(any) == OK) { Type *te = new Type((vector<Type*>*)NULL, Type::EVENT); any->type(te); } yyparse(); stm.leaveToScope(SymTabEntry::Kind::GLOBAL_KIND); GlobalEntry *ge = (GlobalEntry*)(stm.currentScope()); if (ge != NULL) { //cout << "Finished parsing, here is the AST\n"; ge->checkType(); ge->print(cout, 0); string fileName = string(yyfilename); int dotIndex = fileName.find('.'); if(dotIndex > -1) fileName = fileName.substr(0, dotIndex); if (errCount() == 0) { qos.open(fileName + ".q"); ge->genFinalCode("test"); ofstream fos(fileName + ".i"); ge->serializeAsm(fos); fos.close(); qos.close(); } } #endif }
int main () { output.open ("output.txt"); output.clear (); srand (time (0)); float *A = 0, *b = 0, *c = 0, *d = 0, *B = 0, *x = 0, *xk = 0; A = new float [N*N]; B = new float [N*N]; b = new float [N]; c = new float [N]; d = new float [N]; x = new float [N]; xk = new float [N]; GenMatrix (A, 0); for (int i = 0; i < N; i ++) A[i*N + i] = rand ()%10001*N + 10000*N; output << "Matrix A:"; Out (A, 0); GenMatrix(b, 1); output << "Vector b:"; Out (b, 1); fill (&x[0], &x[N-1], 0); fill (&xk[0], &xk[N-1], 0); float Bnorm = 0; for (int i = 0; i < N; i ++) // формирование матрицы B = -D^-1 * (A - D) { c[i] = b[i] / A[i*N + i]; for (int j = 0; j < N; j ++) { if (i == j) { B[i*N + j] = 0; } else { B[i*N + j] = - A[i*N + j] / A[i*N + i]; Bnorm += B[i*N+j] * B[i*N+j]; } } } Bnorm = sqrt (Bnorm); float Teps = 1; while (Teps > eps) // прогон метода { MultipleMatrixToVector (B, x, d); // очередна¤ итераци¤ SumMatrixes (d, c, xk, N); Teps = Norm (xk, x, N)/(1 - Bnorm); // подсчет погрешности iter ++; memcpy (x, xk, N*sizeof (float)); } output << "x:"; Out (x, 1); output << "xk:"; Out (xk, 1); MultipleMatrixToVector(A, x, d); DifMatrix (d, b, d, N); output << "Difference A*xk and b:"; Out (d, 1); output << "Solution:"; Out (x, 1); output.close (); return 0; }
int main() { /********************************************************* //DO NOT OUTPUT DETAILED NUMBER IN THE PRODUCTION VERSION //Open output file file.open("Efficient-Responsive-Single.txt"); if (! file) { //if fail to open the file cerr << "can't open output file Efficient-Responsive-Single.txt!" << endl; exit(EXIT_FAILURE); } *********************************************************/ file2.open("Efficient-Responsive-Single-Nash.txt"); if (! file2) { //if fail to open the file cerr << "can't open output file Efficient-Responsive-Single-Nash.txt!" << endl; exit(EXIT_FAILURE); } cout << setprecision(5); //file << setprecision(10); file2 << setprecision(5); //cout << "u\tvar\tb\tc_E\tc_R\tK\tq_EE\tPi_EE\tCS_EE\tTS_EE\tq_RR\tPi_RR\tCS_RR\tTS_RR\tqE_ER\tqR_ER\tPiE_ER\tPiR_ER\tCS_ER\tTS_ER\tNashEq\tCS*\tTS*" << endl; //file << "u\tvar\tb\tc_E\tc_R\tK\tq_EE\tPi_EE\tCS_EE\tTS_EE\tq_RR\tPi_RR\tCS_RR\tTS_RR\tqE_ER\tqR_ER\tPiE_ER\tPiR_ER\tCS_ER\tTS_ER\tNashEq\tCS*\tTS*" << endl; file2 << "K\tdelta\tb\tNashE\tNashR\tCS01\tCS12\tTS01\tTS12\tCoop01\tCoop12" << endl; //initialize array for standard normal pdf for (int i=0; i<=2*N*STEP; i++) phi[i] = (1/sqrt(2.0*M_PI))*exp(-pow(((double)i/STEP-N),2.0)/2); //initialize default values of the parameters u = 10; var = 16; delta = 1; c_E = 1; c_R = c_E*delta; K = 0; b = 1; //initialize the vectors to save threshold values const int II=1000; const int JJ=100; const int KK=5; //thresholds are such that if the uncertainty $var$ exceeds the threshold, the corresponding optimal strategy switches to R from E vector< vector<double> > NashE(KK+1, vector<double>(JJ+1)); //threshold for the optimal Nash strategy if the other player chooses E vector< vector<double> > NashR(KK+1, vector<double>(JJ+1)); //threshold for the optimal Nash strategy if the other player chooses R vector< vector<double> > CS01(KK+1, vector<double>(JJ+1)); vector< vector<double> > CS12(KK+1, vector<double>(JJ+1)); vector< vector<double> > TS01(KK+1, vector<double>(JJ+1)); vector< vector<double> > TS12(KK+1, vector<double>(JJ+1)); vector< vector<double> > Coop01(KK+1, vector<double>(JJ+1)); vector< vector<double> > Coop12(KK+1, vector<double>(JJ+1)); for (int kk=0; kk<=KK; kk++) //for-loop for delta or K { //K = kk; //iterate over multiple values for K delta = 1+0.1*kk; //iterate over multiple values for delta c_R = c_E*delta; for (int jj=0; jj<=JJ; jj++) //for b { b = jj*0.01; cout << "Calculating K=" << K << ", delta=" << delta << ", b=" << b << " ... " << endl; for (int ii=0; ii<=II; ii++) //for var { var = ii*0.02; //file << u << "\t" << var << "\t" << b << "\t" << c_E << "\t" << c_R << "\t" << K << "\t" ; //cout << u << "\t" << var << "\t" << b << "\t" << c_E << "\t" << c_R << "\t" << K << "\t"; //stdev of the signal (info available to the Responsive firm) stdev = sqrt(var); //for case E-E double q_EE = (u-c_E)/(2+b); double Pi_EE = pow((u-c_E)/(2+b), 2.0); double CS_EE = (1+b)*Pi_EE; double TS_EE = (3+b)*Pi_EE; //file << q_EE << "\t" << Pi_EE << "\t" << CS_EE << "\t" << TS_EE << "\t"; //cout << q_EE << "\t" << Pi_EE << "\t" << CS_EE << "\t" << TS_EE << "\t"; //for case R-R double q_RR=0, Pi_RR=0, CS_RR, TS_RR; for (int i=0;i<=2*N*STEP;i++) { double e = ((double)i/STEP-N)*stdev; if (u + e - c_R>0) { q_RR += (u+e-c_R)/(2+b) * phi[i]; Pi_RR += pow((u+e-c_R)/(2+b), 2.0) * phi[i]; } } q_RR /= STEP; Pi_RR /= STEP; CS_RR = (1+b)*Pi_RR; Pi_RR -= K; //account for fixed cost TS_RR = CS_RR + 2*Pi_RR; //file << q_RR << "\t" << Pi_RR << "\t" << CS_RR << "\t" << TS_RR << "\t"; //cout << q_RR << "\t" << Pi_RR << "\t" << CS_RR << "\t" << TS_RR << "\t"; //for case E-R (firm 1 E, firm 2 R) double qR_ER=0, qE_ER=0, PiR_ER=0, PiE_ER=0, CS_ER=0, TS_ER=0; //search for optimal q1 until foc1=0 double q1=0, q2=0; double lb=0, ub=(2-b)*(u-c_E)/(2*(2-b*b)); //lower and upper bounds used in the searching algorithm if ((ub>lb)&&(foc1_ER(q1)>0)) { q1=(lb+ub)/2; double temp=foc1_ER(q1); for (;ub-lb>0.001;) { if (temp>0) lb = q1; else ub = q1; q1 = (lb+ub)/2; temp = foc1_ER(q1); } } //for given q1, calculating expected q2, Pi1, Pi2 with regard to the second signal e for (int j=0; j<=2*N*STEP; j++) { double e = ((double)j/STEP-N)*stdev; //realization of the second signal e if (e + u - c_R - b*q1<0) q2 = 0; else q2 = (e + u - c_R - b*q1)/2; qR_ER += q2 * phi[j]; PiE_ER += (e + u - q1 - b*q2 - c_E)*q1 * phi[j] ; PiR_ER += (e + u - q2 - b*q1 - c_R)*q2 * phi[j]; CS_ER += 0.5*( pow(q1,2.0) + pow(q2,2.0) + 2*b*q1*q2 ) * phi[j]; } qE_ER = q1; qR_ER /= STEP; PiE_ER /= STEP; PiR_ER /= STEP; CS_ER /= STEP; PiR_ER -= K; //account for fixed cost TS_ER = CS_ER + PiR_ER + PiE_ER; //file << qE_ER << "\t" << qR_ER << "\t" << PiE_ER << "\t" << PiR_ER << "\t" << CS_ER << "\t" << TS_ER << "\t"; //cout << qE_ER << "\t" << qR_ER << "\t" << PiE_ER << "\t" << PiR_ER << "\t" << CS_ER << "\t" << TS_ER << "\t"; /********************************************************* //DO NOT OUTPUT DETAILED NUMBER IN THE PRODUCTION VERSION //Nash equilibrium analysis if ((Pi_EE>=PiR_ER)&&(PiE_ER>=Pi_RR)) { cout << 0 << "\t"; //E-E //file << 0 << "\t"; //E-E } else if ((Pi_EE<PiR_ER)&&(PiE_ER<Pi_RR)) { cout << 2 << "\t"; //R-R //file << 2 << "\t"; //R-R } else if ((Pi_EE>=PiR_ER)&&(PiE_ER<Pi_RR)) { cout << 0.5 << "\t"; //E-E / R-R //file << 0.5 << "\t"; //E-E / R-R } else if ((Pi_EE<PiR_ER)&&(PiE_ER>=Pi_RR)) { cout << 1 << "\t"; //E-R //file << 1 << "\t"; //E-R } else { cout << "???\t"; //error file << "???\t"; //error } //best strategy for maximizing Consumer Surplus if ((CS_EE>=CS_ER)&&(CS_EE>=CS_RR)) { cout << 0 << "\t"; //E-E //file << 0 << "\t"; //E-E } else if ((CS_ER>=CS_EE)&&(CS_ER>=CS_RR)) { cout << 1 << "\t"; //E-R //file << 1 << "\t"; //E-R } else { cout << 2 << "\t"; //R-R //file << 2 << "\t"; //R-R } //best strategy for maximizing Total Surplus if ((TS_EE>=TS_ER)&&(TS_EE>=TS_RR)) { cout << 0 << endl; //E-E //file << 0 << endl; //E-E } else if ((TS_ER>=TS_EE)&&(TS_ER>=TS_RR)) { cout << 1 << endl; //E-R //file << 1 << endl; //E-R } else { cout << 2 << endl; //R-R //file << 2 << endl; //R-R } *********************************************************/ //////////////////////////////////////////////////////////////////////// //keep track of the thresholds on $var$ if (Pi_EE>=PiR_ER) NashE[kk][jj] = var; if (PiE_ER>=Pi_RR) NashR[kk][jj] = var; if ((CS_EE>=CS_ER)&&(CS_EE>=CS_RR)) CS01[kk][jj] = var; if ((CS_EE>=CS_RR)||(CS_ER>=CS_RR)) CS12[kk][jj] = var; if ((TS_EE>=TS_ER)&&(TS_EE>=TS_RR)) TS01[kk][jj] = var; if ((TS_EE>=TS_RR)||(TS_ER>=TS_RR)) TS12[kk][jj] = var; if ((Pi_EE*2>=PiE_ER+PiR_ER)&&(Pi_EE>=Pi_RR)) Coop01[kk][jj] = var; if ((Pi_EE>=Pi_RR)||(PiE_ER+PiR_ER>=2*Pi_RR)) Coop12[kk][jj] = var; } //end-for var } //end-for b //output the thresholds to file2 for (int jj=0; jj<=JJ; jj++) file2 << K << "\t" << delta << "\t" << jj*0.01 << "\t" << NashE[kk][jj] << "\t" << NashR[kk][jj] << "\t" << CS01[kk][jj] << "\t" << CS12[kk][jj] << "\t" << TS01[kk][jj] << "\t" << TS12[kk][jj] << "\t" << Coop01[kk][jj] << "\t" << Coop12[kk][jj] << endl; } //end big parameter loop //file.close(); file2.close(); return 0; }
int main() { Entrada.open("articulo.txt"); if (Entrada.fail()) { cout << "No se pudo abrir el archivo de salida" << endl; exit(1); } cout<<"1.Ver lista de articulos"<<endl; cout<<"2.hacer Factura"<<endl; cout<<"3.Ver total de ventas"<<endl; cout<<"4.Terminar"<<endl; cout<<"opcion"; cin>>opcion; switch(opcion){ case 2: ++k; cout<< "factura numero"<<k<<endl; cout<< "Clave "<<" Cantidad"<<" Descripcion "<<" PrecioU "<<" Precio"<<endl; do{ while ( Entrada >>Clave>>Cantidad>>Desc>>PrecioU){ lista[i].setClave(Clave); lista[i].setDesc(Desc); lista[i].setCantidad(Cantidad); lista[i].setPrecioU(PrecioU); i++; cout<<"Clave"<<endl; cin>>_clav; lista[i].setClave(_clav); if (_clav != Clave) cout<<"esa clave no existe"<<endl; cout<< "cantidad"<<endl; cin>> _canti; lista[i].setCantidad(_canti); lista[i].disminuyeCant(_canti); if( _canti<=Cantidad) Cantidad =_canti; else cout<<"No hay suficiente de ese articulo"<<endl; precioTotal= lista[i].CalcPrecioT(); Total+=precioTotal; cout<<Clave<<Cantidad<<Desc<<PrecioU<<precioTotal<<endl; cout<<"otro articulo"; cin>>yes; } }while(yes!= 'n'); cout<< "El total de la factura es"<<Total<<endl; Salida.open("articulo.txt"); cout<<Clave<<Cantidad<<PrecioU<<endl; Salida.close(); Entrada.close(); break; } return 0; }
int main(int argc, char** argv) { VideoCapture cap("videos/3.1.mp4"); cvNamedWindow("Original Video", 0); cvResizeWindow("Original Video", 600, 400); Mat background, hsv_background; Mat nextframe, hsv_nextframe; cap >> background;//discarding first frame cap >> background; cvtColor(background, hsv_background, COLOR_BGR2HSV); imshow("Original Video", hsv_background); cvMoveWindow("Original Video", 0, 0); /// Using 50 bins for hue and 60 for saturation int h_bins = 50; int s_bins = 60; int histSize[] = { h_bins, s_bins }; // hue varies from 0 to 179, saturation from 0 to 255 float h_ranges[] = { 0, 180 }; float s_ranges[] = { 0, 256 }; const float* ranges[] = { h_ranges, s_ranges }; // Use the o-th and 1-st channels int channels[] = { 0, 1 }; outFile.open("data/2.1.txt"); outFile2.open("data/2.2.txt"); outFile3.open("data/2.3.txt"); outFile4.open("data/2.4.txt"); /// Histograms MatND hist_background; MatND hist_nextframe; MatND store[LEARN_FRAME_LIMIT]; //first frame calcHist(&hsv_background, 1, channels, Mat(), hist_background, 2, histSize, ranges, true, false); normalize(hist_background, hist_background, 0, 1, NORM_MINMAX, -1, Mat()); //second frame cap >> nextframe; cvtColor(nextframe, hsv_nextframe, COLOR_BGR2HSV); calcHist(&hsv_nextframe, 1, channels, Mat(), hist_nextframe, 2, histSize, ranges, true, false); normalize(hist_nextframe, hist_nextframe, 0, 1, NORM_MINMAX, -1, Mat()); int CHISQUARE = 1; int BHATTA = 3; double initChangeCHI = compareHist(hist_background, hist_nextframe, CHISQUARE); double initChangeBHATTA = compareHist(hist_background, hist_nextframe, BHATTA); cout << "Init change CHI is " << initChangeCHI << endl; cout << "Init change BHATTA is " << initChangeBHATTA << endl; //cvWaitKey(0); double prevChangeCHI = 0.0; double prevChangeBHATTA = 0.0; double prevChangeINTERSEC = 0.0; int potentialBackground = 0; bool buffer = false; int bufferCount = 0; int pause = 0; int prev = 0; while (1){ cap >> nextframe; if (nextframe.empty()) break; cvtColor(nextframe, hsv_nextframe, COLOR_BGR2HSV); calcHist(&hsv_nextframe, 1, channels, Mat(), hist_nextframe, 2, histSize, ranges, true, false); normalize(hist_nextframe, hist_nextframe, 0, 1, NORM_MINMAX, -1, Mat()); imshow("Original Video", nextframe); cvMoveWindow("Original Video", 0, 0); double changeCHI = compareHist(hist_background, hist_nextframe, CHISQUARE); double changeBHATTA = compareHist(hist_background, hist_nextframe, BHATTA); double changeINTERSEC = compareHist(hist_background, hist_nextframe, INTERSEC); printf("Change in CHISQ is [%f] ", changeCHI); printf("Change in BHATTA is [%f] ", changeBHATTA); printf("Change in INTERSEC is [%f] ", changeINTERSEC); cout<< endl; if (buffer == true) bufferCount++; if (bufferCount == 45){ buffer = false; cout << "Toggling buffer to false" << endl; //cvWaitKey(0); bufferCount = 0; } //if (abs(changeCHI - initChangeCHI)<CHISQMINTHRES){// || abs(changeBHATTA - initChangeBHATTA)<BHATTAMINTHRES){ if (abs(changeBHATTA)<BHATTAMINTHRES){ buffer = false; bufferCount = 0; cout << "Continuing --------------------------------" << endl; CHISQ_BEST_FRAME = 0.0; potentialBackground = 0; continue; } //Learn new background //abs(changeBHATTA - BHATTAMINTHRES)<0.05 if (abs(changeBHATTA)>BHATTAMINTHRES && changeCHI>0.9 && changeCHI<1.2 && CHISQ_BEST_FRAME - changeBHATTA>1 && BHATTA_BEST_FRAME - changeBHATTA>0.02){ if (potentialBackground < LEARN_FRAME_LIMIT){ store[potentialBackground] = hist_nextframe.clone(); potentialBackground++; cout << "Learning " << endl; //cvWaitKey(0); continue; } else{ hist_background = store[0]; cout << "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^"<<endl; cout << "Changing Background with abs(changeBHATTA - BHATTAMINTHRES) = " << abs(changeBHATTA - BHATTAMINTHRES) << endl; cout << "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^" << endl; //cvWaitKey(0); potentialBackground = 0; } } cout << "Buffer is " << buffer << endl; //cout << "abs(change - initChange) ->>> " << abs(changeCHI - initChangeCHI) << " with buffer "<<buffer<< endl; if (changeCHI<300){ if (changeCHI > CHISQTHRES && buffer == false){ potentialBackground = 0; cout << "****************************" << endl; cout << "Change Detected" << endl; if (prevChangeCHI > changeCHI){// && abs(changeCHI - CHISQ_BEST_FRAME)>CHISQ_BEST_FRAME_DIFF){//Model 1 //if (prevChangeBHATTA > changeBHATTA){//Model 2 cout << "Prev is " << prevChangeCHI << " and current is "<< changeCHI<<endl; cout << "*********************************************" << endl; cout << "Best Frame Detected Using CHISQ " << endl; cout << "*********************************************" << endl; DetectCircles(nextframe); buffer = true; CHISQ_BEST_FRAME = changeCHI; BHATTA_BEST_FRAME = changeBHATTA; cvWaitKey(0); } /*else if (prevChange > change && prev == 1){ cout << "Best Frame Detected" << endl; buffer = true; prev == 0; cvWaitKey(0); } else if (prevChange < change && prev == 1){ prev = 0; }*/ } } else{ potentialBackground = 0; if (changeBHATTA > BHATTATHRES && buffer == false){ cout << "****************************" << endl; cout << "Change Detected" << endl; if (prevChangeBHATTA > changeBHATTA){ cout << "Best Frame Detected Using BHATTA" << endl; DetectCircles(nextframe); buffer = true; cvWaitKey(0); } } } //printf("Prev Change [%f] ", prevChange); cout << endl; printf("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n"); //prevChange = changeCHI; prevChangeCHI = changeCHI; prevChangeBHATTA = changeBHATTA; prevChangeINTERSEC = changeINTERSEC; pause = cvWaitKey(1); if (pause == 32){ pause = cvWaitKey(0); } } outFile.close(); outFile2.close(); outFile3.close(); outFile4.close(); int a = cvWaitKey(0); return 0; }