DEF_TEST(AndroidOptionsSize, reporter) { // A paint with default android options should serialize to something smaller than // a paint with non-default android options. SkPaint defaultOptions; SkPaintOptionsAndroid options; options.setUseFontFallbacks(true); SkPaint nonDefaultOptions; nonDefaultOptions.setPaintOptionsAndroid(options); SkPaint dummy; REPORTER_ASSERT(reporter, Reconstruct(defaultOptions, &dummy) < Reconstruct(nonDefaultOptions, &dummy)); }
void BotanySystem::ParseCommands( std::stringstream* p_ss ) { std::string module; std::string param; std::string value; std::getline(*p_ss, module, ' '); std::getline(*p_ss, module, ' '); if(module == "help" ) { m_engineContext->m_logger->LogText(LogTag::NOTAG, LogLevel::HELP_PRINT, "[BOTANY COMMANDS]"); m_engineContext->m_logger->LogText(LogTag::NOTAG, LogLevel::HELP_PRINT, "/b f [float] - Set botany factor"); m_engineContext->m_logger->LogText(LogTag::NOTAG, LogLevel::HELP_PRINT, "/b s [0/1] - Activate or deactivate botany"); } if(module == "factor" || module == "f") { std::getline(*p_ss, value, ' '); SetGrassFactor((float)atof(value.c_str())); Reconstruct(); } else if(module == "show" || module == "s") { std::getline(*p_ss, value, ' '); m_show = (atoi(value.c_str()) == 1) ? true : false; } }
static void android_options_size(skiatest::Reporter* reporter) { // A paint with default android options should serialize to something smaller than // a paint with non-default android options. SkPaint defaultOptions; SkPaintOptionsAndroid options; options.setUseFontFallbacks(true); SkPaint nonDefaultOptions; nonDefaultOptions.setPaintOptionsAndroid(options); SkPaint dummy; REPORTER_ASSERT(reporter, Reconstruct(defaultOptions, &dummy) < Reconstruct(nonDefaultOptions, &dummy)); }
void circuit_t::ReduceParallelList (const item_list_t ¶llel_list) { item_t first_item = parallel_list.front(); node_t* new_top_node = first_item.e->TopNode(); node_t* new_bottom_node = first_item.e->BottomNode(); string new_value = ""; // Cap, Current Source if (first_item.e->type == E_CAPACITOR || first_item.e->type == E_CSRC) { for (item_list_t::const_iterator i = parallel_list.begin(); i != parallel_list.end(); i++) { if (i->e->type == E_VSRC) { new_value += i->e->GetValueAsString(i->direction); if (next(i) != parallel_list.end()) new_value += " + "; } /* if */ else { new_value += i->e->GetValueAsString(); if (next(i) != parallel_list.end()) new_value += " + "; } /* else */ DisconnectElement (i->e); } /* for */ } /* if */ // all elements else { new_value = "("; for (item_list_t::const_iterator i = parallel_list.begin(); i != parallel_list.end(); i++) { new_value += i->e->GetValueAsString(i->direction) + "^(-1)"; if (next(i) != parallel_list.end()) new_value += " + "; DisconnectElement (i->e); } /* for */ new_value += ")^(-1)"; } /* else */ element_t* new_element = AddElement (NONE, first_item.e->type, 0, ITEM_DIRECTION_FWD, new_top_node, new_bottom_node); new_element->SetValueFromString (new_value); Reconstruct(); //solution->add_step (STEP_PARALLEL_REDUCTION, parallel_list); } /* circuit_t::reduce_parallel_list */
std::string Selector::Select() { auto found = false; if (Select(found, 0, 0, k_)) { return Reconstruct(); } return ""; }
DEF_TEST(AndroidOptionsSerialization, reporter) { // We want to make sure that Android's paint options survive a flatten/unflatten round trip. // These are all non-default options. SkPaintOptionsAndroid options; options.setLanguage("ja-JP"); options.setFontVariant(SkPaintOptionsAndroid::kElegant_Variant); options.setUseFontFallbacks(true); SkPaint paint; paint.setPaintOptionsAndroid(options); SkPaint reconstructed; Reconstruct(paint, &reconstructed); REPORTER_ASSERT(reporter, options == reconstructed.getPaintOptionsAndroid()); }
DEF_TEST(AndroidOptionsSerializationReverse, reporter) { // Opposite test of above: make sure the serialized default values of a paint overwrite // non-default values on the paint we're unflattening into. const SkPaint defaultOptions; SkPaintOptionsAndroid options; options.setLanguage("ja-JP"); options.setFontVariant(SkPaintOptionsAndroid::kElegant_Variant); options.setUseFontFallbacks(true); SkPaint nonDefaultOptions; nonDefaultOptions.setPaintOptionsAndroid(options); Reconstruct(defaultOptions, &nonDefaultOptions); REPORTER_ASSERT(reporter, defaultOptions.getPaintOptionsAndroid() == nonDefaultOptions.getPaintOptionsAndroid()); }
BOOL dump(DWORD dwOEP, struct dll *NewDLL, DWORD dwStartIAT) { DWORD dwBase; DWORD dwLen; BYTE modulePath[MAX_PATH + 8]; PBYTE pDump; PIMAGE_DOS_HEADER pDosHeader; PIMAGE_NT_HEADERS pPE; PIMAGE_SECTION_HEADER pSection; PIMAGE_SECTION_HEADER pSectionHeaders; DWORD curseur, i; HANDLE hFile; DWORD NbByteWritten; PBYTE IAT = NULL; DWORD dwAllocSize = 0; DWORD dwRVAIAT = 0; dwBase = (DWORD)GetModuleHandle(NULL); if (((dwLen = GetModuleFileNameA((HMODULE) dwBase, modulePath, MAX_PATH + 1)) >= MAX_PATH) || (!dwLen)) return FALSE; if (!(pDump = AllocAndCopy(dwBase, &dwAllocSize))) return FALSE; pDosHeader = (PIMAGE_DOS_HEADER)pDump; pPE = (PIMAGE_NT_HEADERS)(pDump + pDosHeader->e_lfanew); pSection = (PIMAGE_SECTION_HEADER)((PCHAR)pPE + sizeof(IMAGE_FILE_HEADER) + pPE->FileHeader.SizeOfOptionalHeader + sizeof(DWORD)); pPE->OptionalHeader.FileAlignment = 0x200; for (curseur = AlignSize(pPE->OptionalHeader.SizeOfHeaders, pPE->OptionalHeader.FileAlignment) - 1; ! pDump[curseur]; curseur --); pSectionHeaders = (PIMAGE_SECTION_HEADER)((PBYTE)pPE + sizeof(IMAGE_FILE_HEADER) + pPE->FileHeader.SizeOfOptionalHeader + sizeof(DWORD)); dwRVAIAT = AlignSize(pSectionHeaders[pPE->FileHeader.NumberOfSections - 1].VirtualAddress + pSectionHeaders[pPE->FileHeader.NumberOfSections - 1].Misc.VirtualSize, pPE->OptionalHeader.SectionAlignment); IAT = Reconstruct(dwStartIAT, NewDLL, dwRVAIAT); memcpy(pDump, dwBase, dwAllocSize); curseur = AlignSize(curseur + 1, pPE->OptionalHeader.FileAlignment); pPE->OptionalHeader.SizeOfHeaders = curseur; for (i = 0; i < pPE->FileHeader.NumberOfSections; i++) { memcpy(pDump + curseur, pDump + pSection[i].VirtualAddress, pSection[i].Misc.VirtualSize); pSection[i].PointerToRawData = curseur; curseur += pSection[i].Misc.VirtualSize - 1; //AlignCurseur(pDump, &curseur); while ((pDump[curseur] == 0) && (((int)curseur) >= -1)) curseur--; curseur = AlignSize(curseur + 1, pPE->OptionalHeader.FileAlignment); pSection[i].SizeOfRawData = curseur - pSection[i].PointerToRawData; } strcpy(pSection[pPE->FileHeader.NumberOfSections].Name, ".suce"); pSection[pPE->FileHeader.NumberOfSections].PointerToRawData = curseur; pSection[pPE->FileHeader.NumberOfSections].Misc.VirtualSize = AlignSize(computeSizeIAT(NewDLL), pPE->OptionalHeader.SectionAlignment); pSection[pPE->FileHeader.NumberOfSections].VirtualAddress = dwRVAIAT; pSection[pPE->FileHeader.NumberOfSections].Characteristics = 0xE0000060; memcpy(pDump + curseur, IAT, pSection[pPE->FileHeader.NumberOfSections].Misc.VirtualSize); curseur += pSection[pPE->FileHeader.NumberOfSections].Misc.VirtualSize - 1; while ((pDump[curseur] == 0) && (((int)curseur) >= -1)) curseur--; curseur = AlignSize(curseur + 1, pPE->OptionalHeader.FileAlignment); pSection[pPE->FileHeader.NumberOfSections].SizeOfRawData = curseur - pSection[pPE->FileHeader.NumberOfSections].PointerToRawData; pPE->FileHeader.NumberOfSections += 1; pPE->OptionalHeader.DataDirectory[1].VirtualAddress = dwRVAIAT; pPE->OptionalHeader.DataDirectory[1].Size = computeSizeIAT(NewDLL); pPE->OptionalHeader.AddressOfEntryPoint = dwOEP - (DWORD)GetModuleHandle(0); pPE->OptionalHeader.SizeOfImage += AlignSize(computeSizeIAT(NewDLL), pPE->OptionalHeader.SectionAlignment); modulePath[dwLen - 4] = '-'; modulePath[dwLen - 3] = 'd'; modulePath[dwLen - 2] = 'u'; modulePath[dwLen - 1] = 'm'; modulePath[dwLen] = 'p'; modulePath[dwLen + 1] = 'e'; modulePath[dwLen + 2] = 'd'; modulePath[dwLen + 3] = '.'; modulePath[dwLen + 4] = 'e'; modulePath[dwLen + 5] = 'x'; modulePath[dwLen + 6] = 'e'; modulePath[dwLen + 7] = 0; if ((hFile = CreateFileA(modulePath,(GENERIC_READ | GENERIC_WRITE), FILE_SHARE_READ | FILE_SHARE_READ, NULL, CREATE_ALWAYS, 0, NULL)) == INVALID_HANDLE_VALUE) return FALSE; WriteFile(hFile, pDump, curseur, &NbByteWritten, NULL); if (NbByteWritten != curseur) return FALSE; return TRUE; }
/// SingleComponentLSScan::ParseMCU // Parse a single MCU in this scan. Return true if there are more // MCUs in this row. bool SingleComponentLSScan::ParseMCU(void) { #if ACCUSOFT_CODE int lines = m_ulRemaining[0]; // total number of MCU lines processed. UBYTE preshift = m_ucLowBit + FractionalColorBitsOf(); struct Line *line = CurrentLine(0); // // If a DNL marker is present, the number of remaining lines is zero. Fix it. if (m_pFrame->HeightOf() == 0) { assert(lines == 0); lines = 8; } assert(m_ucCount == 1); // // A "MCU" in respect to the code organization is eight lines. if (lines > 8) { lines = 8; } if (m_pFrame->HeightOf() > 0) m_ulRemaining[0] -= lines; assert(lines > 0); // Loop over lines and columns do { LONG length = m_ulWidth[0]; LONG *lp = line->m_pData; #ifdef DEBUG_LS int xpos = 0; static int linenumber = 0; printf("\n%4d : ",++linenumber); #endif StartLine(0); if (BeginReadMCU(m_Stream.ByteStreamOf())) { // No error handling strategy. No RST in scans. Bummer! do { LONG a,b,c,d; // neighbouring values. LONG d1,d2,d3; // local gradients. GetContext(0,a,b,c,d); d1 = d - b; // compute local gradients d2 = b - c; d3 = c - a; if (isRunMode(d1,d2,d3)) { LONG run = DecodeRun(length,m_lRunIndex[0]); // // Now fill the data. while(run) { // Update so that the next process gets the correct value. UpdateContext(0,a); // And insert the value into the target line as well. *lp++ = a << preshift; #ifdef DEBUG_LS printf("%4d:<%2x> ",xpos++,a); #endif run--,length--; // As long as there are pixels on the line. } // // More data on the line? I.e. the run did not cover the full m_lJ samples? // Now decode the run interruption sample. if (length) { bool negative; // the sign variable bool rtype; // run interruption type LONG errval; // the prediction error LONG merr; // the mapped error (symbol) LONG rx; // the reconstructed value UBYTE k; // golomb parameter // Get the neighbourhood. GetContext(0,a,b,c,d); // Get the prediction mode. rtype = InterruptedPredictionMode(negative,a,b); // Get the golomb parameter for run interruption coding. k = GolombParameter(rtype); // Golomb-decode the error symbol. merr = GolombDecode(k,m_lLimit - m_lJ[m_lRunIndex[0]] - 1); // Inverse the error mapping procedure. errval = InverseErrorMapping(merr + rtype,ErrorMappingOffset(rtype,rtype || merr,k)); // Compute the reconstructed value. rx = Reconstruct(negative,rtype?a:b,errval); // Update so that the next process gets the correct value. UpdateContext(0,rx); // Fill in the value into the line *lp = rx << preshift; #ifdef DEBUG_LS printf("%4d:<%2x> ",xpos++,*lp); #endif // Update the variables of the run mode. UpdateState(rtype,errval); // Update the run index now. This is not part of // EncodeRun because the non-reduced run-index is // required for the golomb coder length limit. if (m_lRunIndex[0] > 0) m_lRunIndex[0]--; } else break; // end of line. } else { UWORD ctxt; bool negative; // the sign variable. LONG px; // the predicted variable. LONG rx; // the reconstructed value. LONG errval; // the error value. LONG merr; // the mapped error value. UBYTE k; // the Golomb parameter. // Quantize the gradients. d1 = QuantizedGradient(d1); d2 = QuantizedGradient(d2); d3 = QuantizedGradient(d3); // Compute the context. ctxt = Context(negative,d1,d2,d3); // Compute the predicted value. px = Predict(a,b,c); // Correct the prediction. px = CorrectPrediction(ctxt,negative,px); // Compute the golomb parameter k from the context. k = GolombParameter(ctxt); // Decode the error symbol. merr = GolombDecode(k,m_lLimit); // Inverse the error symbol into an error value. errval = InverseErrorMapping(merr,ErrorMappingOffset(ctxt,k)); // Update the variables. UpdateState(ctxt,errval); // Compute the reconstructed value. rx = Reconstruct(negative,px,errval); // Update so that the next process gets the correct value. UpdateContext(0,rx); // And insert the value into the target line as well. *lp = rx << preshift; #ifdef DEBUG_LS printf("%4d:<%2x> ",xpos++,*lp); #endif } } while(++lp,--length); } // No error handling here. EndLine(0); line = line->m_pNext; } while(--lines); // // If this is the last line, gobble up all the // bits from bitstuffing the last byte may have left. // As SkipStuffing is idempotent, we can also do that // all the time. m_Stream.SkipStuffing(); #endif return false; }
/// SingleComponentLSScan::WriteMCU // Write a single MCU in this scan. bool SingleComponentLSScan::WriteMCU(void) { #if ACCUSOFT_CODE int lines = m_ulRemaining[0]; // total number of MCU lines processed. UBYTE preshift = m_ucLowBit + FractionalColorBitsOf(); struct Line *line = CurrentLine(0); assert(m_ucCount == 1); // // A "MCU" in respect to the code organization is eight lines. if (lines > 8) { lines = 8; } m_ulRemaining[0] -= lines; assert(lines > 0); // Loop over lines and columns do { LONG length = m_ulWidth[0]; LONG *lp = line->m_pData; BeginWriteMCU(m_Stream.ByteStreamOf()); // MCU is a single line. StartLine(0); do { LONG a,b,c,d,x; // neighbouring values. LONG d1,d2,d3; // local gradients. GetContext(0,a,b,c,d); x = *lp >> preshift; d1 = d - b; // compute local gradients d2 = b - c; d3 = c - a; if (isRunMode(d1,d2,d3)) { LONG runval = a; LONG runcnt = 0; do { x = *lp >> preshift; if (x - runval < -m_lNear || x - runval > m_lNear) break; // Update so that the next process gets the correct value. // Also updates the line pointers. UpdateContext(0,runval); } while(lp++,runcnt++,--length); // Encode the run. Depends on whether the run was interrupted // by the end of the line. EncodeRun(runcnt,length == 0,m_lRunIndex[0]); // Continue the encoding of the end of the run if there are more // samples to encode. if (length) { bool negative; // the sign variable bool rtype; // run interruption type LONG errval; // the prediction error LONG merr; // the mapped error (symbol) LONG rx; // the reconstructed value UBYTE k; // golomb parameter // Get the neighbourhood. GetContext(0,a,b,c,d); // Get the prediction mode. rtype = InterruptedPredictionMode(negative,a,b); // Compute the error value. errval = x - ((rtype)?(a):(b)); if (negative) errval = -errval; // Quantize the error. errval = QuantizePredictionError(errval); // Compute the reconstructed value. rx = Reconstruct(negative,rtype?a:b,errval); // Update so that the next process gets the correct value. UpdateContext(0,rx); // Get the golomb parameter for run interruption coding. k = GolombParameter(rtype); // Map the error into a symbol. merr = ErrorMapping(errval,ErrorMappingOffset(rtype,errval != 0,k)) - rtype; // Golomb-coding of the error. GolombCode(k,merr,m_lLimit - m_lJ[m_lRunIndex[0]] - 1); // Update the variables of the run mode. UpdateState(rtype,errval); // Update the run index now. This is not part of // EncodeRun because the non-reduced run-index is // required for the golomb coder length limit. if (m_lRunIndex[0] > 0) m_lRunIndex[0]--; } else break; // Line ended, abort the loop over the line. } else { UWORD ctxt; bool negative; // the sign variable. LONG px; // the predicted variable. LONG rx; // the reconstructed value. LONG errval; // the error value. LONG merr; // the mapped error value. UBYTE k; // the Golomb parameter. // Quantize the gradients. d1 = QuantizedGradient(d1); d2 = QuantizedGradient(d2); d3 = QuantizedGradient(d3); // Compute the context. ctxt = Context(negative,d1,d2,d3); // Compute the predicted value. px = Predict(a,b,c); // Correct the prediction. px = CorrectPrediction(ctxt,negative,px); // Compute the error value. errval = x - px; if (negative) errval = -errval; // Quantize the prediction error if NEAR > 0 errval = QuantizePredictionError(errval); // Compute the reconstructed value. rx = Reconstruct(negative,px,errval); // Update so that the next process gets the correct value. UpdateContext(0,rx); // Compute the golomb parameter k from the context. k = GolombParameter(ctxt); // Map the error into a symbol merr = ErrorMapping(errval,ErrorMappingOffset(ctxt,k)); // Golomb-coding of the error. GolombCode(k,merr,m_lLimit); // Update the variables. UpdateState(ctxt,errval); } } while(++lp,--length); EndLine(0); line = line->m_pNext; } while(--lines);
void CMixturePPCA::Reconstruct(const CMixturePPCAParam& param, CVisDVector& data) const { Reconstruct(param.m_EigenParam, param.m_iCluster, data); }
void TSVDUnfoldExample() { gROOT->Reset(); gROOT->SetStyle("Plain"); gStyle->SetOptStat(0); TRandom3 R; const Double_t cutdummy= -99999.0; // --- Data/MC toy generation ----------------------------------- // The MC input Int_t nbins = 40; TH1D *xini = new TH1D("xini", "MC truth", nbins, -10.0, 10.0); TH1D *bini = new TH1D("bini", "MC reco", nbins, -10.0, 10.0); TH2D *Adet = new TH2D("Adet", "detector response", nbins, -10.0, 10.0, nbins, -10.0, 10.0); // Data TH1D *data = new TH1D("data", "data", nbins, -10.0, 10.0); // Data "truth" distribution to test the unfolding TH1D *datatrue = new TH1D("datatrue", "data truth", nbins, -10.0, 10.0); // Statistical covariance matrix TH2D *statcov = new TH2D("statcov", "covariance matrix", nbins, -10.0, 10.0, nbins, -10.0, 10.0); // Fill the MC using a Breit-Wigner, mean 0.3 and width 2.5. for (Int_t i= 0; i<100000; i++) { Double_t xt = R.BreitWigner(0.3, 2.5); xini->Fill(xt); Double_t x = Reconstruct( xt, R ); if (x != cutdummy) { Adet->Fill(x, xt); bini->Fill(x); } } // Fill the "data" with a Gaussian, mean 0 and width 2. for (Int_t i=0; i<10000; i++) { Double_t xt = R.Gaus(0.0, 2.0); datatrue->Fill(xt); Double_t x = Reconstruct( xt, R ); if (x != cutdummy) data->Fill(x); } cout << "Created toy distributions and errors for: " << endl; cout << "... \"true MC\" and \"reconstructed (smeared) MC\"" << endl; cout << "... \"true data\" and \"reconstructed (smeared) data\"" << endl; cout << "... the \"detector response matrix\"" << endl; // Fill the data covariance matrix for (int i=1; i<=data->GetNbinsX(); i++) { statcov->SetBinContent(i,i,data->GetBinError(i)*data->GetBinError(i)); } // --- Here starts the actual unfolding ------------------------- // Create TSVDUnfold object and initialise TSVDUnfold *tsvdunf = new TSVDUnfold( data, statcov, bini, xini, Adet ); // It is possible to normalise unfolded spectrum to unit area tsvdunf->SetNormalize( kFALSE ); // no normalisation here // Perform the unfolding with regularisation parameter kreg = 13 // - the larger kreg, the finer grained the unfolding, but the more fluctuations occur // - the smaller kreg, the stronger is the regularisation and the bias TH1D* unfres = tsvdunf->Unfold( 13 ); // Get the distribution of the d to cross check the regularization // - choose kreg to be the point where |d_i| stop being statistically significantly >>1 TH1D* ddist = tsvdunf->GetD(); // Get the distribution of the singular values TH1D* svdist = tsvdunf->GetSV(); // Compute the error matrix for the unfolded spectrum using toy MC // using the measured covariance matrix as input to generate the toys // 100 toys should usually be enough // The same method can be used for different covariance matrices separately. TH2D* ustatcov = tsvdunf->GetUnfoldCovMatrix( statcov, 100 ); // Now compute the error matrix on the unfolded distribution originating // from the finite detector matrix statistics TH2D* uadetcov = tsvdunf->GetAdetCovMatrix( 100 ); // Sum up the two (they are uncorrelated) ustatcov->Add( uadetcov ); //Get the computed regularized covariance matrix (always corresponding to total uncertainty passed in constructor) and add uncertainties from finite MC statistics. TH2D* utaucov = tsvdunf->GetXtau(); utaucov->Add( uadetcov ); //Get the computed inverse of the covariance matrix TH2D* uinvcov = tsvdunf->GetXinv(); // --- Only plotting stuff below ------------------------------ for (int i=1; i<=unfres->GetNbinsX(); i++) { unfres->SetBinError(i, TMath::Sqrt(utaucov->GetBinContent(i,i))); } // Renormalize just to be able to plot on the same scale xini->Scale(0.7*datatrue->Integral()/xini->Integral()); TLegend *leg = new TLegend(0.58,0.68,0.99,0.88); leg->SetBorderSize(0); leg->SetFillColor(0); leg->SetFillStyle(0); leg->AddEntry(unfres,"Unfolded Data","p"); leg->AddEntry(datatrue,"True Data","l"); leg->AddEntry(data,"Reconstructed Data","l"); leg->AddEntry(xini,"True MC","l"); TCanvas *c1 = new TCanvas( "c1", "Unfolding toy example with TSVDUnfold", 900, 800 ); // --- Style settings ----------------------------------------- Int_t c_Canvas = TColor::GetColor( "#f0f0f0" ); Int_t c_FrameFill = TColor::GetColor( "#fffffd" ); Int_t c_TitleBox = TColor::GetColor( "#6D7B8D" ); Int_t c_TitleText = TColor::GetColor( "#FFFFFF" ); c1->SetFrameFillColor( c_FrameFill ); c1->SetFillColor ( c_Canvas ); c1->Divide(1,2); TVirtualPad * c11 = c1->cd(1); c11->SetFrameFillColor( c_FrameFill ); c11->SetFillColor ( c_Canvas ); gStyle->SetTitleFillColor( c_TitleBox ); gStyle->SetTitleTextColor( c_TitleText ); gStyle->SetTitleBorderSize( 1 ); gStyle->SetTitleH( 0.052 ); gStyle->SetTitleX( c1->GetLeftMargin() ); gStyle->SetTitleY( 1 - c1->GetTopMargin() + gStyle->GetTitleH() ); gStyle->SetTitleW( 1 - c1->GetLeftMargin() - c1->GetRightMargin() ); TH1D* frame = new TH1D( *unfres ); frame->SetTitle( "Unfolding toy example with TSVDUnfold" ); frame->GetXaxis()->SetTitle( "x variable" ); frame->GetYaxis()->SetTitle( "Events" ); frame->GetXaxis()->SetTitleOffset( 1.25 ); frame->GetYaxis()->SetTitleOffset( 1.29 ); frame->Draw(); data->SetLineStyle(2); data->SetLineColor(4); data->SetLineWidth(2); unfres->SetMarkerStyle(20); datatrue->SetLineColor(2); datatrue->SetLineWidth(2); xini->SetLineStyle(2); xini->SetLineColor(8); xini->SetLineWidth(2); // ------------------------------------------------------------ // add histograms unfres->Draw("same"); datatrue->Draw("same"); data->Draw("same"); xini->Draw("same"); leg->Draw(); // covariance matrix gStyle->SetPalette(1,0); TVirtualPad * c12 = c1->cd(2); c12->Divide(2,1); TVirtualPad * c2 = c12->cd(1); c2->SetFrameFillColor( c_FrameFill ); c2->SetFillColor ( c_Canvas ); c2->SetRightMargin ( 0.15 ); TH2D* covframe = new TH2D( *ustatcov ); covframe->SetTitle( "TSVDUnfold covariance matrix" ); covframe->GetXaxis()->SetTitle( "x variable" ); covframe->GetYaxis()->SetTitle( "x variable" ); covframe->GetXaxis()->SetTitleOffset( 1.25 ); covframe->GetYaxis()->SetTitleOffset( 1.29 ); covframe->Draw(); ustatcov->SetLineWidth( 2 ); ustatcov->Draw( "colzsame" ); // distribution of the d quantity TVirtualPad * c3 = c12->cd(2); c3->SetFrameFillColor( c_FrameFill ); c3->SetFillColor ( c_Canvas ); c3->SetLogy(); TLine *line = new TLine( 0.,1.,40.,1. ); line->SetLineStyle(2); TH1D* dframe = new TH1D( *ddist ); dframe->SetTitle( "TSVDUnfold |d_{i}|" ); dframe->GetXaxis()->SetTitle( "i" ); dframe->GetYaxis()->SetTitle( "|d_{i}|" ); dframe->GetXaxis()->SetTitleOffset( 1.25 ); dframe->GetYaxis()->SetTitleOffset( 1.29 ); dframe->SetMinimum( 0.001 ); dframe->Draw(); ddist->SetLineWidth( 2 ); ddist->Draw( "same" ); line->Draw(); }
void TrainLINE() { InitHashTable(); ReadData(); Reconstruct(); }
Waifu2x::eWaifu2xError Waifu2x::waifu2x(const boost::filesystem::path &input_file, const boost::filesystem::path &output_file, const waifu2xCancelFunc cancel_func) { Waifu2x::eWaifu2xError ret; if (!is_inited) return eWaifu2xError_NotInitialized; const boost::filesystem::path ip(input_file); const boost::filesystem::path ipext(ip.extension()); const bool isJpeg = boost::iequals(ipext.string(), ".jpg") || boost::iequals(ipext.string(), ".jpeg"); const bool isReconstructNoise = mode == "noise" || mode == "noise_scale" || (mode == "auto_scale" && isJpeg); const bool isReconstructScale = mode == "scale" || mode == "noise_scale" || mode == "auto_scale"; cv::Mat float_image; ret = LoadMat(float_image, input_file); if (ret != eWaifu2xError_OK) return ret; cv::Mat reconstruct_image; ret = Reconstruct(isReconstructNoise, isReconstructScale, cancel_func, float_image, reconstruct_image); if (ret != eWaifu2xError_OK) return ret; cv::Mat process_image; ret = AfterReconstructFloatMatProcess(isReconstructScale, cancel_func, float_image, reconstruct_image, process_image); if (ret != eWaifu2xError_OK) return ret; float_image.release(); const int cv_depth = DepthBitToCVDepth(output_depth); const double max_val = GetValumeMaxFromCVDepth(cv_depth); const double eps = GetEPS(cv_depth); cv::Mat write_iamge; if (output_depth != 32) // 出力がfloat形式なら変換しない process_image.convertTo(write_iamge, cv_depth, max_val, eps); else write_iamge = process_image; process_image.release(); // 完全透明のピクセルの色を消す(処理の都合上、完全透明のピクセルにも色を付けたから) // モデルによっては画像全域の完全透明の場所にごく小さい値のアルファが広がることがある。それを消すためにcv_depthへ変換してからこの処理を行うことにした // (ただしcv_depthが32の場合だと意味は無いが) if (write_iamge.channels() > 3) { std::vector<cv::Mat> planes; cv::split(write_iamge, planes); cv::Mat mask; cv::threshold(planes[3], mask, 0.0, 1.0, cv::THRESH_BINARY); // アルファチャンネルを二値化してマスクとして扱う // アルファチャンネルが0のところの色を消す planes[0] = planes[0].mul(mask); planes[1] = planes[1].mul(mask); planes[2] = planes[2].mul(mask); cv::merge(planes, write_iamge); } ret = WriteMat(write_iamge, output_file); if (ret != eWaifu2xError_OK) return ret; write_iamge.release(); return eWaifu2xError_OK; }
Waifu2x::eWaifu2xError Waifu2x::AfterReconstructFloatMatProcess(const bool isReconstructScale, const waifu2xCancelFunc cancel_func, const cv::Mat &floatim, const cv::Mat &in, cv::Mat &out) { cv::Size_<int> image_size = in.size(); cv::Mat process_image; if (input_plane == 1) { // 再構築した輝度画像とCreateZoomColorImage()で作成した色情報をマージして通常の画像に変換し、書き込む std::vector<cv::Mat> color_planes; CreateZoomColorImage(floatim, image_size, color_planes); color_planes[0] = in; cv::Mat converted_image; cv::merge(color_planes, converted_image); color_planes.clear(); cv::cvtColor(converted_image, process_image, ConvertInverseMode); converted_image.release(); } else { std::vector<cv::Mat> planes; cv::split(in, planes); // RGBからBGRに直す std::swap(planes[0], planes[2]); cv::merge(planes, process_image); } const int scale2 = ceil(log2(scale_ratio)); const double shrinkRatio = scale_ratio / std::pow(2.0, (double)scale2); cv::Mat alpha; if (floatim.channels() == 4) { std::vector<cv::Mat> planes; cv::split(floatim, planes); if (isReconstructScale) Reconstruct(false, true, cancel_func, planes[3], alpha); else alpha = planes[3]; } // アルファチャンネルがあったらアルファを付加する if (!alpha.empty()) { std::vector<cv::Mat> planes; cv::split(process_image, planes); process_image.release(); planes.push_back(alpha); cv::merge(planes, process_image); } if (isReconstructScale) { const cv::Size_<int> ns(image_size.width * shrinkRatio, image_size.height * shrinkRatio); if (image_size.width != ns.width || image_size.height != ns.height) cv::resize(process_image, process_image, ns, 0.0, 0.0, cv::INTER_LINEAR); } // 値を0〜1にクリッピング cv::threshold(process_image, process_image, 1.0, 1.0, cv::THRESH_TRUNC); cv::threshold(process_image, process_image, 0.0, 0.0, cv::THRESH_TOZERO); out = process_image; return eWaifu2xError_OK; }
/// main int main(int argc,char **argv) { int quality = -1; int hdrquality = -1; int maxerror = 0; int levels = 0; int restart = 0; int lsmode = -1; // Use JPEGLS int hiddenbits = 0; // hidden DCT bits int riddenbits = 0; // hidden bits in the residual domain int ahiddenbits = 0; // hidden DCT bits in the base alpha codestream int ariddenbits = 0; // hidden DCT bits in the residual alpha codestream. int resprec = 8; // precision in the residual domain int aresprec = 8; // precision of the residual alpha double gamma = 0.0; bool pyramidal = false; bool residuals = false; int colortrafo = JPGFLAG_MATRIX_COLORTRANSFORMATION_YCBCR; bool lossless = false; bool optimize = false; bool accoding = false; bool qscan = false; bool progressive = false; bool writednl = false; bool noiseshaping = false; bool rprogressive = false; bool rsequential = false; bool raccoding = false; bool serms = false; bool aserms = false; bool abypass = false; bool losslessdct = false; bool dctbypass = false; bool openloop = false; bool deadzone = false; bool lagrangian = false; bool dering = false; bool aopenloop = false; bool adeadzone = false; bool alagrangian = false; bool adering = false; bool xyz = false; bool cxyz = false; bool separate = false; bool noclamp = false; bool setprofile = false; bool upsample = true; bool median = true; int splitquality = -1; int profile = 2; // profile C. const char *sub = NULL; const char *ressub = NULL; const char *ldrsource = NULL; const char *lsource = NULL; const char *alpha = NULL; // source or target of the alpha plane bool alpharesiduals = false; int alphamode = JPGFLAG_ALPHA_REGULAR; // alpha mode int matte_r = 0,matte_g = 0,matte_b = 0; // matte color for alpha. int alphaquality = 70; int alphahdrquality = 0; int alphasplitquality = -1; int tabletype = 0; // quantization table types int residualtt = 0; int alphatt = 0; int residualalphatt = 0; int smooth = 0; // histogram smoothing PrintLicense(); fflush(stdout); while(argc > 3 && argv[1][0] == '-') { if (!strcmp(argv[1],"-q")) { quality = ParseInt(argc,argv); } else if (!strcmp(argv[1],"-Q")) { hdrquality = ParseInt(argc,argv); } else if (!strcmp(argv[1],"-quality")) { splitquality = ParseInt(argc,argv); } else if (!strcmp(argv[1],"-profile")) { const char *s = ParseString(argc,argv); setprofile = true; if (!strcmp(s,"a") || !strcmp(s,"A")) { profile = 0; } else if (!strcmp(s,"b") || !strcmp(s,"B")) { profile = 1; } else if (!strcmp(s,"c") || !strcmp(s,"C")) { profile = 2; } else if (!strcmp(s,"d") || !strcmp(s,"D")) { profile = 4; } else { fprintf(stderr,"unknown profile definition %s, only profiles a,b,c and d exist", s); return 20; } } else if (!strcmp(argv[1],"-m")) { maxerror = ParseInt(argc,argv); } else if (!strcmp(argv[1],"-md")) { median = true; argv++; argc--; } else if (!strcmp(argv[1],"-ct")) { median = false; argv++; argc--; } else if (!strcmp(argv[1],"-sm")) { smooth = ParseInt(argc,argv); } else if (!strcmp(argv[1],"-z")) { restart = ParseInt(argc,argv); } else if (!strcmp(argv[1],"-r")) { residuals = true; argv++; argc--; } else if (!strcmp(argv[1],"-R")) { hiddenbits = ParseInt(argc,argv); if (hiddenbits < 0 || hiddenbits > 4) { fprintf(stderr,"JPEG XT allows only between 0 and 4 refinement bits.\n"); return 20; } } else if (!strcmp(argv[1],"-rR")) { riddenbits = ParseInt(argc,argv); } else if (!strcmp(argv[1],"-n")) { writednl = true; argv++; argc--; } else if (!strcmp(argv[1],"-c")) { colortrafo = JPGFLAG_MATRIX_COLORTRANSFORMATION_NONE; argv++; argc--; } else if (!strcmp(argv[1],"-cls")) { colortrafo = JPGFLAG_MATRIX_COLORTRANSFORMATION_LSRCT; argv++; argc--; } else if (!strcmp(argv[1],"-sp")) { separate = true; argv++; argc--; } else if (!strcmp(argv[1],"-s")) { sub = ParseString(argc,argv); } else if (!strcmp(argv[1],"-sr")) { ressub = ParseString(argc,argv); } else if (!strcmp(argv[1],"-ncl")) { noclamp = true; argv++; argc--; } else if (!strcmp(argv[1],"-al")) { alpha = ParseString(argc,argv); } else if (!strcmp(argv[1],"-am")) { alphamode = ParseInt(argc,argv); if (alphamode < 0 || alphamode > 3) { fprintf(stderr,"the alpha mode specified with -am must be between 0 and 3\n"); return 20; } } else if (!strcmp(argv[1],"-ab")) { const char *matte = ParseString(argc,argv); if (sscanf(matte,"%d,%d,%d",&matte_r,&matte_g,&matte_b) != 3) { fprintf(stderr,"-ab expects three numeric arguments separated comma, i.e. r,g,b\n"); return 20; } } else if (!strcmp(argv[1],"-all")) { aserms = true; argv++; argc--; } else if (!strcmp(argv[1],"-alo")) { abypass = true; argv++; argc--; } #if ACCUSOFT_CODE else if (!strcmp(argv[1],"-p")) { lossless = true; argv++; argc--; } #endif else if (!strcmp(argv[1],"-h")) { optimize = true; argv++; argc--; } #if ACCUSOFT_CODE else if (!strcmp(argv[1],"-a")) { accoding = true; argv++; argc--; } else if (!strcmp(argv[1],"-ra")) { raccoding = true; argv++; argc--; } #endif else if (!strcmp(argv[1],"-qv")) { qscan = true; argv++; argc--; } else if (!strcmp(argv[1],"-v")) { progressive = true; argv++; argc--; } else if (!strcmp(argv[1],"-rv")) { rprogressive = true; argv++; argc--; } else if (!strcmp(argv[1],"-rs")) { rsequential = true; argv++; argc--; } else if (!strcmp(argv[1],"-r12")) { resprec = 12; residuals = true; argv++; argc--; } else if (!strcmp(argv[1],"-rl")) { losslessdct = true; argv++; argc--; } else if (!strcmp(argv[1],"-ro")) { dctbypass = true; argv++; argc--; } else if (!strcmp(argv[1],"-xyz")) { xyz = true; argv++; argc--; } else if (!strcmp(argv[1],"-cxyz")) { cxyz = true; argv++; argc--; } else if (!strcmp(argv[1],"-N")) { noiseshaping = true; argv++; argc--; } else if (!strcmp(argv[1],"-ol")) { openloop = true; argv++; argc--; } else if (!strcmp(argv[1],"-U")) { upsample = false; argv++; argc--; } else if (!strcmp(argv[1],"-dz")) { deadzone = true; argv++; argc--; #if ACCUSOFT_CODE } else if (!strcmp(argv[1],"-oz")) { lagrangian = true; argv++; argc--; } else if (!strcmp(argv[1],"-ozn")) { oznew = true; argv++; argc--; } else if (!strcmp(argv[1],"-dr")) { dering = true; argv++; argc--; #endif } else if (!strcmp(argv[1],"-qt")) { tabletype = ParseInt(argc,argv); } else if (!strcmp(argv[1],"-rqt")) { residualtt = ParseInt(argc,argv); } else if (!strcmp(argv[1],"-aqt")) { alphatt = ParseInt(argc,argv); } else if (!strcmp(argv[1],"-arqt")) { residualalphatt = ParseInt(argc,argv); } else if (!strcmp(argv[1],"-aol")) { aopenloop = true; argv++; argc--; } else if (!strcmp(argv[1],"-adz")) { adeadzone = true; argv++; argc--; #if ACCUSOFT_CODE } else if (!strcmp(argv[1],"-aoz")) { alagrangian = true; argv++; argc--; } else if (!strcmp(argv[1],"-adr")) { adering = true; argv++; argc--; #endif } else if (!strcmp(argv[1],"-ldr")) { ldrsource = ParseString(argc,argv); } else if (!strcmp(argv[1],"-l")) { serms = true; argv++; argc--; } else if (!strcmp(argv[1],"-g")) { gamma = ParseDouble(argc,argv); } else if (!strcmp(argv[1],"-gf")) { lsource = ParseString(argc,argv); } else if (!strcmp(argv[1],"-aq")) { alphaquality = ParseInt(argc,argv); } else if (!strcmp(argv[1],"-aQ")) { alphahdrquality = ParseInt(argc,argv); } else if (!strcmp(argv[1],"-aquality")) { alphasplitquality = ParseInt(argc,argv); } else if (!strcmp(argv[1],"-ar")) { alpharesiduals = true; argv++; argc--; } else if (!strcmp(argv[1],"-ar12")) { alpharesiduals = true; aresprec = 12; argv++; argc--; } else if (!strcmp(argv[1],"-aR")) { ahiddenbits = ParseInt(argc,argv); } else if (!strcmp(argv[1],"-arR")) { ariddenbits = ParseInt(argc,argv); } #if ACCUSOFT_CODE else if (!strcmp(argv[1],"-y")) { levels = ParseInt(argc,argv); if (levels == 0 || levels == 1) { // In this mode, the hierarchical model is used for lossless coding levels++; pyramidal = false; } else { pyramidal = true; } } #endif else if (!strcmp(argv[1],"-ls")) { lsmode = ParseInt(argc,argv); } else { fprintf(stderr,"unsupported command line switch %s\n",argv[1]); return 20; } } // // Use a very simplistic quality split. if (splitquality >= 0) { switch(profile) { case 0: break; case 1: break; case 2: case 4: SplitQualityC(splitquality,residuals,quality,hdrquality); break; } } // // The alpha channel is encoded with something that works like part 6. if (alphasplitquality > 0) { SplitQualityC(alphasplitquality,alpharesiduals,alphaquality,alphahdrquality); } if (argc != 3) { if (argc > 3) { fprintf(stderr,"Error in argument parsing, argument %s not understood or parsed correctly.\n" "Run without arguments for a list of command line options.\n\n", argv[1]); exit(20); } PrintUsage(argv[0]); return 5; } if (quality < 0 && lossless == false && lsmode < 0) { Reconstruct(argv[1],argv[2],colortrafo,alpha,upsample); } else { switch(profile) { case 0: fprintf(stderr,"**** Profile A encoding not supported due to patented IPRs.\n"); break; case 1: fprintf(stderr,"**** Profile B encoding not supported due to patented IPRs.\n"); break; case 2: case 4: if (setprofile && ((residuals == false && hiddenbits == false && profile != 4) || profile == 2)) residuals = true; EncodeC(argv[1],ldrsource,argv[2],lsource,quality,hdrquality, tabletype,residualtt,maxerror, colortrafo,lossless,progressive, residuals,optimize,accoding, rsequential,rprogressive,raccoding, qscan,levels,pyramidal,writednl,restart, gamma, lsmode,noiseshaping,serms,losslessdct, openloop,deadzone,lagrangian,dering, xyz,cxyz, hiddenbits,riddenbits,resprec,separate, median,noclamp,smooth,dctbypass, sub,ressub, alpha,alphamode,matte_r,matte_g,matte_b, alpharesiduals,alphaquality,alphahdrquality, alphatt,residualalphatt, ahiddenbits,ariddenbits,aresprec, aopenloop,adeadzone,alagrangian,adering, aserms,abypass); break; } } return 0; }