void makeEleMuComparisonPlots (int whichobservable, int whichjet, int whichlepton) { //Open the file and form the name string fileSystematics; string suffix="/gpfs/cms/data/2011/Systematics/postApproval/"; //string suffix="/tmp/"; if (whichlepton==1) suffix=suffix+"ele/"; if (whichlepton==2) suffix=suffix+"muo/"; // setTDRStyle (); gStyle->SetErrorX(0); gStyle->SetPadGridX(0); gStyle->SetPadGridY(0); bool absoluteNormalization = true; int lepton = 3; //1 -> electron, 2-> muon , 3 -> combined reults! bool addLumiUncertainties = true; double lumiError = 0.025; int use_case = whichobservable; int whichjet = whichjet; string version = "_v2_32"; //string s = "/afs/infn.it/ts/user/marone/html/ZJets/FinalPlotsForAN/v41/SVDBayes/"; string s="/afs/infn.it/ts/user/marone/html/ZJets/FinalPlotsForAN/v57_3_postApproval/ele/"; // string s = "/gpfs/cms/users/schizzi/EleMuComparisonPlots/PostUnfolding/"; string eleplotpath = "/gpfs/cms/users/schizzi/Systematics/ele/"; string muoplotpath = "/gpfs/cms/users/schizzi/Systematics/muo/"; gStyle->SetOptStat (0); TCanvas *plots = new TCanvas ("plots", "EB", 200, 100, 600, 800); //DATA: //string elepathFile ="/gpfs/cms/data/2011/Unfolding/testReferenceMu.root"; //string muopathFile ="/gpfs/cms/data/2011/Unfolding/testMu.root"; string elepathFile ="/gpfs/cms/data/2011/Unfolding/UnfoldingOfficialV57_3Sherpa.root"; string muopathFile ="/gpfs/cms/data/2011/Unfolding/UnfoldingOfficialV57_3.root"; if (whichlepton==2){ elepathFile ="/gpfs/cms/data/2011/Unfolding/UnfoldingOfficialV57_3SherpaMu.root"; muopathFile ="/gpfs/cms/data/2011/Unfolding/UnfoldingOfficialV57_3Mu.root"; s="/afs/infn.it/ts/user/marone/html/ZJets/FinalPlotsForAN/v57_3_postApproval/muo/"; } //string elepathFile ="/gpfs/cms/data/2011/Unfolding/UnfoldingOfficialV57_3NoSQRT.root"; //string muopathFile ="/gpfs/cms/data/2011/Unfolding/UnfoldingOfficialV57_3NoMCToy.root"; TFile *histof = TFile::Open (elepathFile.c_str ()); histof->cd (""); TDirectory *dir = gDirectory; TList *mylist = (TList *) dir->GetListOfKeys (); TIter iter (mylist); TObject *tobj = 0; TFile *histofmuo = TFile::Open (muopathFile.c_str ()); string stringmatch; string systPathFile; string systPathFileMuo; histof->cd (""); int i = 0; // solo di servizio quando debuggo... while ((tobj = iter.Next ())) { string name = tobj->GetName (); if (use_case == 1) { // Jet Multiplicity stringmatch = "JetMultiplicityUnfolded"; systPathFile = eleplotpath + "systematicsEff_jetMult" + version + ".txt"; systPathFileMuo = muoplotpath + "systematicsEff_jetMult" + version + ".txt"; fileSystematics = suffix+"systematicsUnfMCToy_jetMult" + version + ".txt"; } if (use_case == 2) { // Jet Pt if (whichjet == 1) { stringmatch = "jReco_leading"; systPathFile = eleplotpath + "systematicsEff_jet1Pt" + version + ".txt"; systPathFileMuo = muoplotpath + "systematicsEff_jet1Pt" + version + ".txt"; fileSystematics = suffix+"systematicsUnfMCToy_jet1Pt" + version + ".txt"; } if (whichjet == 2) { stringmatch = "jReco_subleading"; systPathFile = eleplotpath + "systematicsEff_jet2Pt" + version + ".txt"; systPathFileMuo = muoplotpath + "systematicsEff_jet2Pt" + version + ".txt"; fileSystematics = suffix+"systematicsUnfMCToy_jet2Pt" + version + ".txt"; } if (whichjet == 3) { stringmatch = "jReco_subsubleading"; systPathFile = eleplotpath + "systematicsEff_jet3Pt" + version + ".txt"; systPathFileMuo = muoplotpath + "systematicsEff_jet3Pt" + version + ".txt"; fileSystematics = suffix+"systematicsUnfMCToy_jet3Pt" + version + ".txt"; } if (whichjet == 4) { stringmatch = "jReco_subsubsubleading"; systPathFile = eleplotpath + "systematicsEff_jet4Pt" + version + ".txt"; systPathFileMuo = muoplotpath + "systematicsEff_jet4Pt" + version + ".txt"; fileSystematics = suffix+"systematicsUnfMCToy_jet4Pt" + version + ".txt"; } } if (use_case == 3) { // Jet Eta if (whichjet == 1) { stringmatch = "jReco_leadingeta"; systPathFile = eleplotpath + "systematicsEff_jet1Eta" + version + ".txt"; systPathFileMuo = muoplotpath + "systematicsEff_jet1Eta" + version + ".txt"; fileSystematics = suffix+"systematicsUnfMCToy_jet1Eta" + version + ".txt"; } if (whichjet == 2) { stringmatch = "jReco_subleadingeta"; systPathFile = eleplotpath + "systematicsEff_jet2Eta" + version + ".txt"; systPathFileMuo = muoplotpath + "systematicsEff_jet2Eta" + version + ".txt"; fileSystematics = suffix+"systematicsUnfMCToy_jet2Eta" + version + ".txt"; } if (whichjet == 3) { stringmatch = "jReco_subsubleadingeta"; systPathFile = eleplotpath + "systematicsEff_jet3Eta" + version + ".txt"; systPathFileMuo = muoplotpath + "systematicsEff_jet3Eta" + version + ".txt"; fileSystematics = suffix+"systematicsUnfMCToy_jet3Eta" + version + ".txt"; } if (whichjet == 4) { stringmatch = "jReco_subsubsubleadingeta"; systPathFile = eleplotpath + "systematicsEff_jet4Eta" + version + ".txt"; systPathFileMuo = muoplotpath + "systematicsEff_jet4Eta" + version + ".txt"; fileSystematics = suffix+"systematicsUnfMCToy_jet4Eta" + version + ".txt"; } } if (use_case == 4) { // Ht if (whichjet == 1) { stringmatch = "HReco_leading"; systPathFile = eleplotpath + "systematicsEff_jet1Ht" + version + ".txt"; systPathFileMuo = muoplotpath + "systematicsEff_jet1Ht" + version + ".txt"; fileSystematics = suffix+"systematicsUnfMCToy_jet1Ht" + version + ".txt"; } if (whichjet == 2) { stringmatch = "HReco_subleading"; systPathFile = eleplotpath + "systematicsEff_jet2Ht" + version + ".txt"; systPathFileMuo = muoplotpath + "systematicsEff_jet2Ht" + version + ".txt"; fileSystematics = suffix+"systematicsUnfMCToy_jet2Ht" + version + ".txt"; } if (whichjet == 3) { stringmatch = "HReco_subsubleading"; systPathFile = eleplotpath + "systematicsEff_jet3Ht" + version + ".txt"; systPathFileMuo = muoplotpath + "systematicsEff_jet3Ht" + version + ".txt"; fileSystematics = suffix+"systematicsUnfMCToy_jet3Ht" + version + ".txt"; } if (whichjet == 4) { stringmatch = "HReco_subsubsubleading"; fileSystematics = suffix+"systematicsUnfMCToy_jet4Ht" + version + ".txt"; systPathFile = eleplotpath + "systematicsEff_jet4Ht" + version + ".txt"; systPathFileMuo = muoplotpath + "systematicsEff_jet4Ht" + version + ".txt"; } } if (name == stringmatch) { cout << "CONFIGURATION:" << endl; cout << "stringmatch: " <<stringmatch<< endl; cout << "systPathFile: " <<systPathFile<< endl; TH1D *leading; gDirectory->GetObject (name.c_str (), leading); leading->SetMarkerSize(0.9); leading->Sumw2(); histofmuo->cd (""); TH1D *leadingmuo; gDirectory->GetObject (name.c_str (), leadingmuo); leadingmuo->SetMarkerSize(0.9); leadingmuo->Sumw2(); // /// EFFICIENCY Systematics: // for (int nnbins=1;nnbins<=leading->GetNbinsX ();nnbins++) { // cout << fabs(leading->GetBinContent(nnbins)-leadingmuo->GetBinContent(nnbins))/(2*leading->GetBinContent(nnbins)) << endl; // cout << leading->GetBinContent(nnbins)-leadingmuo->GetBinContent(nnbins) << endl; // } // read from file --------------------------------------------- double dat; ifstream inM; cout << "reading ... " << systPathFile << endl; inM.open (systPathFile.c_str ()); std::vector < double >systTmpM; while (1) { inM >> dat; if (!inM.good ()) break; systTmpM.push_back (dat); } inM.close (); // ------------------------------------------------------------ // read from file --------------------------------------------- ifstream inM2; cout << "reading ... " << systPathFileMuo << endl; inM2.open (systPathFileMuo.c_str ()); std::vector < double >systTmpMmuo; while (1) { inM2 >> dat; if (!inM2.good ()) break; systTmpMmuo.push_back (dat); } inM2.close (); // ------------------------------------------------------------ TH1D *leadingRatioSystematics; leadingRatioSystematics = (TH1D *) leading->Clone ("leading"); if (systTmpM.size () != leadingRatioSystematics->GetNbinsX ()) cout << "TE SON MONA! WRONG NUMBER OF BINS (# syst from file->" <<systTmpM.size()<<" - # bins->"<<leadingRatioSystematics->GetNbinsX()<<")"<<endl; for (int i = 0; i < leadingRatioSystematics->GetNbinsX (); i++) { //leadingRatioSystematics->SetBinContent(i + 1, 1.0); //leadingRatioSystematics->SetBinError (i + 1,sqrt(systTmpM[i]*systTmpM[i] + systTmpMmuo[i]*systTmpMmuo[i])); // leadingRatioSystematics->SetBinContent(i + 1, 1.0); // leadingRatioSystematics->SetBinError (i + 1,max(systTmpM[i]/100.0,systTmpMmuo[i]/100.0)); } plots->cd (); TPad *pad1 = new TPad("pad1","pad1",0.01,0.3,0.99,0.99); pad1->Draw(); pad1->cd(); pad1->SetTopMargin(0.1); pad1->SetBottomMargin(0.0); pad1->SetLeftMargin(0.2); pad1->SetRightMargin(0.0); pad1->SetFillStyle(0); if (use_case !=3) pad1->SetLogy(1); else pad1->SetLogy(0); if (use_case ==3){ leading->SetMinimum((0.5-0.05*(whichjet-1))*leading->GetMinimum()); leading->SetMaximum((1.25+0.35*(whichjet-1))*leading->GetMaximum()); } leading->SetLineColor (kRed+1); leading->SetMarkerStyle (20); leading->SetFillColor (kRed+1); leading->SetMarkerColor (kRed+1); leading->GetXaxis ()->SetTitleOffset (1.1); leading->GetXaxis ()->SetTitleSize (0.05); leading->GetXaxis ()->SetLabelSize (0.0); leading->GetXaxis ()->SetLabelFont (42); leading->GetXaxis ()->SetTitleFont (42); leading->GetYaxis ()->SetTitleOffset (1.); leading->GetYaxis ()->SetTitleSize (0.07); leading->GetYaxis ()->SetLabelSize (0.06); leading->GetYaxis ()->SetLabelFont (42); leading->GetYaxis ()->SetTitleFont (42); leading->SetTitle (); leading->GetXaxis ()->SetTitle (); if (use_case ==1) { if (absoluteNormalization) leading->GetYaxis ()->SetTitle ("d#sigma/dN [pb]"); else { if (lepton == 1) leading->GetYaxis ()->SetTitle ("(1/#sigma_{Z #rightarrow e^{+}e^{-}}) d#sigma/dN"); if (lepton == 2) leading->GetYaxis ()->SetTitle ("(1/#sigma_{Z #rightarrow #mu^{+}#mu^{-}}) d#sigma/dN"); if (lepton == 3) leading->GetYaxis ()->SetTitle ("(1/#sigma_{Z #rightarrow l^{+}l^{-}}) d#sigma/dN"); } } if (use_case ==2) { if (absoluteNormalization) leading->GetYaxis ()->SetTitle ("d#sigma/dp_{T} [pb/GeV]"); else { if (lepton == 1) leading->GetYaxis ()->SetTitle ("(1/#sigma_{Z #rightarrow e^{+}e^{-}}) d#sigma/dp_{T}"); if (lepton == 2) leading->GetYaxis ()->SetTitle ("(1/#sigma_{Z #rightarrow #mu^{+}#mu^{-}}) d#sigma/dp_{T}"); if (lepton == 3) leading->GetYaxis ()->SetTitle ("(1/#sigma_{Z #rightarrow l^{+}l^{-}}) d#sigma/dp_{T}"); } } if (use_case ==3) { if (absoluteNormalization) leading->GetYaxis ()->SetTitle ("d#sigma/d#eta [pb]"); else { if (lepton == 1) leading->GetYaxis ()->SetTitle ("(1/#sigma_{Z #rightarrow e^{+}e^{-}}) d#sigma/d#eta"); if (lepton == 2) leading->GetYaxis ()->SetTitle ("(1/#sigma_{Z #rightarrow #mu^{+}#mu^{-}}) d#sigma/d#eta"); if (lepton == 3) leading->GetYaxis ()->SetTitle ("(1/#sigma_{Z #rightarrow l^{+}l^{-}}) d#sigma/d#eta"); } } if (use_case ==4) { if (absoluteNormalization) leading->GetYaxis ()->SetTitle ("d#sigma/dH_{T} [pb/GeV]"); else { if (lepton == 1) leading->GetYaxis ()->SetTitle ("(1/#sigma_{Z #rightarrow e^{+}e^{-}}) d#sigma/dH_{T}"); if (lepton == 2) leading->GetYaxis ()->SetTitle ("(1/#sigma_{Z #rightarrow #mu^{+}#mu^{-}}) d#sigma/dH_{T}"); if (lepton == 3) leading->GetYaxis ()->SetTitle ("(1/#sigma_{Z #rightarrow l^{+}l^{-}}) d#sigma/dH_{T}"); } } leading->SetFillColor (kBlack); leading->SetFillStyle (3001); leading->SetMarkerColor (kBlack); leading->SetLineColor (kBlack); leading->SetMarkerStyle (20); leading->Draw ("E1"); leadingmuo->SetFillColor (kBlue); leadingmuo->SetFillStyle (3001); leadingmuo->SetMarkerColor (kBlue); leadingmuo->SetLineColor (kBlue); leadingmuo->SetMarkerStyle (21); leadingmuo->Draw ("E1SAME"); //------------------------------------------- TLegend *legendsx_d; legendsx_d = new TLegend (0.74, 0.6, 0.98, 0.88); legendsx_d->SetFillColor (kWhite); legendsx_d->SetBorderSize (1); legendsx_d->SetNColumns(1); legendsx_d->SetTextSize(.040); legendsx_d->AddEntry (leading, "Sherpa", "PEL"); legendsx_d->AddEntry (leadingmuo, "Madgraph", "PEL"); legendsx_d->Draw ("same"); // Draw the ratio plot: ---------------------- leadingRatio = (TH1D *) leading->Clone ("leading"); leadingRatio->Divide(leadingmuo); for (int mem=1; mem<=leadingRatio->GetNbinsX(); mem++) { cout << "Syst for bin nr." << mem << ":\t" << fabs(leadingRatio->GetBinContent(mem)-1.0)/2 << endl; } plots->cd(); TPad *pad3 = new TPad("pad3","pad3",0.01,0.01,0.99,0.30); pad3->Draw(); pad3->cd(); pad3->SetTopMargin(0.0); pad3->SetBottomMargin(0.3); pad3->SetLeftMargin(0.2); pad3->SetRightMargin(0); pad3->SetFillStyle(0); leadingRatio->GetXaxis()->SetLabelFont (42); leadingRatio->GetXaxis()->SetTitleFont (42); leadingRatio->GetXaxis()->SetTitleSize(0.11); leadingRatio->GetXaxis()->SetLabelSize(0.11); leadingRatio->GetXaxis()->SetTitleOffset (1.1); leadingRatio->GetYaxis()->SetTitleSize(0.11); leadingRatio->GetYaxis()->SetLabelSize(0.10); leadingRatio->GetYaxis()->SetTitleOffset(0.65); leadingRatio->GetYaxis()->SetTitle("Ratio"); leadingRatio->GetYaxis()->SetNdivisions(5); leadingRatio->GetYaxis()->SetRangeUser(0.4,1.6); if (use_case ==1) { leadingRatio->GetXaxis ()->SetTitle ("Exclusive jet multiplicity"); } if (use_case ==2) { if (whichjet == 1) leadingRatio->GetXaxis ()->SetTitle ("Leading jet p_{T} [GeV]"); if (whichjet == 2) leadingRatio->GetXaxis ()->SetTitle ("Second jet p_{T} [GeV]"); if (whichjet == 3) leadingRatio->GetXaxis ()->SetTitle ("Third jet p_{T} [GeV]"); if (whichjet == 4) leadingRatio->GetXaxis ()->SetTitle ("Fourth jet p_{T} [GeV]"); } if (use_case ==3) { if (whichjet == 1) leadingRatio->GetXaxis ()->SetTitle ("Leading jet #eta"); if (whichjet == 2) leadingRatio->GetXaxis ()->SetTitle ("Second jet #eta"); if (whichjet == 3) leadingRatio->GetXaxis ()->SetTitle ("Third jet #eta"); if (whichjet == 4) leadingRatio->GetXaxis ()->SetTitle ("Fourth jet #eta"); } if (use_case ==4) { if (whichjet == 1) leadingRatio->GetXaxis ()->SetTitle ("H_{T}, N_{jet} >= 1 [GeV]"); if (whichjet == 2) leadingRatio->GetXaxis ()->SetTitle ("H_{T}, N_{jet} >= 2 [GeV]"); if (whichjet == 3) leadingRatio->GetXaxis ()->SetTitle ("H_{T}, N_{jet} >= 3 [GeV]"); if (whichjet == 4) leadingRatio->GetXaxis ()->SetTitle ("H_{T}, N_{jet} >= 4 [GeV]"); } leadingRatio->SetFillColor (kRed+2); leadingRatio->SetMarkerColor (kRed+2); leadingRatio->SetLineColor (kRed+2); leadingRatio->Draw ("E0"); leadingRatioSystematics->SetFillColor (kGreen+3); leadingRatioSystematics->SetFillStyle (3004); leadingRatioSystematics->SetMarkerColor (kGreen+3); leadingRatioSystematics->SetLineColor (kGreen+3); leadingRatioSystematics->SetMarkerStyle (1); //leadingRatioSystematics->Draw ("E3SAME"); leadingRatio->Draw ("E1SAME"); myfile.open (fileSystematics.c_str()); cout<<"TXT file saved in "<<fileSystematics<<endl; loopAndDumpEntries(leadingRatio,leadingmuo); TLine *OLine2 = new TLine(leading->GetXaxis()->GetXmin(),1.,leading->GetXaxis()->GetXmax(),1.); OLine2->SetLineColor(kBlack); OLine2->SetLineStyle(2); OLine2->Draw(); //latexLabel->SetTextSize(0.09); // latexLabel->DrawLatex(0.2,0.35,"Ratio"); ///////////////////////////////////////////////////// string title1; title1 = s + "DifferentialX" + stringmatch + ".pdf"; cout << title1 << endl; plots->Print (title1.c_str ()); plots->Draw(); return; } }
int main(int argc, char* argv[]) { cerr << "Score v2.5 written by Philipp Koehn" << endl << "Modified by Ventsislav Zhechev, Autodesk Development Sàrl" << endl << "scoring methods for extracted rules" << endl ; if (argc < 4) { cerr << "syntax: score extract lex phrase-table [--Inverse] [--Hierarchical] [--OnlyDirect] [--LogProb] [--NegLogProb] [--NoLex] [--GoodTuring] [--WordAlignment file]\n"; exit(1); } char* fileNameExtract = argv[1]; char* fileNameLex = argv[2]; char* fileNamePhraseTable = argv[3]; char* fileNameWordAlignment; for(int i=4; i<argc; ++i) { if (strcmp(argv[i],"inverse") == 0 || strcmp(argv[i],"--Inverse") == 0) { inverseFlag = true; cerr << "using inverse mode\n"; } else if (strcmp(argv[i],"--Hierarchical") == 0) { hierarchicalFlag = true; cerr << "processing hierarchical rules\n"; } else if (strcmp(argv[i],"--OnlyDirect") == 0) { onlyDirectFlag = true; cerr << "outputing in correct phrase table format (no merging with inverse)\n"; } else if (strcmp(argv[i],"--WordAlignment") == 0) { wordAlignmentFlag = true; fileNameWordAlignment = argv[++i]; cerr << "outputing word alignment in file " << fileNameWordAlignment << endl; } else if (strcmp(argv[i],"--NoLex") == 0) { lexFlag = false; cerr << "not computing lexical translation score\n"; } else if (strcmp(argv[i],"--GoodTuring") == 0) { goodTuringFlag = true; cerr << "using Good Turing discounting\n"; } else if (strcmp(argv[i],"--LogProb") == 0) { logProbFlag = true; cerr << "using log-probabilities\n"; } else if (strcmp(argv[i],"--NegLogProb") == 0) { logProbFlag = true; negLogProb = -1; cerr << "using negative log-probabilities\n"; } else { cerr << "ERROR: unknown option " << argv[i] << endl; exit(1); } } // lexical translation table if (lexFlag) lexTable.load(fileNameLex); // compute count of counts for Good Turing discounting if (goodTuringFlag) computeCountOfCounts(fileNameExtract); // sorted phrase extraction file Bz2LineReader extractFile(fileNameExtract); // output file: phrase translation table Bz2LineWriter phraseTableFile(fileNamePhraseTable); // output word alignment file if (!inverseFlag && wordAlignmentFlag) { wordAlignmentFile.open(fileNameWordAlignment); if (wordAlignmentFile.fail()) { cerr << "ERROR: could not open word alignment file " << fileNameWordAlignment << endl; exit(1); } } // loop through all extracted phrase translations int lastSource = -1; vector< PhraseAlignment > phrasePairsWithSameF; int i=0; string lastLine = ""; PhraseAlignment *lastPhrasePair = NULL; for (string line = extractFile.readLine(); !line.empty(); line = extractFile.readLine()) { if (line.empty()) break; if ((++i)%10000000 == 0) cerr << "[p. score:" << i << "]" << flush; else if (i % 100000 == 0) cerr << "." << flush; // identical to last line? just add count if (lastSource >= 0 && line == lastLine) { lastPhrasePair->addToCount(line); continue; } lastLine = line; // create new phrase pair PhraseAlignment phrasePair; vector<string> lineVector = tokenize(line.c_str()); phrasePair.create(lineVector, i); // only differs in count? just add count if (lastPhrasePair != NULL && lastPhrasePair->equals(phrasePair)) { lastPhrasePair->count += phrasePair.count; phrasePair.clear(); continue; } // if new source phrase, process last batch if (lastSource >= 0 && lastSource != phrasePair.source) { processPhrasePairs(phrasePairsWithSameF, phraseTableFile); for (size_t j=0; j<phrasePairsWithSameF.size(); phrasePairsWithSameF[j++].clear()); phrasePairsWithSameF.clear(); phraseTableT.clear(); phraseTableS.clear(); // process line again, since phrase tables flushed phrasePair.clear(); phrasePair.create(lineVector, i); } // add phrase pairs to list, it's now the last one lastSource = phrasePair.source; phrasePairsWithSameF.push_back(phrasePair); lastPhrasePair = &phrasePairsWithSameF[phrasePairsWithSameF.size()-1]; } processPhrasePairs(phrasePairsWithSameF, phraseTableFile); if (!inverseFlag && wordAlignmentFlag) wordAlignmentFile.close(); }
//------------------------------------------------------------------------------------ int EditDDs(void) throw(Exception) { try { if(CI.Verbose) oflog << "BEGIN EditDDs()" << " at total time " << fixed << setprecision(3) << double(clock()-totaltime)/double(CLOCKS_PER_SEC) << " seconds." << endl; if(!CI.OutputTDDFile.empty()) { tddofs.open(CI.OutputTDDFile.c_str(),ios::out); if(tddofs.is_open()) { oflog << "Opened file " << CI.OutputTDDFile << " for triple difference and cycle slip output." << endl; tddofs << "# " << Title << endl; tddofs << "TDS site site sat sat freq iter cnt week sow " << "dcnt TD(m) slip(cy) frac\n"; tddofs << "SED site site sat sat freq iter cnt week sow " << "DDres(m) TDres(m)\n"; } else { oflog << "Warning - Failed to open file " << CI.OutputTDDFile << endl; } } if(CI.Verbose) { oflog << " TUR site site sat sat iter N Average StdDev SigYX" << " Median M-est MAD\n"; oflog << " SUR site site sat sat iter N Average StdDev SigYX" << " Median M-est MAD\n"; } int i,j,k; map<DDid,DDData>::iterator it; // ------------------------------------------------------------------- // delete DD buffers that are too small, or that user wants to exclude // also compute maxCount, the largest value of Count seen in all baselines maxCount = 0; vector<DDid> DDdelete; for(it = DDDataMap.begin(); it != DDDataMap.end(); it++) { // is it too small? if(it->second.count.size() < CI.MinDDSeg) { DDdelete.push_back(it->first); continue; } // prepare 'mark' vector mark.assign(it->second.count.size(),1); ngood = mark.size(); nbad = 0; // remove points where bias had to be reset multiple times k = EditDDResets(it->first, it->second); if(k || ngood < CI.MinDDSeg) { DDdelete.push_back(it->first); continue; } // remove isolated points k = EditDDIsolatedPoints(it->first, it->second); if(k || ngood < CI.MinDDSeg) { DDdelete.push_back(it->first); continue; } // find and remove slips if(CI.Frequency != 2) { // L1 k = EditDDSlips(it->first, it->second,1); if(k || ngood < CI.MinDDSeg) { DDdelete.push_back(it->first); continue; } } if(CI.Frequency != 1) { // L2 k = EditDDSlips(it->first, it->second,2); if(k || ngood < CI.MinDDSeg) { DDdelete.push_back(it->first); continue; } } // find and remove outliers if(CI.Frequency != 2) { // L1 k = EditDDOutliers(it->first, it->second,1); if(k || ngood < CI.MinDDSeg) { DDdelete.push_back(it->first); continue; } } if(CI.Frequency != 1) { // L2 k = EditDDOutliers(it->first, it->second,2); if(k || ngood < CI.MinDDSeg) { DDdelete.push_back(it->first); continue; } } // output raw data with mark OutputRawDData(it->first, it->second, mark); // use vector 'mark' to delete data if(nbad > 0) { vector<double> nDDL1,nDDL2,nDDP1,nDDP2,nDDER; vector<int> ncount; for(i=0; i<it->second.count.size(); i++) { if(mark[i] == 1) { nDDL1.push_back(it->second.DDL1[i]); nDDL2.push_back(it->second.DDL2[i]); nDDP1.push_back(it->second.DDP1[i]); nDDP2.push_back(it->second.DDP2[i]); nDDER.push_back(it->second.DDER[i]); ncount.push_back(it->second.count[i]); } } it->second.DDL1 = nDDL1; it->second.DDL2 = nDDL2; it->second.DDP1 = nDDP1; it->second.DDP2 = nDDP2; it->second.DDER = nDDER; it->second.count = ncount; // ignore resets from now on... } // find the max count if(it->second.count[it->second.count.size()-1] > maxCount) maxCount = it->second.count[it->second.count.size()-1]; } // close the output file tddofs.close(); mark.clear(); // now delete the ones that were marked for(i=0; i<DDdelete.size(); i++) { if(CI.Verbose) oflog << setw(2) << DDdelete[i] << " total = " << setw(5) << DDDataMap[DDdelete[i]].count.size() << ", count = " << setw(5) << DDDataMap[DDdelete[i]].count[0] << " - " << setw(5) << DDDataMap[DDdelete[i]].count[DDDataMap[DDdelete[i]].count.size()-1] << " -- Delete this DD dataset." << endl; DDDataMap.erase(DDdelete[i]); } DDdelete.clear(); // ------------------------------------------------------------------- // output DD summary { // use this loop to compute the number of DDs long nDDs; ostringstream oss; oss << "Double differences summary:" << endl; for(k=1,nDDs=0,it=DDDataMap.begin(); it!=DDDataMap.end(); it++,k++) { // output oss << " " << setw(2) << k << " " << it->first << " " << setw(5) << it->second.count.size() << " " << setw(5) << it->second.count[0] << " - " << setw(5) << it->second.count[it->second.count.size()-1]; nDDs += it->second.count.size(); // gaps - (count : number of pts) for(i=0; i<it->second.count.size()-1; i++) { j = it->second.count.at(i+1) - it->second.count.at(i); if(j > 1) oss << " (" << it->second.count.at(i)+1 << ":" << j-1 << ")"; } oss << endl; } // output if(CI.Verbose) oflog << oss.str(); if(CI.Screen) cout << oss.str(); // check that there were some DDs if(k <= 1 || nDDs < 500) { // what is the min number of DDs ? oflog << "Too few double differences (" << nDDs << ") were found.. Abort." << endl; cout << "Too few double differences (" << nDDs << ") were found.. Abort." << endl; return -3; } } // dump buffers to a file OutputDDData(); return 0; } catch(Exception& e) { GPSTK_RETHROW(e); } catch(exception& e) { Exception E("std except: "+string(e.what())); GPSTK_THROW(E); } catch(...) { Exception e("Unknown exception"); GPSTK_THROW(e); } } // end EditDDs()
/* Process the requests from the clients, and return the feedback */ string process_request(char* p_cmd, int sock, int type) { string rt; string rcmd; // REAL CMD string args; if (type == FTP_CONTROL_TYPE) { cout << FTP_LOG_HEAD << " Get a control cmd: " << p_cmd << ", at " << sock << endl; int i; for (i = 0; i<CMD_MAX_LENGTH; i++) { if (p_cmd[i] != ' ' && p_cmd[i] != '\0' && p_cmd[i] != '\n') rcmd += p_cmd[i]; else break; } for (int j = i+1; j<CMD_MAX_LENGTH; j++) { if (p_cmd[j] != '\0' && p_cmd[i] != '\n') args += p_cmd[j]; else break; } //cout << "REAL CMD:" << rcmd << ", args:" << args << endl; if (rcmd == FTP_CMD_USER) { /* Request a password */ rt = FTP_RSP_R_PASS; strcpy(clients[sock].user, rcmd.c_str()); } else if (rcmd == FTP_CMD_PASS) { /* Get the user, then match them. */ /* In the future, this should be put into the database. */ if (args == "super123") { clients[sock].is_logged = true; clients[sock].set_password(args.c_str()); rt = FTP_RSP_P_PASS; } else rt = FTP_RSP_E_PASS; } else if (rcmd == FTP_CMD_LIST) { if (clients[sock].is_logged) { rt = FTP_RSP_LIST; DIR* dir; struct dirent* ptr; dir = opendir(FTP_DIR); while ((ptr = readdir(dir)) != NULL) { /* Strcmp will return a true value while dismatching. */ #ifdef __linux if (!strcmp(ptr->d_name, ".")) continue; else if (!strcmp(ptr->d_name, "..")) continue; struct stat file_stat; string file_path(FTP_DIR); file_path += ptr->d_name; stat(file_path.c_str(), &file_stat); rt += ptr->d_type; rt += " "; rt += ptr->d_name; string temp; temp += ptr->d_type; temp += " "; temp += ptr->d_name; // TODO-- This place, the file name may be greater than 50 place. for (int pos = temp.length(); pos<40; pos++) rt += " "; rt += byte2std(file_stat.st_size); rt += "\n"; #endif } closedir(dir); } else rt = FTP_RSP_R_LOG; } else if (rcmd == FTP_CMD_PUT) { if (clients[sock].is_logged) { rt = FTP_RSP_RF_START; string file_path(FTP_DIR); file_path += args; //strcpy(file_name[sock], args.c_str()); --real use strcpy(file_name_temp, args.c_str()); //ofs[sock].open(file_path.c_str(), ios::binary); ofs_temp.open(file_path.c_str(), ios::binary); } else rt = FTP_RSP_R_LOG; } else if (rcmd == FTP_CMD_GET) { if (clients[sock].is_logged) { rt = FTP_RSP_SF_START; string file_path(FTP_DIR); file_path += args; //strcpy(file_name[sock], args.c_str()); strcpy(file_name_temp, args.c_str()); //ifs[sock].open(file_path.c_str(), ios::binary); // TODO--judge whether the file exists. ifs_temp.open(file_path.c_str(), ios::binary); } else rt = FTP_RSP_R_LOG; } else if (rcmd == FTP_CMD_QUIT) { rt = FTP_RSP_BYE; } else rt = FTP_RSP_ERR; return rt; } else { // p_cmd = buffer if (p_cmd[0] == FTP_FTR_CMD_CONTINUE) { rt = FTP_FTR_CMD_CONTINUE; cout << FTP_LOG_HEAD << "Write into " << file_name_temp << ", size of " << strlen(p_cmd)-1 << endl; /* More comman way, but it need to be tested for binary and ascii! */ int b_len = strlen(p_cmd); for (int d = 1; d<b_len; d++) ofs_temp.put(p_cmd[d]); } else if (p_cmd[0] == FTP_FTR_CMD_ENDALL) { rt = FTP_FTR_CMD_ENDALL; memset(p_cmd, 0, sizeof(p_cmd)); strcpy(file_name[sock], ""); strcpy(file_name_temp, ""); //ofs[sock].close(); ofs_temp.close(); } /* Sending files would return the file data. */ else if (p_cmd[0] == FTP_FTS_CMD_CONTINUE) { /* Just like writing */ ifs_temp.read(buffer[sock]+1, sizeof(buffer[sock])-1); /* Get the file ending, gcount() is not useful for now. */ int real_read = ifs_temp.gcount(); if (real_read < FILE_MAX_BUFFER) { rt = FTP_FTS_CMD_ENDALL; buffer[sock][0] = FTP_FTS_CMD_ENDALL; } else { rt = FTP_FTS_CMD_CONTINUE; buffer[sock][0] = FTP_FTS_CMD_CONTINUE; } cout << FTP_LOG_HEAD << "Read from " << file_name_temp << ", size of " << real_read << endl; // For future features rt.append(p_cmd+1); } else if (p_cmd[0] == FTP_FTS_CMD_ENDALL) { rt = FTP_FTS_CMD_ENDALL; memset(p_cmd, 0, sizeof(p_cmd)); strcpy(file_name[sock], ""); strcpy(file_name_temp, ""); //ifs[sock].close(); ifs_temp.close(); } else { /* Breakpoint resends, and errors handle in the future. */ rt = FTP_FT_ERR; } return rt; } }
/** * Define an optimization problem that finds a set of muscle controls to maximize * the forward velocity of the forearm/hand segment mass center. */ 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_withArms.osim"); // 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 ... ]' */ // initialize controller parameters Vector controllerParameters(numParameters, 0.05); // initialize initial times for each excitation 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 controllerParameters[24] = 0.2; //arm_flex // 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 controllerParameters[25] = 0.01; //arm_flex // 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); // Lowest 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; }
void Print(const Graph& mGraph, const vector<Graph::Primitive*>& mPrimitives) { #ifdef EXTRACT_PRIMITIVES Vec2 v0, v1; double x0, y0, x1, y1; int j0, j1, index; const int numPrimitives = (int)mPrimitives.size(); int i; for (i = 0; i < numPrimitives; ++i) { Graph::Primitive* primitive = mPrimitives[i]; int numElements = (int)primitive->Sequence.size(); switch (primitive->Type) { case Graph::PT_ISOLATED_VERTEX: v0 = primitive->Sequence[0].first; x0 = v0.X(); y0 = v0.Y(); index = primitive->Sequence[0].second; fout.open("./isolated_vert_PlanarGraph.txt",ios::out|ios::app); fout<<index+1<<" "; fout.close(); //SetThickPixel(x0, y0, 1, mColors[i]); break; case Graph::PT_FILAMENT: for (j0 = 0, j1 = 1; j1 < numElements; ++j0, ++j1) { v0 = primitive->Sequence[j0].first; x0 = (int)v0.X(); y0 = (int)v0.Y(); v1 = primitive->Sequence[j1].first; x1 = (int)v1.X(); y1 = (int)v1.Y(); int index2 = primitive->Sequence[j1].second; fout.open("./Filaments_PlanarGraph.txt",ios::out|ios::app); if (j0==0) { int index1 = primitive->Sequence[j0].second; fout<<index1+1<<" "<<index2+1<<" "; } //DrawLine(x0, y0, x1, y1, mColors[i]); else { fout<<index2+1<<" "; }; } fout<<endl; fout.close(); break; case Graph::PT_MINIMAL_CYCLE: // if (fout.is_open()) { //cout<<"File is open\n"; //fout << numElements<<"\n"; //cout << "Number of points in the cycle: "<<numElements<<"\n"; fout.open("./Cycles_PlanarGraph.txt",ios::out|ios::app); for (j0 = numElements - 1, j1 = 0; j1 < numElements; j0 = j1++) { v0 = primitive->Sequence[j0].first; x0 = (int)v0.X(); y0 = (int)v0.Y(); v1 = primitive->Sequence[j1].first; x1 = (int)v1.X(); y1 = (int)v1.Y(); index = primitive->Sequence[j0].second; fout<<index+1<<" "; // cout<<index+1<<" "; //DrawLine(x0, y0, x1, y1, mColors[i]); } fout<<endl; // cout<<endl; fout.close(); break; } } } #endif }
/* finishing... */ VOID fini_stride(INT32 code, VOID* v){ int i; UINT64 cum; if(interval_size == -1){ output_file_stride.open("stride_full_int_pin.out", ios::out|ios::trunc); } else{ output_file_stride.open("stride_phases_int_pin.out", ios::out|ios::app); } output_file_stride << numReadInstrsAnalyzed; /* local read distribution */ cum = 0; for(i = 0; i < MAX_DISTR; i++){ cum += localReadDistrib[i]; if( (i == 0) || (i == 8) || (i == 64) || (i == 512) || (i == 4096) || (i == 32768) || (i == 262144) ){ if(cum > 0) output_file_stride << " " << cum; else output_file_stride << " 0"; } if(i == 262144) break; } /* global read distribution */ cum = 0; for(i = 0; i < MAX_DISTR; i++){ cum += globalReadDistrib[i]; if( (i == 0) || (i == 8) || (i == 64) || (i == 512) || (i == 4096) || (i == 32768) || (i == 262144) ){ if(cum > 0) output_file_stride << " " << cum; else output_file_stride << " 0"; } if(i == 262144) break; } output_file_stride << " " << numWriteInstrsAnalyzed; /* local write distribution */ cum = 0; for(i = 0; i < MAX_DISTR; i++){ cum += localWriteDistrib[i]; if( (i == 0) || (i == 8) || (i == 64) || (i == 512) || (i == 4096) || (i == 32768) || (i == 262144) ){ if(cum > 0) output_file_stride << " " << cum; else output_file_stride << " 0"; } if(i == 262144) break; } /* global write distribution */ cum = 0; for(i = 0; i < MAX_DISTR; i++){ cum += globalWriteDistrib[i]; if( (i == 0) || (i == 8) || (i == 64) || (i == 512) || (i == 4096) || (i == 32768) ){ if(cum > 0) output_file_stride << " " << cum; else output_file_stride << " 0"; } if(i == 262144){ if(cum > 0) output_file_stride << " " << cum << endl; else output_file_stride << " 0" << endl; break; } } output_file_stride << "number of instructions: " << total_ins_count_for_hpc_alignment << endl; output_file_stride.close(); }
bool TraceInit(const char* filename) { traceFile.open(filename); return traceFile.is_open(); }
void TraceClose() { traceFile.close(); }
extern "C" __declspec( dllexport ) void Init2() { outfile.open("dynamic_secondary_dll.out"); outfile << hex << showbase; }
extern "C" __declspec( dllexport ) void Fini2() { outfile.close(); }
int parseCommandLine_format(int argc, char *argv[]) { int index, c; static struct option longOptions[] = { {"file", required_argument, 0, 'f' }, {"out", required_argument, 0, 'o' }, {"lineWidth", required_argument, 0, 'w' }, {"minLen", required_argument, 0, 'm' }, {"maxLen", required_argument, 0, 'M' }, {"fastq", no_argument, 0, 'q' }, {"filterN", no_argument, 0, 'n' }, {"noComment", no_argument, 0, 'c' }, {"pacbio", no_argument, 0, 'p' }, {"help", no_argument, 0, 'h' }, {"version", no_argument, 0, 'v' }, {0,0,0,0} }; while ( (c = getopt_long ( argc, argv, "f:o:w:m:M:qncphv", longOptions, &index))!= -1 ) { switch (c) { case 'f': _format_IN_FILE = optarg; break; case 'o': _format_OUT_FILE = optarg; break; case 'w': _format_LINE_WIDTH = str2type<int>(optarg); break; case 'm': _format_MIN_LEN = str2type<long long>(optarg); break; case 'M': _format_MAX_LEN = str2type<long long>(optarg); break; case 'q': _format_isFastq = true; break; case 'n': _format_filterN = true; break; case 'c': _format_noComment = false; break; case 'p': _format_pacbio = true; break; case 'h': printHelp_format(); return 0; break; case 'v': cout << "Version: " << FASTUTILS_VERSION << endl; cout << "Build Date: " << BUILD_DATE << endl; return 0; break; default: cerr << "[ERROR] run \"fastUtils shuffle -h\" to get a list of acceptable arguments." << endl; cerr << endl; return 0; } } if(_format_IN_FILE == "") { cerr << endl; cerr<< "[ERROR] option -f is required" << endl; cerr << endl; return 0; } if(_format_LINE_WIDTH < 0) _format_LINE_WIDTH = 0; if(_format_MIN_LEN < 0) _format_MIN_LEN = 0; if(_format_MAX_LEN < 0) _format_MAX_LEN = LLONG_MAX; if(_format_MIN_LEN > _format_MAX_LEN) { cerr << endl; cerr<< "[ERROR] minLen cannot be greater than maxLen" << endl; cerr << endl; return 0; } if(_format_OUT_FILE == "") { _format_pout = &cout; } else { _format_fout.open(_format_OUT_FILE.c_str()); if(_format_fout.is_open()==false) { cerr<< "[ERROR] could not open file: " << _format_OUT_FILE << endl; return 0; } _format_pout = &_format_fout; } return 1; }
int main(int argc, char* argv[]) { //At start state all spins =+1, in case we want random start uncomment random. char *outfilename; long idum; int **spin_matrix, n_spins, mcs, flips; double w[17], average[5], initial_temp, final_temp, E, M, temp_step; // Read in output file, abort if there are too few command-line arguments if( argc <= 1 ){ cout << "Bad Usage: " << argv[0] << " read also output file on same line" << endl; exit(1); } else{ outfilename=argv[1]; } ofile.open(outfilename); // Read in initial values such as size of lattice, temp and cycles read_input(n_spins, mcs, initial_temp, final_temp, temp_step); spin_matrix = (int**) matrix(n_spins, n_spins, sizeof(int)); idum = -1; // random starting point<<{this is used to initialize the method ran1 found in lib.cpp} for ( double temperature = initial_temp; temperature <= final_temp; temperature+=temp_step){ flips=0; // setup array for possible energy changes for( int de =-8; de <= 8; de++) w[de+8] = 0; for( int de =-8; de <= 8; de+=4) w[de+8] = exp(-de/temperature); // initialise array for expectation values for( int i = 0; i < 5;i++) average[i] = 0.;//{it is used to stor the following values E,E^2, M,M^2, |M|,flips} //the initialization calculate E and M we start with giving a start temperature and the size of the grid. //we send the info n_spins, temp, the spin:matrix and the adresse of E and M to updated the initial //values of the E & M of the system. if(temperature == initial_temp) { // initialise energy and magnetization E = M = 0.; initialize(n_spins, temperature, spin_matrix, E, M); } // start Monte Carlo computation //int cycles ; for (int cycles = 1; cycles <= mcs; cycles++) { Metropolis(n_spins, idum, spin_matrix, E, M, w, flips); // update expectation values //NB:for each Metro cycle we get a possible state, note the temp is unchanged so those are just possible states //for the one giving temp. The simulation should bring the system to the most possible // E and M giving spesified temperature as it stablise. average[0] += E; average[1] += E*E; average[2] += M; average[3] += M*M; average[4] += fabs(M); //output(n_spins, cycles, temperature ,average, flips,E); //this line is used in case we want to store the averages as function of mcs } // print results cout << "Your flips prosent is "<< (double)flips/n_spins/n_spins/mcs <<"\n"; output(n_spins, mcs, temperature,average, flips,E);//This line in case u want to save the data as function of tempirature } free_matrix((void **) spin_matrix); // free memory ofile.close(); // close output file return 0; }
int main(int argc, char* argv[]) { cout << "size of unsigned " << sizeof(unsigned) << endl; cout << "size of unsigned long " << sizeof(unsigned long) << endl; cout << "size of unsigned long long " << sizeof(unsigned long long) << endl; if (argc!=7) { std::cerr<<"\n\nUSE: corr <path/ReadFile> <path/MapPoolsToBacsFile> <path/OutputFile> <k-mer_size> <input_file_number> <thread>\n\n"; exit(EXIT_FAILURE); } string readFname(argv[1]); kmerSize=atoi(argv[4]); cores=atoi(argv[6]); unsigned int files=atoi(argv[5]); char delimC[] = "."; Parser parser; parser.update(delimC, readFname); cout << "MAX_KMERS is " << MAX_KMERS(kmerSize) << endl; Timer* pTimer; ioh=new IOF<mybitsetx>(argv[1], argv[2], argv[3], kmerSize, files); ioh->ReadB(); //ioh.CheckCorrect(); //load BAC sigs into trie unsigned short* bacPools=(unsigned short*)malloc(sizeof(unsigned short)*BACS*LAYERS); readBacMappings(bacPools); trie=new Trie(); for (unsigned short i=0;i<BACS;i++) trie->insert(&bacPools[i*LAYERS], 7, i+1); pools2bacs=new HashTable<mysig>(); pools2bacs->allocHash(2); reads=(struct readFasta*)malloc(MAX_POOL_SIZE*sizeof(struct readFasta)); if (!reads) { perror("Error allocating the reads!"); exit(1); } for (unsigned int r=0; r<MAX_POOL_SIZE; r++) { reads[r].header=NULL; reads[r].read=NULL; } for (unsigned int i=52;i<91;i++) { numReads = ioh->readReads(i, reads); printf("Number of reads read is %d\n", numReads); unsigned int numHit=0; unsigned int numSearch=0; //output files for corrected and uncorrected reads ostringstream of, of1; of<<parser.get(0)<<i<<"."<<"corr"; out.open(of.str().c_str(), ios_base::out); if(!out) { cerr<<"Error opening output file "<<of.str()<<endl; exit(EXIT_FAILURE); }; //correct reads in this pool pTimer=new Timer("correct reads in pool"); correctReads(i,numSearch,numHit); delete pTimer; //empty cache //if (i%5==0) // pools2bacs->makeEmpty(); cout << "Pool " << i << ", numSearch " << numSearch << ", numHit " << numHit << endl; out.close(); }//end for i for (unsigned int r=0; r<MAX_POOL_SIZE; r++) { free(reads[r].header); free(reads[r].read); } free(reads); return 0; }
void searchForMovement(Mat thresholdImage, Mat &cameraFeed){ ofstream fil_X,fil_Xk,fil_Y,fil_Yk; fil_X.open("X.txt", ios::app); fil_Xk.open("Xk.txt", ios::app); fil_Y.open("Y.txt", ios::app); fil_Yk.open("Yk.txt", ios::app); static unsigned int time = 0; bool objectDetected = false; Mat temp; thresholdImage.copyTo(temp); //these two vectors needed for output of findContours vector< vector<Point> > contours; vector<Vec4i> hierarchy; //find contours of filtered image using openCV findContours function //findContours(temp,contours,hierarchy,CV_RETR_CCOMP,CV_CHAIN_APPROX_SIMPLE );// retrieves all contours findContours(temp,contours,hierarchy,CV_RETR_EXTERNAL,CV_CHAIN_APPROX_SIMPLE );// retrieves external contours //if contours vector is not empty, we have found some objects if(contours.size()>0)objectDetected=true; else objectDetected = false; if(objectDetected){ //the largest contour is found at the end of the contours vector //we will simply assume that the biggest contour is the object we are looking for. vector< vector<Point> > largestContourVec; largestContourVec.push_back(contours.at(contours.size()-1)); //make a bounding rectangle around the largest contour then find its centroid //this will be the object's final estimated position. objectBoundingRectangle = boundingRect(largestContourVec.at(0)); int xpos = objectBoundingRectangle.x+objectBoundingRectangle.width/2; int ypos = objectBoundingRectangle.y+objectBoundingRectangle.height/2; //update the objects positions by changing the 'theObject' array values theObject[0] = xpos , theObject[1] = ypos; } //make some temp x and y variables so we dont have to type out so much int x = theObject[0]; int y = theObject[1]; static int flagg = 0; if(flagg<5) flagg=flagg+1; if (flagg == 3) { Prior = (Mat_<float>(4, 1) << x, y, 0, 0); } float KalX; float KalY; KalX = x; KalY = y; Kalman_Filter(&KalX, &KalY); KalX = (int)KalX; KalY = (int)KalY; /* fil_X <<","<< x << ", " << time;// .open("X.txt"); fil_Xk <<","<< KalX <<", "<<time;// .open("Xk.txt"); fil_Y << "," << y << ", " << time; fil_Yk << "," << KalY << ", " << time; time++;*/ //draw some crosshairs around the object for kalman filter circle(cameraFeed, Point(KalX, KalY), 25, Scalar(0, 0,255), 2); line(cameraFeed, Point(KalX, KalY), Point(KalX, KalY - 25), Scalar(0, 0, 255), 2); line(cameraFeed, Point(KalX, KalY), Point(KalX, KalY + 25), Scalar(0, 0,255), 2); line(cameraFeed, Point(KalX, KalY), Point(KalX - 25, KalY), Scalar(0, 0,255), 2); line(cameraFeed, Point(KalX, KalY), Point(KalX + 25, KalY), Scalar(0, 0,255), 2); //draw some crosshairs around the object circle(cameraFeed,Point(x,y),20,Scalar(0,255,0),2); line(cameraFeed,Point(x,y),Point(x,y-25),Scalar(0,255,0),2); line(cameraFeed,Point(x,y),Point(x,y+25),Scalar(0,255,0),2); line(cameraFeed,Point(x,y),Point(x-25,y),Scalar(0,255,0),2); line(cameraFeed,Point(x,y),Point(x+25,y),Scalar(0,255,0),2); //write the position of the object to the screen //putText(cameraFeed,"Tracking object at (" + intToString(x)+","+intToString(y)+")",Point(x,y),1,1,Scalar(255,0,0),2); //putText(cameraFeed, "Tracking object at (" + intToString(KalX) + "," + intToString(KalY) + ")", Point(KalX, KalY), 1, 1, Scalar(255, 0, 0), 2); }
void fileClose() { myfile.close(); }
int main(int argc, char** argv){ string fileName=""; int camIndex=-1; char flag; char options[]="hp:m:c::"; char inputMedia=Unknown; CvCapture* capture=NULL; IplImage* original=NULL; IplImage* frame=NULL; while((flag=getopt(argc, argv, options)) != -1){ switch(flag){ case 'h': printUsage(argv[0]); exit(EXIT_SUCCESS); case 'c': if(optarg == 0){ if(optind < argc){ camIndex=atoi(argv[optind]); } } else{ camIndex=atoi(optarg); } inputMedia=Camera; break; case 'p': fileName=optarg; inputMedia=Photo; break; case 'm': fileName=optarg; inputMedia=Video; break; default: printUsage(argv[0]); exit(-1); } } if(inputMedia==Video){ capture = cvCaptureFromAVI(fileName.c_str()); if(!capture){ cerr<<"Error: Could not open video "<<fileName<<endl; exit(-1); } cout<<"Reading video "<<fileName<<endl; frame=getFrame(capture); } if(inputMedia==Photo){ original=cvLoadImage(fileName.c_str()); if(original == NULL){ cout<<"Error: Could not load photo "<<fileName<<endl; exit(-1); } cout<<"Input image depth="<<original->depth<<endl; int width = original->width; int height = original->height; if(original->width > 512 || original->height > 512){ width = width/2; height = height/2; frame = cvCreateImage( cvSize(width, height), original->depth, original->nChannels ); cvResize(original, frame); } else{ frame=cvCreateImage( cvGetSize(original), original->depth, original->nChannels ); cvCopy(original, frame); } cout<<"Loaded photo "<<fileName<<endl; } if(inputMedia==Camera){ capture = cvCaptureFromCAM(camIndex); if(!capture){ cerr<<"Error: Could not open camera "<<camIndex<<endl; exit(-1); } cout<<"Reading from camera "<<camIndex<<endl; frame=getFrame(capture); } if(inputMedia==Unknown){ cout<<"Option error!"<<endl; printUsage(argv[0]); exit(-1); } IplImage* greyImg=NULL; IplImage* edgeImg=NULL; IplImage* input = frame; IplImage* colorSpace =NULL; if(frame->width > 512 || frame->height > 512){ int width = frame->width/2; int height = frame->height/2; colorSpace=cvCreateImage(cvSize(width, height), frame->depth, frame->nChannels); cvResize(frame, colorSpace); } else{ colorSpace=cvCreateImage(cvGetSize(frame), frame->depth, frame->nChannels); } cvNamedWindow("Input", CV_WINDOW_AUTOSIZE); cvNamedWindow("ColorSpace", CV_WINDOW_AUTOSIZE); cvNamedWindow("Grey", CV_WINDOW_AUTOSIZE); cvNamedWindow("Lines", CV_WINDOW_AUTOSIZE); //cvNamedWindow("Controls", 0); cvSetMouseCallback("Input", mouseHandler, (void*)colorSpace); cvSetMouseCallback("ColorSpace", mouseHandler, (void*)colorSpace); int colorIndex=2; int colorChannel=0; int lineThresh=20; int minLength=30; int maxGap=10; int cannyThresh1=10; int cannyThresh2=200; int cannyAperture=1; cvCreateTrackbar("Color Space", "Input", &colorIndex, 3, forceUpdate); cvCreateTrackbar("Color Channel", "Input", &colorChannel, 3, forceUpdate); cvCreateTrackbar("Canny Aperture", "Input", &cannyAperture, 3, forceUpdate); cvCreateTrackbar("Canny Threshold1", "Input", &cannyThresh1, 300, forceUpdate); cvCreateTrackbar("Canny Threshold2", "Input", &cannyThresh2, 300, forceUpdate); cvCreateTrackbar("Line Threshold", "Input", &lineThresh, 300, forceUpdate); cvCreateTrackbar("Minimum Line Length", "Input", &minLength, 300, forceUpdate); cvCreateTrackbar("Maximum Segment Gap", "Input", &maxGap, 300, forceUpdate); //cvResizeWindow("Controls", 400, 300); bool isPaused=false; bool stepMode=false; char keyVal='p'; float milSecs=0; uint32_t frameCount=0; while(keyVal!='q'){ if(keyVal=='o'){ //Output data saveData=true; } if(keyVal=='r'){ //RESET while(!seedPoints.empty()){ delete seedPoints.back(); seedPoints.pop_back(); } updateNeeded=true; } if(keyVal=='s'){ cout<<"Enter, step mode"<<endl; cout<<"\tn - Next frame"<<endl; cout<<"\tq - Quit"<<endl; cout<<"\ts - Exit step mode"<<endl; stepMode=true; } if(keyVal=='j'){ int jump=frameCount; cout<<"Enter, jump mode @ frame="<<frameCount<<endl; cout<<"\tWhat frame to jump to? "; cin>>jump; while(frameCount < jump){ frameCount++; /*if(input!=frame && input!=NULL){ cvReleaseImage(&input); input=NULL; cout<<"Release"<<endl; }*/ frame=getFrame(capture); if(frame==NULL){ cout<<"At end of stream, read "<<frameCount<<" frames"<<endl; exit(1); } if(frameCount%10==0){ int width = frame->width; int height = frame->height; //input = frame; /*if(width > 512 || height > 512){ width = width/2; height = height/2; if(input==frame || input==NULL){ cout<<"Alloc"<<endl; input = cvCreateImage( cvSize(width, height), frame->depth, frame->nChannels ); } cvResize(frame, input); } cvShowImage("Input", input);*/ cvWaitKey(10); } //cvWaitKey(2); cout<<"frame="<<frameCount<<endl; } cout<<"Jump complete!"<<endl; } if(stepMode){ while(1){ keyVal=cvWaitKey(50); if(keyVal=='s'){ //Stop step mode stepMode=false; keyVal=0; cout<<"Exit, step mode"<<endl; break; } else if(keyVal=='q'){ //Exit program stepMode=false; cout<<"Exit program"<<endl; break; } else if(keyVal=='n'){ //Next frame cout<<"Step, frame="<<frameCount<<endl; getNewFrame=true; break; } } } if(updateNeeded || !isPaused || getNewFrame){ if(inputMedia != Photo){ if(!isPaused || getNewFrame){ frameCount++; if(input!=frame && input!=NULL){ cvReleaseImage(&input); input=NULL; } frame=getFrame(capture); if(frame==NULL){ cout<<"At end of stream, read "<<frameCount<<" frames"<<endl; break; //exit(1); } getNewFrame=false; } int width = frame->width; int height = frame->height; if(frame->width > 512 || frame->height > 512){ width = width/2; height = height/2; if(input==frame || input==NULL){ //cvReleaseImage(&input); input = cvCreateImage( cvSize(width, height), frame->depth, frame->nChannels ); } cvResize(frame, input); } else{ input=frame; } } else{ int width = original->width; int height = original->height; if(original->width > 512 || original->height > 512){ width = width/2; height = height/2; //input = cvCreateImage( cvSize(width, height), orginal->depth, orginal->nChannels ); cvResize(original, input); } else{ cvCopy(original, input); } } if(frameCount < STARTUP_DELAY){ cout<<"Starting up"<< STARTUP_DELAY-frameCount <<endl; frameCount++; } else{ //Time how long it takes to process timeval timeTemp; timeval timeDelta; gettimeofday(&timeTemp, NULL); /********* PROCESS IMAGE *******/ if(greyImg==NULL){ greyImg=cvCreateImage( cvGetSize(input), IPL_DEPTH_8U, 1 ); } if(edgeImg==NULL){ edgeImg=cvCreateImage( cvGetSize(input), IPL_DEPTH_8U, 1 ); } if(colorIndex==1){ //Normalized RGB for(int row=0; row<input->height; row++){ for(int col=0; col<input->width; col++){ float red=(uint8_t)GetPixelPtrD8(input, row, col, 0); float green=(uint8_t)GetPixelPtrD8(input, row, col, 1); float blue=(uint8_t)GetPixelPtrD8(input, row, col, 2); float sum=red+green+blue; float r=red/sum; float g=green/sum; float b=blue/sum; GetPixelPtrD8(colorSpace, row, col, 0) = (uint8_t) (r * 255); GetPixelPtrD8(colorSpace, row, col, 1) = (uint8_t) (g * 255); GetPixelPtrD8(colorSpace, row, col, 2) = (uint8_t) (b * 255); } } } else if(colorIndex==2){ //HSV cvCvtColor(input, colorSpace, CV_RGB2HSV); } else if(colorIndex==3){ //HLS cvCvtColor(input, colorSpace, CV_RGB2HLS); } else{ cvCopy(input, colorSpace); } if(colorChannel>=3){ cvCvtColor(colorSpace, greyImg, CV_RGB2GRAY); } else{ //Copy target color channel into buffer IplImage* channels[3]={NULL, NULL, NULL}; channels[colorChannel]=greyImg; cvSplit(colorSpace, channels[0], channels[1], channels[2], NULL); } CvMemStorage* storage = cvCreateMemStorage(0); CvSeq* lines = 0; cvCanny( greyImg, edgeImg, cannyThresh1, cannyThresh2, (2*cannyAperture)+1 ); clearHist(targetHist); clearHist(rejectedHist); clearHist(acceptedHist); lines = cvHoughLines2( edgeImg, storage, CV_HOUGH_PROBABILISTIC, 1, CV_PI/180, lineThresh+1, minLength, maxGap ); //Delete old points while(!seedPoints.empty()){ delete seedPoints.back(); seedPoints.pop_back(); } for(int row=colorSpace->height/2; row<colorSpace->height; row+=10){ for(int col=0; col < colorSpace->width; col+=10){ CvPoint* pt=new CvPoint; pt->x=col; pt->y=row; seedPoints.push_back(pt); } } PixelStats stats; calcStats(colorSpace, seedPoints, &stats); vector<CvPoint*>::iterator iter=seedPoints.begin(); while(iter!=seedPoints.end()){ CvPoint* pt=*iter; double chan0Delta=fabs(((uint8_t)GetPixelPtrD8(colorSpace, pt->y, pt->x, 0)) - stats.avgVal.val[0]); double chan1Delta=fabs(((uint8_t)GetPixelPtrD8(colorSpace, pt->y, pt->x, 1)) - stats.avgVal.val[1]); double chan2Delta=fabs(((uint8_t)GetPixelPtrD8(colorSpace, pt->y, pt->x, 2)) - stats.avgVal.val[2]); if(chan0Delta > stats.stdDev.val[0]*1 /*|| chan1Delta > stats.stdDev.val[1]*1.5 || chan2Delta > stats.stdDev.val[2]*1.5*/){ delete (*iter); iter=seedPoints.erase(iter); continue; } iter++; } //PixelStats stats; calcStats(colorSpace, seedPoints, &stats); int removed=0; int total=lines->total; totalChecked+=total; for(int i=0; i<lines->total; i++){ CvPoint* line = (CvPoint*)cvGetSeqElem(lines,i); float slope=(float)(line[0].y - line[1].y)/(float)(line[0].x - line[1].x); /*if(line[0].y < 50 || line[1].y<50){ removed++; continue; } if(fabsf(slope-1) < 0.1){ removed++; continue; }*/ CvLineIterator iterator; int count=cvInitLineIterator( colorSpace, line[0], line[1], &iterator, 8, 0 ); CvScalar avgVal=cvScalarAll(0); CvScalar delta=cvScalarAll(0); CvScalar variance=cvScalarAll(0); CvScalar stdDev=cvScalarAll(0); clearHist(tempHist); for(int p=0; p<count; p++){ //Loop over pixels in line tempHist[iterator.ptr[0]][0]++; tempHist[iterator.ptr[1]][1]++; tempHist[iterator.ptr[2]][2]++; avgVal.val[0]+=iterator.ptr[0]; avgVal.val[1]+=iterator.ptr[1]; avgVal.val[2]+=iterator.ptr[2]; CV_NEXT_LINE_POINT(iterator); } avgVal.val[0]=avgVal.val[0]/count; avgVal.val[1]=avgVal.val[1]/count; avgVal.val[2]=avgVal.val[2]/count; count=cvInitLineIterator( colorSpace, line[0], line[1], &iterator, 8, 0 ); for(int p=0; p<count; p++){ //Loop over pixels in line variance.val[0]+=(iterator.ptr[0]-avgVal.val[0])*(iterator.ptr[0]-avgVal.val[0]); variance.val[1]+=(iterator.ptr[1]-avgVal.val[1])*(iterator.ptr[1]-avgVal.val[1]); variance.val[2]+=(iterator.ptr[2]-avgVal.val[2])*(iterator.ptr[2]-avgVal.val[2]); CV_NEXT_LINE_POINT(iterator); } variance.val[0]/=count; variance.val[1]/=count; variance.val[2]/=count; delta.val[0]=fabs(avgVal.val[0]-stats.avgVal.val[0]); delta.val[1]=fabs(avgVal.val[1]-stats.avgVal.val[1]); delta.val[2]=fabs(avgVal.val[2]-stats.avgVal.val[2]); stdDev.val[0]=sqrt(variance.val[0]); stdDev.val[1]=sqrt(variance.val[1]); stdDev.val[2]=sqrt(variance.val[2]); //cout<<"line m="<<slope<<" stdDev="<<cvScalarToString(stdDev, 3)<<", avg="<<cvScalarToString(avgVal, 3); if(delta.val[0] < 10*stats.stdDev.val[0] && delta.val[1] < 2*stats.stdDev.val[1] && delta.val[2] < 4*stats.stdDev.val[2]){ cout<<" REMOVED deltaAvg="<<cvScalarToString(delta,3)<<" stdDev="<<cvScalarToString(stdDev,3)<<endl; removed++; cvLine( input, line[0], line[1], CV_RGB(255,0,0), 1); stageRemoved[0]++; addHist(tempHist, rejectedHist, rejectedHist); continue; } //Dark grass Checking for HSV if(avgVal.val[0] > stats.avgVal.val[0]){ cout<<" REMOVED chan0 AVG deltaAvg="<<cvScalarToString(delta,3)<<" stdDev="<<cvScalarToString(stdDev,3)<<endl; removed++; cvLine( input, line[0], line[1], CV_RGB(255,255,0), 1); stageRemoved[1]++; addHist(tempHist, rejectedHist, rejectedHist); continue; } else if(avgVal.val[1] > stats.avgVal.val[1]){ cout<<" REMOVED chan1 AVG deltaAvg="<<cvScalarToString(delta,3)<<" stdDev="<<cvScalarToString(stdDev,3)<<endl; removed++; cvLine( input, line[0], line[1], CV_RGB(0,127,127), 1); stageRemoved[2]++; addHist(tempHist, rejectedHist, rejectedHist); continue; } else if(avgVal.val[2] > 200){ //cout<<" REMOVED chan2 AVG deltaAvg="<<cvScalarToString(delta,3)<<" stdDev="<<cvScalarToString(stdDev,3)<<endl; //removed++; //cvLine( input, line[0], line[1], CV_RGB(255,157,0), 1); //continue; } if(15*stats.stdDev.val[0] < stdDev.val[0]){ cout<<" REMOVED hue deltaAvg="<<cvScalarToString(delta,3)<<" stdDev="<<cvScalarToString(stdDev,3)<<endl; removed++; cvLine( input, line[0], line[1], CV_RGB(255,83,83), 1); stageRemoved[3]++; addHist(tempHist, rejectedHist, rejectedHist); continue; } cout<<"Keeping deltaAvg="<<cvScalarToString(delta,3)<<" stdDev="<<cvScalarToString(stdDev,3)<<endl; cvLine( input, line[0], line[1], CV_RGB(0, 255, 0), 1); addHist(tempHist, acceptedHist, acceptedHist); } if(saveData==true){ dataFile1.open("targetHist.dat", ios_base::trunc); dataFile2.open("acceptedHist.dat", ios_base::trunc); dataFile3.open("rejectedHist.dat", ios_base::trunc); cout<<"Writing Data to file..."<<endl; for(int j=0; j<256; j++){ dataFile1<<targetHist[j][0]<<" "<<targetHist[j][1]<<" "<<targetHist[j][2]<<endl; dataFile2<<acceptedHist[j][0]<<" "<<acceptedHist[j][1]<<" "<<acceptedHist[j][2]<<endl; dataFile3<<rejectedHist[j][0]<<" "<<rejectedHist[j][1]<<" "<<rejectedHist[j][2]<<endl; } cout<<"Writing complete"<<endl; dataFile1.close(); dataFile2.close(); dataFile3.close(); saveData=false; isPaused=true; } totalAccepted+=total-removed; cvReleaseMemStorage(&storage); /********* END PROCESSING *******/ gettimeofday(&timeDelta, NULL); timeDelta.tv_sec-=timeTemp.tv_sec; timeDelta.tv_usec-=timeTemp.tv_usec; milSecs=((float)timeDelta.tv_sec)*1000 + ((float)timeDelta.tv_usec)/1000; for(int i=0; i<seedPoints.size(); i++){ CvPoint* pt=seedPoints.at(i); cvCircle(input, *pt, 2, cvScalar(0,0,255), 1); } cout<<"\tAvg="<<cvScalarToString(stats.avgVal,3)<<endl; cout<<"\tVariance="<<cvScalarToString(stats.variance,3)<<endl; cout<<"\tStdDev="<<cvScalarToString(stats.stdDev,3)<<endl; cout<<"Found "<<total<<" lines and removed "<<removed<<" lines"; cout<<" - Processed frame in "<<milSecs<<"ms."<<endl; } cvShowImage("Input", input); cvShowImage("ColorSpace", colorSpace); cvShowImage("Grey", greyImg); cvShowImage("Lines", edgeImg); updateNeeded=false; } if(keyVal=='p'){ isPaused=!isPaused; if(isPaused){ cout<<"Paused @ frame="<<frameCount<<endl; } else{ cout<<"Unpaused"<<endl; } } if(keyVal=='q'){ break; } keyVal=cvWaitKey(10); }
int pkmGaussianMixtureModel::writeToFile(ofstream &fileStream, bool writeClusterNums, bool writeWeights, bool writeMeans, bool writeCovs, bool verbose) { if(!fileStream.is_open()) return -1; // use the best-model CvEM myModel = emModel[bestModel]; const CvMat **modelCovs = myModel.get_covs(); const CvMat *modelMus = myModel.get_means(); const CvMat *modelWeights = myModel.get_weights(); int numClusters = myModel.get_nclusters(); // output the total number of clusters if(writeClusterNums) { if(verbose) fileStream << "Number of Clusters: " << numClusters << "\n"; else fileStream << numClusters << "\n"; } if(writeWeights) { // output the weights of each cluster if(verbose) fileStream << "Weight of Clusters\n"; for (int k = 0; k < numClusters; k++) { const double *weightPtr = (const double *)(modelWeights->data.ptr + k*modelWeights->step); double weight = weightPtr[0]; if(verbose) fileStream << k << ": " << weight << "\n"; else fileStream << weight << " "; } fileStream << "\n"; } if(writeMeans) { // output the means of each cluster if(verbose) fileStream << "Means of Clusters\n"; for (int k = 0; k < numClusters; k++) { if(verbose) fileStream << "Cluster " << k << ":\n"; for (int i = 0; i < m_nVariables; i++) { if(verbose) fileStream << i << ": " << cvmGet(modelMus, k, i) << " "; else fileStream << cvmGet(modelMus, k, i) << " "; } fileStream << "\n"; } } if(writeCovs) { // output the covariances of each cluster if(verbose) fileStream << "Covariances of Clusters\n"; for (int k = 0; k < numClusters; k++) { const CvMat * covar = modelCovs[k]; if(verbose) fileStream << "Cluster " << k << ":\n"; for (int i = 0; i < m_nVariables; i++) { for (int j = 0; j < m_nVariables; j++) { if(verbose) fileStream << i << "," << j << ": " << cvmGet(covar, i, j) << " "; else fileStream << cvmGet(covar, i, j) << " "; } } fileStream << "\n"; } } return 0; }
VOID stride_instr_interval_output(){ int i; UINT64 cum; output_file_stride.open("stride_phases_int_pin.out", ios::out|ios::app); output_file_stride << numReadInstrsAnalyzed; /* local read distribution */ cum = 0; for(i = 0; i < MAX_DISTR; i++){ cum += localReadDistrib[i]; if( (i == 0) || (i == 8) || (i == 64) || (i == 512) || (i == 4096) || (i == 32768) || (i == 262144) ){ if(cum > 0) output_file_stride << " " << cum; else output_file_stride << " 0"; } if(i == 262144) break; } /* global read distribution */ cum = 0; for(i = 0; i < MAX_DISTR; i++){ cum += globalReadDistrib[i]; if( (i == 0) || (i == 8) || (i == 64) || (i == 512) || (i == 4096) || (i == 32768) || (i == 262144) ){ if(cum > 0) output_file_stride << " " << cum; else output_file_stride << " 0"; } if(i == 262144) break; } output_file_stride << " " << numWriteInstrsAnalyzed; /* local write distribution */ cum = 0; for(i = 0; i < MAX_DISTR; i++){ cum += localWriteDistrib[i]; if( (i == 0) || (i == 8) || (i == 64) || (i == 512) || (i == 4096) || (i == 32768) || (i == 262144) ){ if(cum > 0) output_file_stride << " " << cum; else output_file_stride << " 0"; } if(i == 262144) break; } /* global write distribution */ cum = 0; for(i = 0; i < MAX_DISTR; i++){ cum += globalWriteDistrib[i]; if( (i == 0) || (i == 8) || (i == 64) || (i == 512) || (i == 4096) || (i == 32768) ){ if(cum > 0) output_file_stride << " " << cum; else output_file_stride << " 0"; } if(i == 262144){ if(cum > 0) output_file_stride << " " << cum << endl; else output_file_stride << " 0" << endl; break; } } output_file_stride.close(); }
void closeStreams(ifstream & fin_par, ofstream & fout_par) { fin_par.close(); fout_par.close(); }
/* initializing */ void init_stride(){ int i; /* initializing total instruction counts is done in mica.cpp */ /* initial sizes */ numRead = 1024; numWrite = 1024; /* allocate memory */ if ((instrRead = (ADDRINT*) malloc (numRead * sizeof (ADDRINT))) == (ADDRINT*) NULL) { cerr << "Not enough memory (in main (2))" << endl; exit (0); } //cerr << "malloc " << numRead*sizeof(ADDRINT) << "bytes" << endl; if ((instrWrite = (ADDRINT*) malloc (numWrite * sizeof (ADDRINT))) == (ADDRINT*) NULL) { cerr << "Not enough memory (in main (3))" << endl; exit (0); } //cerr << "malloc " << numWrite*sizeof(ADDRINT) << "bytes" << endl; /* initialize */ readIndex = 1; writeIndex = 1; for (i = 0; i < (int)numRead; i++) instrRead[i] = 0; for (i = 0; i < (int)numWrite; i++) instrWrite[i] = 0; lastReadAddr = 0; lastWriteAddr = 0; for (i = 0; i < MAX_DISTR; i++) { localReadDistrib[i] = 0; localWriteDistrib[i] = 0; globalReadDistrib[i] = 0; globalWriteDistrib[i] = 0; } numInstrsAnalyzed = 0; numReadInstrsAnalyzed = 0; numWriteInstrsAnalyzed = 0; indices_memRead_size = 1024; if( (indices_memRead = (ADDRINT*) malloc(indices_memRead_size*sizeof(ADDRINT))) == (ADDRINT*)NULL){ cerr << "Could not allocate memory for indices_memRead" << endl; exit(1); } for (i = 0; i < (int)indices_memRead_size; i++) indices_memRead[i] = 0; indices_memWrite_size = 1024; if( (indices_memWrite = (ADDRINT*) malloc(indices_memWrite_size*sizeof(ADDRINT))) == (ADDRINT*)NULL){ cerr << "Could not allocate memory for indices_memWrite" << endl; exit(1); } for (i = 0; i < (int)indices_memWrite_size; i++) indices_memWrite[i] = 0; if(interval_size != -1){ output_file_stride.open("stride_phases_int_pin.out", ios::out|ios::trunc); output_file_stride.close(); } }
int main(int argc, char ** argv) { int graf[VERTICES * VERTICES] = { 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0 }; MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &worldSize); file << "After init\n"; stack = new LinkedStack<Kostra > (); uzly = new Uzel[VERTICES]; for (int i = 0; i < VERTICES; i++) { for (int j = 0; j < VERTICES; j++) { if (graf[i * VERTICES + j] == 1) { uzly[i].hrany.push_back(uzly[j]); } } } string txt = "process"; txt.append(convertInt(rank)); txt.append(".txt"); file.open(txt.c_str()); file << txt; // if (rank == 0) { // predist pytaniu sameho seba reqRank++; // uvodny uzel do stack vector<Uzel> kostra; kostra.push_back(uzly[6]); Kostra * k = new Kostra(kostra); stack->add(k); } // TEST // Kostra * next = stack->next(); // next = stack->next(); // next = stack->next(); // stack->next(); // stack->next(); // stack->next(); // stack->next(); // stack->next(); // stack->next(); // stack->next(); // stack->next(); // stack->next(); // stack->next(); // stack->next(); // stack->next(); // stack->next(); // stack->next(); // // stack->print(); token = (rank == 0) ? 1 : 0; MPI_Barrier(MPI_COMM_WORLD); file << "Process " << rank << " : Starting cycle\n"; mainCycle(); file << "Process " << rank << ": Ukoncen???"; // MPI_Finalize(); // file.close(); // return 0; //} // /////TEST // int * rmsg = 0; // file << "Rank: " << rank << " Size: " << worldSize << "\n"; // file << "Before recieving Msg: " << *rmsg << "\n"; // // MPI_Send(&graf, 4, MPI_INT, 0, 1, MPI_COMM_WORLD); // MPI_Recv(&rmsg, 4, MPI_INT, 0, 1, MPI_COMM_WORLD, &status); // // file << "Recieved Msg: " << *rmsg; // // uzly = new Uzel[8]; // // for (int i = 0; i < 8; i++) { // for (int j = 0; j < 8; j++) { // if (graf[i * 8 + j] == 1) { // uzly[i].hrany.push_back(uzly[j]); // } // } // } // vector<Uzel> kostra; // kostra.push_back(uzly[6]); // Kostra * k = new Kostra(kostra); // // // k->toString(); // //test stack // stack = new LinkedStack<Kostra > (); // stack->divide(); // stack->divide(); // Kostra * first = stack->front->k; // Kostra * next = stack->next(); // // file << "\nSize of linked Stack: " << stack->size; // stack->print(); // // // Node * x = new Node(k); // stack->add(k); // stack->back->k->toString(); // // file << "\nSize of linked Stack: " << stack->size; // // // kostra.push_back(uzly[5]); // file << "\n------Next of Front then Front----------------\n"; // Node<Kostra> * temp = stack->front; // k = temp->k->next(); // // // x = new Node(k); // file << "\n------Front then add----------------\n"; // stack->add(k); // // file << "\n------Prev of Back and Back----------------\n"; // // // temp = stack->front; // temp->k->toString(); // k = temp->k->next(); // // stack->add(k); // temp = stack->front; // temp->k->toString(); // k = temp->k->next(); // stack->add(k); // // temp = stack->front; // temp->k->toString(); // k = temp->k->next(); // stack->add(k); // // temp = stack->front; // temp->k->toString(); // k = temp->k->next(); // stack->add(k); // // temp = stack->front; // temp->k->toString(); // k = temp->k->next(); // stack->add(k); // // file << "\n------Komplet Stack Before split----------------\n"; // stack->print(); // Node<Kostra> * n = stack->front; // while (n != NULL) { // n->k->toString(); // n = n->next; // } // // // // // LinkedStack<Kostra> * second = stack->divide(); // // // file << "\n------Komplet Stack after Split----------------\n"; // n = stack->front; // while (n != NULL) { // n->k->toString(); // n = n->next; // } // // // file << "\n------Komplet Second after Split----------------\n"; // n = second->front; // while (n != NULL) { // n->k->toString(); // n = n->next; // } // // // // // Transfer * t = new Transfer(stack->divide()); // // Transfer t(second); // t.print(); // file << "\n------SEND MPI----------------\n"; // MPI_Send(t.transfer, t.size, MPI_SHORT, 0, 0, MPI_COMM_WORLD); // // // // // int testTransferSize; // int flag; // MPI_Iprobe(0, MPI_ANY_SOURCE, MPI_COMM_WORLD, &flag, &status); // MPI_Get_count(&status, MPI_SHORT, &testTransferSize); // // // file << "\nTransfer Size: " << testTransferSize << "\n"; // // short * testTransfer = new short[testTransferSize]; // Transfer* newTransfer = new Transfer(testTransferSize); // MPI_Recv(newTransfer->transfer, testTransferSize, MPI_SHORT, MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status); // delete second; // // // // // // file << "\n------TransferedStack----------------\n"; // LinkedStack<Kostra> * trasferedStack = newTransfer->unpack(); // n = trasferedStack->front; // while (n != NULL) { // n->k->toString(); // n = n->next; // } // stack->add(trasferedStack); //// // file << "\n------Komplet stack after merge----------------\n"; // n = stack->front; // while (n != NULL) { // n->k->toString(); // n = n->next; // } // // // // // temp = stack->front; // // k = temp->k->next(); // // stack->add(k); // // // // file << "\nSize of linked Stack: " << stack->size << "\n"; // // // // // // // test stack children // // // // stack->front->k.toString(); // // // // MPI_Finalize(); // return 0; // // // // // // 1 2 3 4 5 6 7 8 // // // // // // vector<Uzel> kostra; // // deque<Kostra> fulls; // // kostra.push_back(uzly[6]); // // Kostra k(kostra, uzly); // // // // stack->push_front(k); // // int x = 0; // // while (!stack->empty()) { // // if (next->isFull()) { // // fulls.push_front(*next); // // } else { // // stack->push_back(*next); // // } // // x++; // // } // // // // file << "Stack\n"; // // for (deque<Kostra>::iterator i = stack->begin(); i != stack->end(); i++) { // // i->toString(); // // } // // // // file << "Fulls\n"; // // // for (deque<Kostra>::iterator it = fulls.begin(); it != fulls.end(); it++) { // // //// it->toString(); // // //// file << "7\n" << it->output; // // // // // // } // // deque<Kostra>::iterator it = fulls.end(); // // it--; // // it--; // // file << "7\n" << it->output; // // // //} // // file << "TEST ANYSEK\n"; // // stack->add(k); // Node<Kostra> * temp = stack->front; // file << "\n\n-----Adresa" << stack->front << "\n\n"; // stack->next(); // stack->next(); // stack->next(); // stack->next(); // stack->next(); // stack->next(); // stack->next(); // stack->print(); // stack->popFront(); // //// file << "\n\n\n\nTEST ANYSEK\n"; ////// file << "\n\n-----Pocet Deti: " << temp->id << "\n\n"; //// stack->print(); //// Node<Kostra> * t = new Node(k); //// delete(); //// k->toString(); // stack->print(); // // MPI_Finalize(); return 0; }
// Image load callback - inserts the probes. void ImgLoad(IMG img, void *v) { // Called every time a new image is loaded if ( (IMG_Name(img).find("libdl.so") != string::npos) || (IMG_Name(img).find("LIBDL.SO") != string::npos) || (IMG_Name(img).find("LIBDL.so") != string::npos) ) { RTN rtndlclose = RTN_FindByName(img, "dlclose"); if (RTN_Valid(rtndlclose) && RTN_IsSafeForProbedReplacement(rtndlclose)) { OutFile << CurrentTime() << "Inserting probe for dlclose at " << RTN_Address(rtndlclose) << endl; OutFile.flush(); AFUNPTR fptr = (RTN_ReplaceProbed(rtndlclose, AFUNPTR(mydlclose))); fptrdlclose = (int (*)(VOID_PTR ))fptr; } RTN rtndlopen = RTN_FindByName(img, "dlopen"); if (RTN_Valid(rtndlopen) && RTN_IsSafeForProbedReplacement(rtndlopen)) { OutFile << CurrentTime() << "Inserting probe for dlopen at " << RTN_Address(rtndlopen) << endl; OutFile.flush(); AFUNPTR fptr = (RTN_ReplaceProbed(rtndlopen, AFUNPTR(mydlopen))); fptrdlopen = (VOID_PTR (*)(__const CHAR_PTR , int ))fptr; } RTN rtndlsym = RTN_FindByName(img, "dlsym"); if (RTN_Valid(rtndlsym) && RTN_IsSafeForProbedReplacement(rtndlsym)) { OutFile << CurrentTime() << "Inserting probe for dlsym at " << RTN_Address(rtndlsym) << endl; OutFile.flush(); AFUNPTR fptr = (RTN_ReplaceProbed(rtndlsym, AFUNPTR(mydlsym))); fptrdlsym = (VOID_PTR (*)(VOID_PTR, __const CHAR_PTR ))fptr; } RTN rtndlvsym = RTN_FindByName(img, "dlvsym"); if (RTN_Valid(rtndlvsym) && RTN_IsSafeForProbedReplacement(rtndlvsym)) { OutFile << CurrentTime() << "Inserting probe for dlvsym at " << RTN_Address(rtndlvsym) << endl; OutFile.flush(); AFUNPTR fptr = (RTN_ReplaceProbed(rtndlvsym, AFUNPTR(mydlvsym))); fptrdlvsym = (VOID_PTR (*)(VOID_PTR, __const CHAR_PTR, __const CHAR_PTR))fptr; } RTN rtndladdr = RTN_FindByName(img, "dladdr"); if (RTN_Valid(rtndladdr) && RTN_IsSafeForProbedReplacement(rtndladdr)) { OutFile << CurrentTime() << "Inserting probe for dladdr at " << RTN_Address(rtndladdr) << endl; OutFile.flush(); AFUNPTR fptr = (RTN_ReplaceProbed(rtndladdr, AFUNPTR(mydladdr))); fptrdladdr = (int (*)(__const void * , Dl_info * ))fptr; } RTN rtndladdr1 = RTN_FindByName(img, "dladdr1"); if (RTN_Valid(rtndladdr) && RTN_IsSafeForProbedReplacement(rtndladdr1)) { OutFile << CurrentTime() << "Inserting probe for dladdr1 at " << RTN_Address(rtndladdr1) << endl; OutFile.flush(); AFUNPTR fptr = (RTN_ReplaceProbed(rtndladdr, AFUNPTR(mydladdr1))); fptrdladdr1 = (int (*)(__const void * , Dl_info *, void **, int ))fptr; } RTN rtndlerror = RTN_FindByName(img, "dlerror"); if (RTN_Valid(rtndlerror) && RTN_IsSafeForProbedReplacement(rtndlerror)) { OutFile << CurrentTime() << "Inserting probe for dlerror at " << RTN_Address(rtndlerror) << endl; OutFile.flush(); AFUNPTR fptr = (RTN_ReplaceProbed(rtndlerror, AFUNPTR(mydlerror))); fptrdlerror = (CHAR_PTR (*)(void ))fptr; } } // finished instrumentation }
int main (int argc, char **argv) { options ( argc, argv ); map <string,string> confMap; if ( dgas_conf_read ( confFileName, &confMap ) != 0 ) { cerr << "Can't Open Configuration file: " << confFileName << endl; help(argv[0]); exit(1); } notfor2lHlr(confMap["is2ndLevelHlr"]); hlr_sql_server = (confMap["hlr_sql_server"]).c_str(); hlr_sql_user = (confMap["hlr_sql_user"]).c_str(); hlr_sql_password = (confMap["hlr_sql_password"]).c_str(); hlr_sql_dbname = (confMap["hlr_sql_dbname"]).c_str(); hlr_logFileName = (confMap["hlr_def_log"]).c_str(); if (needs_help) { help(argv[0]); return 0; } logStream.open( hlr_logFileName.c_str() , ios::app); hlrResource r; r.rid = rid_buff; r.email = email_buff; r.descr = descr_buff; r.ceId = ce_id_buff; //it is right! hlrResource class has certSubject there!, need to be FIXED in the future, and the class member changhed to ceId r.gid = gid_buff; r.acl = certSubject_buff; if ( r.rid == "" || r.ceId == "" || r.acl == "" || r.gid == "" ) { cerr << "Resource rid, gid, ceId and CE host CertSubject are mandatory parameters." << endl; help(argv[0]); logStream.close(); return 1; } else { hlrResource resourceBuff; resourceBuff.ceId = r.ceId; if ( !force && resourceBuff.get() == 0 ) { cerr << "A resource whit this Grid CE Id already exists, it is not possible to create the account!" << endl; cerr << resourceBuff << endl; return 3; } else { if ( force ) { cerr << "Warning! --Force specified, Overwriting!" << endl; } } if ( force || !r.exists() ) { if (debug) cout << "Adding resource..."; int res = r.put(); if ( res == 0 ) { cout << "Resource added!" << endl; } else { cout << "error adding resource!" << endl; cout << "Exit code:" << res << endl; } logStream.close(); return res; } else { cerr << "Error: This resource already exists in the database!" << endl; if ( debug ) { r.get(); cerr << r << endl; } logStream.close(); return 1; } } }
bool nNFileWriter::writeInstance(ofstream &file, nMeshInstance *dp) { if(!dp) { nGine::instance()->getLogger()->addDebugLog("Unable to write... nothings"); return true; } dp->CPUload(); uint64_t flags = 0; if(dp->getCoords(0).x != n::inf()) flags++; flags = flags<<1; if(!dp->getNormal(0).isNull()) flags++; //flags = flags<<1; file.write((const char*)&flags, 8); uint32_t count = dp->getVertexCount(); uint32_t tCount = dp->getTriangleCount(); uint32_t mCount = dp->getMaterialCount(); file.write((const char*)&count, 4); file.write((const char*)&tCount, 4); file.write((const char*)&mCount, 4); nGine::instance()->getLogger()->addDebugLog(nLogger::numToString((int)count) + " vertices, " + nLogger::numToString((int)tCount) + " triangles, " + nLogger::numToString((int)mCount) + " materials to write"); for(unsigned int i = 0; i != mCount; i++) { float nid = (float)((uint16_t)-1); nMaterial *mat = dp->getMaterial(i); char shininess = mat->getShininess(); uint16_t blend = mat->getBlendFactor() * (double)nid; file.write((char*)&shininess, 1); file.write((char*)&blend, 2); float dat[] = {mat->getDiffuseColor().x, mat->getDiffuseColor().y, mat->getDiffuseColor().z, mat->getAmbientColor().x, mat->getAmbientColor().y, mat->getAmbientColor().z, mat->getSpecularColor().x, mat->getSpecularColor().y, mat->getSpecularColor().z}; for(unsigned int j = 0; j != 9; j++) { uint16_t d = (uint16_t)(dat[j] * nid); file.write((const char*)&d, 2); } for(unsigned int j = 0; j != 4; j++) if(!mat->getTexture((nMaterial::nTextureRole)j)) file.write("\0", 1); else { string tName = mat->getTexture((nMaterial::nTextureRole)j)->getName(); if(tName.length() > nGine::instance()->appPath().length() && tName.substr(0, nGine::instance()->appPath().length()) == nGine::instance()->appPath()) tName = tName.substr(nGine::instance()->appPath().length()); if(tName.length() > nGine::instance()->getRessourcesManager()->getTextureManager()->getTextureDir().length() && tName.substr(0, nGine::instance()->getRessourcesManager()->getTextureManager()->getTextureDir().length()) == nGine::instance()->getRessourcesManager()->getTextureManager()->getTextureDir()) tName = tName.substr(nGine::instance()->getRessourcesManager()->getTextureManager()->getTextureDir().length()); char l = tName.length(); file.write(&l, 1); file<<tName; } } for(unsigned int i = 0; i != count; i++) { float X = dp->getPosition(i).x; float Y = dp->getPosition(i).y; float Z = dp->getPosition(i).z; uint32_t *x = (uint32_t*)&X; uint32_t *y = (uint32_t*)&Y; uint32_t *z = (uint32_t*)&Z; file.write((const char*)x, 4); file.write((const char*)y, 4); file.write((const char*)z, 4); } if(!dp->getNormal(0).isNull()) for(unsigned int i = 0; i != count; i++) { float X = dp->getNormal(i).x; float Y = dp->getNormal(i).y; float Z = dp->getNormal(i).z; uint32_t *x = (uint32_t*)&X; uint32_t *y = (uint32_t*)&Y; uint32_t *z = (uint32_t*)&Z; file.write((const char*)x, 4); file.write((const char*)y, 4); file.write((const char*)z, 4); } if(dp->getCoords(0).x != n::inf()) for(unsigned int i = 0; i != count; i++) { float U = dp->getCoords(i).x; float V = dp->getCoords(i).y; uint32_t *u = (uint32_t*)&U; uint32_t *v = (uint32_t*)&V; file.write((const char*)u, 4); file.write((const char*)v, 4); } nMaterial *mat = 0; uint32_t nid = (uint32_t)-1; for(unsigned int i = 0; i != tCount; i++) { if(dp->getTriangle(i).material != mat) { mat = dp->getTriangle(i).material; file.write((const char*)&nid , 4); uint32_t index = 0; for(unsigned int j = 0; j != dp->getMaterialCount(); j++) if(dp->getMaterial(j) == mat) { index = j + 1; break; } file.write((const char*)&index , 2); } for(unsigned int j = 0; j != 3; j++) { uint32_t index = dp->getIndexedTriangle(i).v[j]; file.write((const char*)&index , 4); } } return true; }
extern "C" number HighResTime(){ #ifdef __LVL3ONLY__ float ar[2]; float ltime=0; static number ETimeLast; static timeval TPSLast; static struct timezone TZ; static timeval TPS; static integer init=0; const number TRes=0.02; if(init++ ==0){ gettimeofday(&TPSLast,&TZ); ETimeLast=ETIMEU(ar); } geant time=ETIMEU(ar); if(time -ETimeLast > TRes){ gettimeofday(&TPSLast,&TZ); ETimeLast=time; return time; } else { // // Try to get more high res // gettimeofday(&TPS,&TZ); ltime=number(TPS.tv_sec-TPSLast.tv_sec)+1.e-6*(TPS.tv_usec-TPSLast.tv_usec); TPSLast.tv_sec=TPS.tv_sec; TPSLast.tv_usec=TPS.tv_usec; if(ltime<= TRes )ETimeLast+=ltime; else ETimeLast=time; return ETimeLast; } #else #ifdef sun hrtime_t nsec=gethrtime(); return double(nsec)*1e-9; #else #ifdef _PGTRACK_ return AMSgettime(); #else static unsigned int count=0; float ltime=0; #pragma omp threadprivate (count) TIMEX(ltime); // if(!AMSCommonsI::remote()){ // ltime=ETIMEU(ar); // count++; // } // else if((count++)%128==0){ // // clock_t clicks = clock(); // // ltime=( (float) clicks / CLOCKS_PER_SEC ); // ltime=ETIMEU(ar); // } if(0 && (count)%2048==0 ){ ifstream fbin; fbin.open("/proc/self/where"); if(fbin){ int node=-1; fbin>>node; if(node!=0){ if(!AMSCommonsI::remote())cout <<"AMSTimeID::validate-I-Remote Client Detected "<<endl; AMSCommonsI::setremote(true); } else{ if(AMSCommonsI::remote())cout <<"AMSTimeID::validate-I-Local Client Detected "<<endl; AMSCommonsI::setremote(false); } } else{
VOID Fini(INT32 code, VOID *v) { TraceFile.close(); }
int main(int argc, char *argv[]) { char f[500], f2[500], f3[500], f4[500], f5[500], f6[500], f7[500], f8[500]; ostrstream fname(f, 500, ios::out); ostrstream fname2(f2, 500, ios::out); ostrstream fname3(f3, 500, ios::out); ostrstream fname4(f4, 500, ios::out); ostrstream fname5(f5, 500, ios::out); ostrstream fname6(f6, 500, ios::out); ostrstream fname7(f7, 500, ios::out); ostrstream fname8(f8, 500, ios::out); char mname[500]; if(argc != 6) { cerr << "Usage: " << argv[0] << " [max_generations] [mutation_percent] [agreement_threshold]" << " [crossover_percent] [self-test_threshold]" << endl; cerr << "Defaults: max_gen=" << MAX_ROUNDS << " self-test=" << BAD_THRESHOLD << " agree=" << TRAIN_AGREE << " xover=" << PR_XOVER << " mutate=" << PR_MUTATION << endl; } if(argc > 1) MAX_ROUNDS = atoi(argv[1]); if(argc > 2) PR_MUTATION = atof(argv[2]); if(argc > 3) TRAIN_AGREE = atoi(argv[3]); if(argc > 4) PR_XOVER = atof(argv[4]); if(argc > 5) BAD_THRESHOLD = atof(argv[5]); cout << "Vars: " << MAX_ROUNDS << " " << PR_MUTATION << endl; float classAccuracy[MAX_RUNS][MAX_ROUNDS][CLASS_COUNT]; float averageAccuracy[MAX_ROUNDS][CLASS_COUNT]; float bestAccuracy[MAX_ROUNDS][CLASS_COUNT]; for(int i = 0; i < MAX_ROUNDS; i++) { for(int j = 0; j < CLASS_COUNT; j++) { averageAccuracy[i][j] = 0; bestAccuracy[i][j] = 0; } } attack.setThreshold(TRAIN_AGREE); normal.setThreshold(TRAIN_AGREE); unknown.setThreshold((TRAIN_AGREE*2)); logNeg = 0; sprintf(mname, "res/unknown.%d_%d_%f_%f", MAX_ANTIBODIES, MAX_ROUNDS, PR_XOVER, PR_MUTATION); mystery.open(mname); fname << "res/fitness." << MAX_ANTIBODIES << "_" << MAX_ROUNDS << "_" << PR_XOVER << "_" << PR_MUTATION << ends; fout.open(f); cout << f << endl; fname2 << "res/details." << MAX_ANTIBODIES << "_" << MAX_ROUNDS << "_" << PR_XOVER << "_" << PR_MUTATION << ends; fout2.open(f2); #ifdef VERBOSE_OUTPUT fname3 << "res/full." << MAX_ANTIBODIES << "_" << MAX_ROUNDS << "_" << PR_XOVER << "_" << PR_MUTATION << ends; fout3.open(f3); #endif fname4 << "res/bad." << MAX_ANTIBODIES << "_" << MAX_ROUNDS << "_" << PR_XOVER << "_" << PR_MUTATION << ends; fout4.open(f4); fname5 << "res/false_pos." << MAX_ANTIBODIES << "_" << MAX_ROUNDS << "_" << PR_XOVER << "_" << PR_MUTATION << ends; fout5.open(f5); fname6 << "res/false_neg." << MAX_ANTIBODIES << "_" << MAX_ROUNDS << "_" << PR_XOVER << "_" << PR_MUTATION << ends; fout6.open(f6); fname7 << "res/classifications." << MAX_ANTIBODIES << "_"<< MAX_ROUNDS << "_" << PR_XOVER << "_" << PR_MUTATION << ends; fout7.open(f7); fname8 << "res/missed." << MAX_ANTIBODIES << "_"<< MAX_ROUNDS << "_" << PR_XOVER << "_" << PR_MUTATION << ends; fout8.open(f8); #ifdef VERBOSE_OUTPUT fout3 << "#Parameters: MAX_ROUNDS = " << MAX_ROUNDS << " MAX_ANTIBODIES = " << MAX_ANTIBODIES << endl << "# PR_XOVER = " << PR_XOVER << " PR_MUTATION = " << PR_MUTATION << endl << "# BAD_THRESHOLD = " << BAD_THRESHOLD << " TRAIN_AGREE = " << TRAIN_AGREE << endl; #endif fout << "#Parameters: MAX_ROUNDS = " << MAX_ROUNDS << " MAX_ANTIBODIES = " << MAX_ANTIBODIES << endl << "# PR_XOVER = " << PR_XOVER << " PR_MUTATION = " << PR_MUTATION << endl << "# BAD_THRESHOLD = " << BAD_THRESHOLD << " TRAIN_AGREE = " << TRAIN_AGREE << endl; for(int i = 0; i < CLASS_COUNT; i++) { for(int j = 0; j < MAX_ANTIBODIES; j++) { pop[i][j] = NULL; } } for(int r = 0; r < MAX_RUNS; r++) { initialGen(); if (r == 0) { Copy(ALL); } fout << "Population " << setw(5) << r << endl; cout << "Population " << setw(5) << r << endl; for(int i = 0; i < MAX_ROUNDS; i++) { if(i == MAX_ROUNDS - 1) logNeg = 1; cout << "Generation " << i << endl; cout << left << setw(15) << "Class" << setw(10) << "Percent"; cout << left << setw(7) << "Detect" << setw(7) << "Total" << endl; #ifdef VERBOSE_OUTPUT fout3 << "BEGIN " << i << endl; #endif fout << setw(5) << i << " |"; fout4 << setw(3) << i; fout5 << setw(3) << i; fout6 << setw(3) << i; testSelf(); train(); for(int c = 0; c < CLASS_COUNT; c++) { classAccuracy[r][i][c] = attack.labelAccuracy[c]; averageAccuracy[i][c] += attack.labelAccuracy[c]; if(attack.labelAccuracy[c] > bestAccuracy[i][c]) { bestAccuracy[i][c] = attack.labelAccuracy[c]; Copy(c); } } outputTrainedClasses(i); if(i < MAX_ROUNDS - 1) nextGen(classAccuracy[r][i]); fout << endl; fout5 << endl; fout6 << endl; #ifdef VERBOSE_OUTPUT fout3 << "END " << i << endl; #endif } testUnknown(r); } for(int r = 0; r < MAX_RUNS; r++) { cout << "Overall classification stats for Population " << r << endl; cout << left << setw(5) << "Gen"; for(int c = 0; c < CLASS_COUNT; c++) { cout << left << setw(10) << CLASS_LABELS[c]; } cout << endl; for(int i = 0; i < MAX_ROUNDS; i++) { cout << setw(5) << i; for(int c = 0; c < CLASS_COUNT; c++) { cout << setw(10) << classAccuracy[r][i][c]; } cout << endl; } } cout << "Average accuracy over all populations.\n"; cout << left << setw(5) << "Gen"; for(int c = 0; c < CLASS_COUNT; c++) { cout << left << setw(10) << CLASS_LABELS[c]; } cout << endl; for(int i = 0; i < MAX_ROUNDS; i++) { cout << setw(5) << i; for(int j = 0; j < CLASS_COUNT; j++) { cout << setw(10) << averageAccuracy[i][j] / MAX_RUNS; } cout << endl; } cout << "Best accuracy over all populations.\n"; cout << left << setw(5) << "Gen"; for(int c = 0; c < CLASS_COUNT; c++) { cout << left << setw(10) << CLASS_LABELS[c]; } cout << endl; for(int i = 0; i < MAX_ROUNDS; i++) { cout << setw(5) << i; for(int j = 0; j < CLASS_COUNT; j++) { cout << setw(10) << bestAccuracy[i][j]; } cout << endl; } cout << endl << "Champions population statistics:\n"; cout << endl; for(int i = 0; i < CLASS_COUNT; i++) { cout << "Class " << i+1 << ":\n"; for(int j = 0; j < MAX_ANTIBODIES; j++) { cout << "\t" << j+1 << " - "; cout << champs[i][j]; cout << endl; } cout << endl; } cout << endl; Dump(champs); fout.close(); fout2.close(); #ifdef VERBOSE_OUTPUT fout3.close(); #endif fout4.close(); fout5.close(); fout6.close(); return 0; }
/*************************** FUNCTIONS ***********************************/ void cleanup() { // Close all the file streams transformationFile.close(); trialFile.close(); anglesFile.close(); }
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 (36 + NUM_OF_CONSUMERS)); // C1 <--> R1 for (int i = 0; i < GROUP_SIZE; i++, g++) p2p.Install (nodes.Get (g), nodes.Get (37 + NUM_OF_CONSUMERS)); // C2 <--> R3 for (int i = 0; i < GROUP_SIZE; i++, g++) p2p.Install (nodes.Get (g), nodes.Get (9 + NUM_OF_CONSUMERS)); // C3 <--> R5 for (int i = 0; i < GROUP_SIZE; i++, g++) p2p.Install (nodes.Get (g), nodes.Get (38 + NUM_OF_CONSUMERS)); // C4 <--> R6 for (int i = 0; i < GROUP_SIZE; i++, g++) p2p.Install (nodes.Get (g), nodes.Get (13 + NUM_OF_CONSUMERS)); // C5 <--> R10 for (int i = 0; i < GROUP_SIZE; i++, g++) p2p.Install (nodes.Get (g), nodes.Get (16 + NUM_OF_CONSUMERS)); // C6 <--> R8 for (int i = 0; i < GROUP_SIZE; i++, g++) p2p.Install (nodes.Get (g), nodes.Get (20 + NUM_OF_CONSUMERS)); // C7 <--> R11 for (int i = 0; i < GROUP_SIZE; i++, g++) p2p.Install (nodes.Get (g), nodes.Get (18 + NUM_OF_CONSUMERS)); // C8 <--> R12 for (int i = 0; i < GROUP_SIZE; i++, g++) p2p.Install (nodes.Get (g), nodes.Get (28 + NUM_OF_CONSUMERS)); // C9 <--> R18 for (int i = 0; i < GROUP_SIZE; i++, g++) p2p.Install (nodes.Get (g), nodes.Get (21 + NUM_OF_CONSUMERS)); // C10 <--> R17 for (int i = 0; i < GROUP_SIZE; i++, g++) p2p.Install (nodes.Get (g), nodes.Get (24 + NUM_OF_CONSUMERS)); // C11 <--> R20 for (int i = 0; i < GROUP_SIZE; i++, g++) p2p.Install (nodes.Get (g), nodes.Get (26 + NUM_OF_CONSUMERS)); // C12 <--> R24 for (int i = 0; i < GROUP_SIZE; i++, g++) p2p.Install (nodes.Get (g), nodes.Get (35 + NUM_OF_CONSUMERS)); // C13 <--> R29 for (int i = 0; i < GROUP_SIZE; i++, g++) p2p.Install (nodes.Get (g), nodes.Get (34 + NUM_OF_CONSUMERS)); // C14 <--> R28 for (int i = 0; i < GROUP_SIZE; i++, g++) p2p.Install (nodes.Get (g), nodes.Get (33 + NUM_OF_CONSUMERS)); // C15 <--> R21 // Connecting routers p2p.Install (nodes.Get (0 + NUM_OF_CONSUMERS), nodes.Get (1 + NUM_OF_CONSUMERS)); // R0 <--> R9 p2p.Install (nodes.Get (1 + NUM_OF_CONSUMERS), nodes.Get (2 + NUM_OF_CONSUMERS)); // R1 <--> R15 p2p.Install (nodes.Get (1 + NUM_OF_CONSUMERS), nodes.Get (17 + NUM_OF_CONSUMERS)); // R1 <--> R15 p2p.Install (nodes.Get (2 + NUM_OF_CONSUMERS), nodes.Get (3 + NUM_OF_CONSUMERS)); // R2 <--> R9 p2p.Install (nodes.Get (2 + NUM_OF_CONSUMERS), nodes.Get (4 + NUM_OF_CONSUMERS)); // R2 <--> R9 p2p.Install (nodes.Get (2 + NUM_OF_CONSUMERS), nodes.Get (6 + NUM_OF_CONSUMERS)); // R2 <--> R9 p2p.Install (nodes.Get (2 + NUM_OF_CONSUMERS), nodes.Get (36 + NUM_OF_CONSUMERS)); // R2 <--> R9 p2p.Install (nodes.Get (2 + NUM_OF_CONSUMERS), nodes.Get (8 + NUM_OF_CONSUMERS)); // R2 <--> R9 p2p.Install (nodes.Get (2 + NUM_OF_CONSUMERS), nodes.Get (17 + NUM_OF_CONSUMERS)); // R2 <--> R9 p2p.Install (nodes.Get (2 + NUM_OF_CONSUMERS), nodes.Get (19 + NUM_OF_CONSUMERS)); // R2 <--> R9 p2p.Install (nodes.Get (3 + NUM_OF_CONSUMERS), nodes.Get (5 + NUM_OF_CONSUMERS)); // R3 <--> R4 p2p.Install (nodes.Get (4 + NUM_OF_CONSUMERS), nodes.Get (16 + NUM_OF_CONSUMERS)); // R4 <--> R7 p2p.Install (nodes.Get (5 + NUM_OF_CONSUMERS), nodes.Get (8 + 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 (6 + NUM_OF_CONSUMERS), nodes.Get (37 + NUM_OF_CONSUMERS)); // R6 <--> R7 p2p.Install (nodes.Get (7 + NUM_OF_CONSUMERS), nodes.Get (10 + NUM_OF_CONSUMERS)); // R7 <--> R9 p2p.Install (nodes.Get (8 + NUM_OF_CONSUMERS), nodes.Get (9 + NUM_OF_CONSUMERS)); // R8 <--> R9 p2p.Install (nodes.Get (8 + NUM_OF_CONSUMERS), nodes.Get (11 + NUM_OF_CONSUMERS)); // R8 <--> R9 p2p.Install (nodes.Get (8 + NUM_OF_CONSUMERS), nodes.Get (17 + NUM_OF_CONSUMERS)); // R8 <--> R9 // 9 done p2p.Install (nodes.Get (10 + NUM_OF_CONSUMERS), nodes.Get (11 + NUM_OF_CONSUMERS)); // R10 <--> R14 p2p.Install (nodes.Get (11 + NUM_OF_CONSUMERS), nodes.Get (16 + NUM_OF_CONSUMERS)); // R11 <--> R13 p2p.Install (nodes.Get (11 + NUM_OF_CONSUMERS), nodes.Get (38 + NUM_OF_CONSUMERS)); // R11 <--> R13 p2p.Install (nodes.Get (11 + NUM_OF_CONSUMERS), nodes.Get (12 + NUM_OF_CONSUMERS)); // R11 <--> R13 p2p.Install (nodes.Get (11 + NUM_OF_CONSUMERS), nodes.Get (13 + NUM_OF_CONSUMERS)); // R11 <--> R13 p2p.Install (nodes.Get (11 + NUM_OF_CONSUMERS), nodes.Get (23 + 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 (23 + NUM_OF_CONSUMERS)); // R13 <--> R14 p2p.Install (nodes.Get (14 + NUM_OF_CONSUMERS), nodes.Get (16 + NUM_OF_CONSUMERS)); // R14 <--> R15 p2p.Install (nodes.Get (14 + NUM_OF_CONSUMERS), nodes.Get (15 + NUM_OF_CONSUMERS)); // R14 <--> R18 p2p.Install (nodes.Get (15 + NUM_OF_CONSUMERS), nodes.Get (39 + NUM_OF_CONSUMERS)); // R15 <--> R16 p2p.Install (nodes.Get (15 + NUM_OF_CONSUMERS), nodes.Get (17 + NUM_OF_CONSUMERS)); // R15 <--> R19 p2p.Install (nodes.Get (16 + NUM_OF_CONSUMERS), nodes.Get (17 + NUM_OF_CONSUMERS)); // R16 <--> R23 p2p.Install (nodes.Get (16 + NUM_OF_CONSUMERS), nodes.Get (19 + NUM_OF_CONSUMERS)); // R16 <--> R27 p2p.Install (nodes.Get (17 + NUM_OF_CONSUMERS), nodes.Get (18 + NUM_OF_CONSUMERS)); // R17 <--> R23 p2p.Install (nodes.Get (17 + NUM_OF_CONSUMERS), nodes.Get (19 + NUM_OF_CONSUMERS)); // R17 <--> R23 p2p.Install (nodes.Get (17 + NUM_OF_CONSUMERS), nodes.Get (29 + NUM_OF_CONSUMERS)); // R17 <--> R23 p2p.Install (nodes.Get (17 + NUM_OF_CONSUMERS), nodes.Get (32 + NUM_OF_CONSUMERS)); // R17 <--> R23 p2p.Install (nodes.Get (17 + NUM_OF_CONSUMERS), nodes.Get (31 + NUM_OF_CONSUMERS)); // R17 <--> R23 p2p.Install (nodes.Get (17 + NUM_OF_CONSUMERS), nodes.Get (39 + NUM_OF_CONSUMERS)); // R17 <--> R23 // 18 done p2p.Install (nodes.Get (19 + NUM_OF_CONSUMERS), nodes.Get (20 + NUM_OF_CONSUMERS)); // R19 <--> R22 p2p.Install (nodes.Get (19 + NUM_OF_CONSUMERS), nodes.Get (27 + NUM_OF_CONSUMERS)); // R19 <--> R22 // 20 done p2p.Install (nodes.Get (21 + NUM_OF_CONSUMERS), nodes.Get (22 + NUM_OF_CONSUMERS)); // R21 <--> R22 p2p.Install (nodes.Get (22 + NUM_OF_CONSUMERS), nodes.Get (40 + NUM_OF_CONSUMERS)); // R22 <--> R23 p2p.Install (nodes.Get (22 + NUM_OF_CONSUMERS), nodes.Get (23 + NUM_OF_CONSUMERS)); // R22 <--> R28 p2p.Install (nodes.Get (22 + NUM_OF_CONSUMERS), nodes.Get (25 + NUM_OF_CONSUMERS)); // R22 <--> R29 p2p.Install (nodes.Get (23 + NUM_OF_CONSUMERS), nodes.Get (24 + NUM_OF_CONSUMERS)); // R23 <--> R24 // 24 done p2p.Install (nodes.Get (25 + NUM_OF_CONSUMERS), nodes.Get (27 + NUM_OF_CONSUMERS)); // R26 <--> R27 p2p.Install (nodes.Get (26 + NUM_OF_CONSUMERS), nodes.Get (27 + NUM_OF_CONSUMERS)); // R26 <--> R27 p2p.Install (nodes.Get (27 + NUM_OF_CONSUMERS), nodes.Get (40 + NUM_OF_CONSUMERS)); // R26 <--> R27 p2p.Install (nodes.Get (27 + NUM_OF_CONSUMERS), nodes.Get (30 + NUM_OF_CONSUMERS)); // R26 <--> R27 p2p.Install (nodes.Get (27 + NUM_OF_CONSUMERS), nodes.Get (31 + NUM_OF_CONSUMERS)); // R26 <--> R27 p2p.Install (nodes.Get (28 + NUM_OF_CONSUMERS), nodes.Get (29 + NUM_OF_CONSUMERS)); // R26 <--> R27 p2p.Install (nodes.Get (29 + NUM_OF_CONSUMERS), nodes.Get (30 + NUM_OF_CONSUMERS)); // R26 <--> R27 p2p.Install (nodes.Get (30 + NUM_OF_CONSUMERS), nodes.Get (31 + NUM_OF_CONSUMERS)); // R26 <--> R27 p2p.Install (nodes.Get (30 + NUM_OF_CONSUMERS), nodes.Get (41 + NUM_OF_CONSUMERS)); // R26 <--> R27 p2p.Install (nodes.Get (30 + NUM_OF_CONSUMERS), nodes.Get (35 + NUM_OF_CONSUMERS)); // R26 <--> R27 p2p.Install (nodes.Get (31 + NUM_OF_CONSUMERS), nodes.Get (41 + NUM_OF_CONSUMERS)); // R26 <--> R27 p2p.Install (nodes.Get (31 + NUM_OF_CONSUMERS), nodes.Get (32 + NUM_OF_CONSUMERS)); // R26 <--> R27 p2p.Install (nodes.Get (31 + NUM_OF_CONSUMERS), nodes.Get (34 + NUM_OF_CONSUMERS)); // R26 <--> R27 p2p.Install (nodes.Get (32 + NUM_OF_CONSUMERS), nodes.Get (33 + NUM_OF_CONSUMERS)); // R26 <--> R27 // 33 done // 34 done // 35 done // 36 done // 37 done // 38 done // 39 done // 40 done // 41 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::AccountingConsumer"); consumerHelperHonest.SetAttribute("Frequency", StringValue("10")); // 10 interests a second consumerHelperHonest.SetAttribute("Randomize", StringValue("uniform")); consumerHelperHonest.SetAttribute("StartSeq", IntegerValue(0)); consumerHelperHonest.SetPrefix("/prefix/A/"); for(int i=0; i < NUM_OF_CONSUMERS; i++) { consumerHelperHonest.SetAttribute("ConsumerID", IntegerValue(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 // Producer will reply to all requests starting with /prefix/A ndn::AppHelper producerHelper("ns3::ndn::AccountingProducer"); producerHelper.SetPrefix("/prefix/A"); producerHelper.SetAttribute("PayloadSize", StringValue("1024")); producerHelper.Install(nodes.Get(producerId)); // Traces ndn::L3RateTracer::InstallAll(RATE_OUTPUT_FILE_NAME, Seconds(1.0)); Simulator::Stop(Seconds(SIMULATION_DURATION)); Simulator::Run(); Simulator::Destroy(); delayFile.close(); return 0; }