gax:: gax(): ispushed(false), bpk(Vec2(50,50),Vec2(200,100)) { cfg->SET(spiral_step); cfg->SET(spiral_start); bpk.add_bar(varname(spiral_step),&spiral_step); bpk.add_bar(varname(spiral_start),&spiral_start); bpk.add_bar(varname(how_many),&how_many); funs["gal"]=([this]() { lines.clear(); float inner, arms, startmult, stepmult, spiral_resolution; cfg->SET(spiral_resolution); cfg->SET(arms); cfg->SET(inner); cfg->SET(startmult); cfg->SET(stepmult); auto & o = circs["o"], & i = circs["i"]; float rado = wcenter.y*.9, radi = wcenter.y*inner; confpoint(o,rado,Color::Transparent,wcenter,1); confpoint(i,radi,Color::Transparent,wcenter,1); int many = how_many*arms; for(int i = 0; i < many; ++i) { float shift_angle = float(i)*PI*2/float(many); // cons_print(shift_angle); lines["arch"+strfy(i)]=VertexArray(LinesStrip); auto & thisline = lines["arch"+strfy(i)]; for (int i=0; i< spiral_resolution; i++) { float angle = 2*PI*i/float(spiral_resolution); thisline.append(Vertex(Vec2( wcenter.x+(spiral_start*startmult+stepmult*spiral_step*angle) *cos(angle+shift_angle), wcenter.y+(spiral_start*startmult+stepmult*spiral_step*angle) *sin(angle+shift_angle) ))); } } lb2(lines.size()); }); funs["gal"](); }
// parse Flash vars and create _root variables // Flash vars come in the format: // myvar1=value1,myvar2=value2,myvar3=value3,... void root::set_flash_vars(const gameswf::tu_string& vars) { for (const char* word = vars.c_str(); *word; ) { bool nullDel = false; const char* delimiter = strchr(word, '='); if (delimiter == NULL) { // no value return; } gameswf::tu_string varname(word, int(delimiter - word)); word = delimiter + 1; delimiter = strchr(word, ','); if (delimiter == NULL) { delimiter = vars.c_str() + vars.size(); nullDel = true; } gameswf::tu_string value(word, int(delimiter - word)); get_root_movie()->set_member(varname, value.c_str()); if (nullDel) return; word = delimiter + 1; } }
// // Visit_Member // void Input_Stream_Aggr_Member_Generator:: Visit_Member (const CHAOS::Member & member) { CHAOS::MemberType type = member.ref (); std::string name (member.name ()); if (CHAOS::String::meta == type.type ()) { std::string varname ("val_"); varname += member.name (); this->out_ << "ACE_CString " << varname << ";" << "stream >> " << varname << ";" << "val." << name << " = " << varname << ".c_str ();" << std::endl; } else if (CHAOS::Boolean::meta == type.type ()) { this->out_ << "stream >> CUTS_TCPIP_InputCDR::to_boolean (val." << name << ");"; } else { this->out_ << "stream >> val." << member.name () << ";"; } }
static Array HHVM_FUNCTION(xdebug_get_declared_vars) { if (RuntimeOption::RepoAuthoritative) { raise_error("xdebug_get_declared_vars unsupported in RepoAuthoritative " "mode"); } // Grab the callee function VMRegAnchor _; // Ensure consistent state for vmfp auto func = g_context->getPrevFunc(vmfp()); if (!func) { return Array::Create(); } // Add each named local to the returned array. Note that since this function // is supposed to return all _declared_ variables in scope, which includes // variables that have been unset. auto const numNames = func->numNamedLocals(); PackedArrayInit vars(numNames); for (Id i = 0; i < numNames; ++i) { assert(func->lookupVarId(func->localVarName(i)) == i); String varname(const_cast<StringData*>(func->localVarName(i))); // Skip the internal closure "0Closure" variable if (!s_closure_varname.equal(varname)) { vars.append(varname); } } return vars.toArray(); }
void Printer::Print(const map<string, string>& variables, const char* text) { int size = strlen(text); int pos = 0; // The number of bytes we've written so far. for (int i = 0; i < size; i++) { if (text[i] == '\n') { // Saw newline. If there is more text, we may need to insert an indent // here. So, write what we have so far, including the '\n'. WriteRaw(text + pos, i - pos + 1); pos = i + 1; // Setting this true will cause the next WriteRaw() to insert an indent // first. at_start_of_line_ = true; } else if (text[i] == variable_delimiter_) { // Saw the start of a variable name. // Write what we have so far. WriteRaw(text + pos, i - pos); pos = i + 1; // Find closing delimiter. const char* end = strchr(text + pos, variable_delimiter_); if (end == NULL) { GOOGLE_LOG(DFATAL) << " Unclosed variable name."; end = text + pos; } int endpos = end - text; string varname(text + pos, endpos - pos); if (varname.empty()) { // Two delimiters in a row reduce to a literal delimiter character. WriteRaw(&variable_delimiter_, 1); } else { // Replace with the variable's value. map<string, string>::const_iterator iter = variables.find(varname); if (iter == variables.end()) { GOOGLE_LOG(DFATAL) << " Undefined variable: " << varname; } else { WriteRaw(iter->second.data(), iter->second.size()); } } // Advance past this variable. i = endpos; pos = endpos + 1; } } // Write the rest. WriteRaw(text + pos, size - pos); }
Res FillTemplate(const string& template_string, const map<string, string>& vars, bool tolerate_missing_vars, string* out) { assert(out); out->clear(); const char* p = template_string.c_str(); for (;;) { const char* begin = strstr(p, "${"); if (!begin) { // Done. *out += p; break; } const char* end = strchr(p, '}'); if (!end) { // Done. *out += p; break; } string varname(begin + 2, end - (begin + 2)); if (IsValidVarname(varname)) { // See if we can replace this slot. map<string, string>::const_iterator it = vars.find(varname); if (it == vars.end()) { if (tolerate_missing_vars) { // Pass the variable through, without replacing it. out->append(p, end + 1 - p); p = end + 1; continue; } else { out->clear(); return Res(ERR, "Template contained varname '" + varname + "' but no variable of that name is defined."); } } // Insert text up to the var. out->append(p, begin - p); // Insert the replacement text. out->append(it->second); p = end + 1; } else { // Non-varname character; don't replace anything here. out->append(p, end + 1 - p); p = end + 1; } } return Res(OK); }
cnpy::npz_t cnpy::npz_load(std::string fname) { FILE* fp = fopen(fname.c_str(),"rb"); if(!fp) { throw std::runtime_error("npz_load: Error! Unable to open file "+fname+"!"); } cnpy::npz_t arrays; while(1) { std::vector<char> local_header(30); size_t headerres = fread(&local_header[0],sizeof(char),30,fp); if(headerres != 30) throw std::runtime_error("npz_load: failed fread"); //if we've reached the global header, stop reading if(local_header[2] != 0x03 || local_header[3] != 0x04) break; //read in the variable name uint16_t name_len = *(uint16_t*) &local_header[26]; std::string varname(name_len,' '); size_t vname_res = fread(&varname[0],sizeof(char),name_len,fp); if(vname_res != name_len) throw std::runtime_error("npz_load: failed fread"); //erase the lagging .npy varname.erase(varname.end()-4,varname.end()); //read in the extra field uint16_t extra_field_len = *(uint16_t*) &local_header[28]; if(extra_field_len > 0) { std::vector<char> buff(extra_field_len); size_t efield_res = fread(&buff[0],sizeof(char),extra_field_len,fp); if(efield_res != extra_field_len) throw std::runtime_error("npz_load: failed fread"); } uint16_t compr_method = *reinterpret_cast<uint16_t*>(&local_header[0]+8); uint32_t compr_bytes = *reinterpret_cast<uint32_t*>(&local_header[0]+18); uint32_t uncompr_bytes = *reinterpret_cast<uint32_t*>(&local_header[0]+22); if(compr_method == 0) {arrays[varname] = load_the_npy_file(fp);} else {arrays[varname] = load_the_npz_array(fp,compr_bytes,uncompr_bytes);} } fclose(fp); return arrays; }
Word * varsub(char **s) { Bufblock *b; Word *w; if(**s == '{') /* either ${name} or ${name: A%B==C%D}*/ return expandvar(s); b = varname(s); if(b == 0) return 0; w = varmatch(b->start, s); freebuf(b); return w; }
static Word* expandvar(char **s) { Word *w; Bufblock *buf; Symtab *sym; char *cp, *begin, *end; begin = *s; (*s)++; /* skip the '{' */ buf = varname(s); if (buf == 0) return 0; cp = *s; if (*cp == '}') { /* ${name} variant*/ (*s)++; /* skip the '}' */ w = varmatch(buf->start, s); freebuf(buf); return w; } if (*cp != ':') { SYNERR(-1); fprint(2, "bad variable name <%s>\n", buf->start); freebuf(buf); return 0; } cp++; end = charin(cp , "}"); if(end == 0){ SYNERR(-1); fprint(2, "missing '}': %s\n", begin); Exit(); } *end = 0; *s = end+1; sym = symlook(buf->start, S_VAR, 0); if(sym == 0 || sym->value == 0) w = newword(buf->start); else w = subsub((Word*) sym->value, cp, end); freebuf(buf); return w; }
cnpy::npz_t cnpy::npz_load(std::string fname) { FILE * fp = fopen(fname.c_str(), "rb"); if (!fp) printf("npz_load: Error! Unable to open file %s!\n", fname.c_str()); assert(fp); cnpy::npz_t arrays; while (1) { std::vector<char> local_header(30); size_t headerres = fread(&local_header[0], sizeof(char), 30, fp); if (headerres != 30) throw std::runtime_error("npz_load: failed fread"); // if we've reached the global header, stop reading if (local_header[2] != 0x03 || local_header[3] != 0x04) break; // read in the variable name unsigned short name_len = *(unsigned short *)&local_header[26]; std::string varname(name_len, ' '); size_t vname_res = fread(&varname[0], sizeof(char), name_len, fp); if (vname_res != name_len) throw std::runtime_error("npz_load: failed fread"); // erase the lagging .npy varname.erase(varname.end() - 4, varname.end()); // read in the extra field unsigned short extra_field_len = *(unsigned short *)&local_header[28]; if (extra_field_len > 0) { std::vector<char> buff(extra_field_len); size_t efield_res = fread(&buff[0], sizeof(char), extra_field_len, fp); if (efield_res != extra_field_len) throw std::runtime_error("npz_load: failed fread"); } arrays[varname] = load_the_npy_file(fp); } fclose(fp); return arrays; }
void ScriptController::SetEnvVarSpecial(const char* prefix, const char* name, const char* value) { BString<1024> varname("%s_%s", prefix, name); // Original name SetEnvVar(varname, value); BString<1024> normVarname = *varname; // Replace special characters with "_" and convert to upper case for (char* ptr = normVarname; *ptr; ptr++) { if (strchr(".:*!\"$%&/()=`+~#'{}[]@- ", *ptr)) *ptr = '_'; *ptr = toupper(*ptr); } // Another env var with normalized name (replaced special chars and converted to upper case) if (strcmp(varname, normVarname)) { SetEnvVar(normVarname, value); } }
void nuiMimeMultiPart::Dump(nglOStream* pStream) { nglString varname(_T("MyParam")); nglString value(_T("MyValue")); nglString fileref(_T("MyFile")); nglString filename(_T("prout.txt")); // nglString filename(_T("")); nglString mimetype("plain/text"); const uint8* data = (const uint8*)"YATTA!"; uint32 datalen = strlen((const char*)data); ////////////////////////////////////// nglString str; // prepare start and end boundaries: nglString start; start.CFormat(_T("--%s"), mBoundary.GetChars()); nglString end; end.Add(_T("\n")); end.Add(start); end.Add(_T("--\n")); start.Add(_T("\n")); { std::map<nglString, nglString>::const_iterator it = mVariables.begin(); std::map<nglString, nglString>::const_iterator end = mVariables.end(); while (it != end) { pStream->WriteText(start); str.CFormat(_T("Content-Disposition: form-data; name=\"%s\"\n\n"), it->first.GetChars()); pStream->WriteText(str); pStream->WriteText(it->second); pStream->WriteText(_T("\n")); ++it; } } { for (uint32 i = 0; i < mpFiles.size(); i++) { pStream->WriteText(start); str.CFormat(_T("Content-Disposition: form-data; name=\"%s\"; filename=\"%s\"\n"), mpFiles[i]->mVarName.GetChars(), mpFiles[i]->mFileName.GetChars()); pStream->WriteText(str); str.CFormat(_T("Content-Transfer-Encoding: %s\n"), mpFiles[i]->mContentTransfertEncoding.GetChars()); pStream->WriteText(str); str.CFormat(_T("Content-Type: %s\n\n"), mpFiles[i]->mType.GetChars()); pStream->WriteText(str); pStream->WriteUInt8(&mpFiles[i]->mContents[0], mpFiles[i]->mContents.size()); } } if (mVariables.empty() && mpFiles.empty()) pStream->WriteText(start); pStream->WriteText(end); //mem.WriteUInt8((const uint8*)"\0", 1); // Add final 0 for printf //nglString enc(mem.GetBufferData(), mem.GetSize()); //NGL_OUT(_T("Mime encoded:\n%s\n"), enc.GetChars()); }
void avtMM5FileFormat::PopulateDatabaseMetaData(avtDatabaseMetaData *md, int timeState) { Initialize(); for(MeshNameMap::const_iterator pos = meshNames.begin(); pos != meshNames.end(); ++pos) { int sdims, tdims; sdims = tdims = (int)pos->second.size(); avtMeshMetaData *mmd = new avtMeshMetaData(pos->first, 1, 1, 1, 0, sdims, tdims, AVT_RECTILINEAR_MESH); md->Add(mmd); } // Now iterate over the variables and add them. if(mm5file != 0 && mm5file->ntimes > 0) { if(mm5file->fields_over_time[0].nfields > 0) { for(int i = 0; i < mm5file->fields_over_time[0].nfields; ++i) { const int *dims = mm5file->fields_over_time[0]. fields[i].header.end_index; int ndims = mm5file->fields_over_time[0]. fields[i].header.ndim; std::string varname(mm5file->fields_over_time[0]. fields[i].header.name); if(ndims == 1) { // Add the curve metadata. avtCurveMetaData *cmd = new avtCurveMetaData; cmd->name = varname; cmd->yLabel = varname; cmd->yUnits = std::string(mm5file->fields_over_time[0]. fields[i].header.unit); } else { // Assemble the name of the mesh that the variable is on. std::string meshName; char tmp[100]; for(int d = 0; d < ndims; ++d) { if(d != 0) SNPRINTF(tmp, 100, "x%d", dims[d]); else SNPRINTF(tmp, 100, "%d", dims[d]); meshName += tmp; } // Add the scalar metadata avtScalarMetaData *smd = new avtScalarMetaData( varname, meshName, AVT_ZONECENT); smd->hasUnits = true; smd->units = std::string(mm5file->fields_over_time[0]. fields[i].header.unit); md->Add(smd); } } meshNamesCreated = true; } } }
void dynamic_context::set_environment_variables() { if (!theEnvironmentVariables) theEnvironmentVariables = new EnvVarMap(); #if defined (WIN32) LPTCH envVarsCH = GetEnvironmentStrings(); LPTSTR envVarsSTR = (LPTSTR) envVarsCH; while (*envVarsSTR) { int size = lstrlen(envVarsSTR); char * envVar = new char[size+1]; WideCharToMultiByte( CP_ACP, WC_NO_BEST_FIT_CHARS|WC_COMPOSITECHECK|WC_DEFAULTCHAR, envVarsSTR, size+1, envVar, size+1, NULL, NULL); zstring envVarZS(envVar); int eqPos = envVarZS.find_first_of("="); if (eqPos > 0) { zstring varname(envVarZS.substr(0, eqPos)); zstring varvalue(envVarZS.substr(eqPos+1, size)); if (!varname.empty() || !varvalue.empty()) theEnvironmentVariables->insert(std::pair<zstring, zstring>(varname,varvalue)); } delete envVar; envVarsSTR += lstrlen(envVarsSTR) + 1; } FreeEnvironmentStrings(envVarsCH); #else const char* invalid_char; for (char **env = environ; *env; ++env) { zstring envVarZS(*env); if ((invalid_char = utf8::validate(envVarZS.c_str())) != NULL) throw XQUERY_EXCEPTION(err::FOCH0001, ERROR_PARAMS(zstring("#x") + BUILD_STRING(std::uppercase << std::hex << (static_cast<unsigned int>(*invalid_char)&0xFF)))); if ((invalid_char = utf8::validate(envVarZS.c_str())) != NULL) { throw XQUERY_EXCEPTION(err::FOCH0001, ERROR_PARAMS(zstring("#x") + BUILD_STRING(std::uppercase << std::hex << (static_cast<unsigned int>(*invalid_char) & 0xFF)) )); } int size = envVarZS.size(); int eqPos = envVarZS.find_first_of("="); if (eqPos > 0) { zstring varname(envVarZS.substr(0, eqPos)); zstring varvalue(envVarZS.substr(eqPos+1, size)); if (!varname.empty() || !varvalue.empty()) theEnvironmentVariables->insert(std::pair<zstring, zstring>(varname,varvalue)); } } #endif }
QString GraphDs::fieldName() { return varname(); }
QString GraphDs::fileName() { QString ret = QString("/mnt/x5/snafu/munin/entityfx.com/%1-%2-%3-%4.rrd").arg(host().name()).arg(graphds()).arg(varname()).arg(dsType()); return ret; }
int main(int argc, const char** argv) { // check for correct command line arguments if(argc < 3 || argc > 4){ std::cout << "Usage: " << argv[0] << " infile outfile [namespace]" << std::endl; return 2; } // parse command line const char* iname = argv[1]; const char* oname = argv[2]; const char* ns = ((argc >= 4)?(argv[3]):""); // calculate the char array variable name std::string varname(iname); std::replace_if(varname.begin(), varname.end(), is_not_alnum, '_'); // calculate the namespaces std::vector<std::string> namespaces = split(ns, "::"); /* std::stringstream nss(ns); std::vector<std::string> namespaces; std::string ns_part; while(std::getline(nss, ns_part, ':')){ namespaces.push_back(ns_part); } */ // open input file std::ifstream ifile(iname, std::ios::in | std::ios::binary); if(!ifile.is_open()){ std::cerr << "Unable to open file '" << iname << "'!" << std::endl; return 1; } // open output file std::ofstream ofile(oname, std::ios::out | std::ios::binary); if(!ofile.is_open()){ std::cerr << "Unable to write to file '" << oname << "'!" << std::endl; return 1; } // open namespace brackets for(int i = 0; i < namespaces.size(); i++) { ofile << "namespace " << namespaces[i] << "{" << std::endl; } // write all bytes to the array ofile << "extern const char " << varname << "[] = \""; unsigned long numchars = 0; unsigned char c = ifile.get(); while(ifile.good()){ if(numchars % 20 == 0){ ofile << "\"\n \""; } numchars++; ofile << "\\x" << std::hex << std::setw(2) << std::setfill('0') << (int)c; c = ifile.get(); } ofile << "\";" << std::endl; // write the array length ofile << "extern const unsigned long " << varname << "_len = " << std::dec << std::setw(0) << std::setfill(' ') << numchars << ";" << std::endl; // close namespace brackets for(int i = 0; i < namespaces.size(); i++) { ofile << "}" << std::endl; }; // close files, return success ofile.close(); ifile.close(); return 0; }
parse_stmt(char *tedname, int lno, char *ss,char **cmd, u_char *count) { char fn[32], *arg,*tt; char tbuf[1024]; u_short funidx[64],fuid; int typ,cmlen=0,fncnt=0,argtyp,ii; while (*ss) { if (!(ss=varname(ss,fn))) lper(tedname,lno,"func name expected"); for(fuid=0;fuid<funcno;fuid++) if (!strcmp(fn,func[fuid].funname)) break; if (fuid==funcno) { lper2(tedname,lno,"func %s is not defined",fn); return 0; } ss=skip_spc(ss); if (*ss!='(') lper(tedname,lno,"( expected"); ss++; funidx[fncnt++]=cmlen; argtyp=func[fuid].argtype; tbuf[cmlen++]=fuid; switch (argtyp) { case 0: case 4: case 5: case 6: typ=takearg(tedname, lno, ss,&arg,&tt); if (typ!=0) lper(tedname,lno,"No arg is expected"); break; case 1: typ=takearg(tedname, lno, ss,&arg,&tt); if (typ!=1) lper(tedname, lno, tedname,lno,"integer is expected"); tbuf[cmlen++]=atoi(arg); break; case 2: typ=takearg(tedname, lno, ss,&arg,&tt); if (typ!=2) lper(tedname,lno,"String is expected"); strcpy(&tbuf[cmlen],arg); cmlen+=strlen(arg)+1; break; case 3: /* (string,string) */ typ=takearg(tedname, lno,ss,&arg,&tt); if (typ!=2) lper(tedname,lno,"String is expected"); strcpy(&tbuf[cmlen],arg); cmlen+=strlen(arg)+1; tt=skip_spc(tt); if (*tt!=',') lper(tedname,lno,", is expected"); tt++; typ=takearg(tedname, lno,tt,&arg,&tt); if (typ!=2) lper(tedname,lno,"String is expected"); strcpy(&tbuf[cmlen],arg); cmlen+=strlen(arg)+1; break; case 7: /* (string,string,string) */ typ=takearg(tedname, lno,ss,&arg,&tt); if (typ!=2) lper(tedname,lno,"String is expected"); strcpy(&tbuf[cmlen],arg); cmlen+=strlen(arg)+1; tt=skip_spc(tt); if (*tt!=',') lper(tedname,lno,", is expected"); tt++; typ=takearg(tedname, lno,tt,&arg,&tt); if (typ!=2) lper(tedname,lno,"String is expected"); strcpy(&tbuf[cmlen],arg); cmlen+=strlen(arg)+1; tt=skip_spc(tt); if (*tt!=',') lper(tedname,lno,", is expected"); tt++; typ=takearg(tedname, lno,tt,&arg,&tt); if (typ!=2) lper(tedname,lno,"String is expected"); strcpy(&tbuf[cmlen],arg); cmlen+=strlen(arg)+1; break; case 8: /* int int */ typ=takearg(tedname, lno, ss,&arg,&tt); if (typ!=1) lper(tedname, lno, tedname,lno,"integer is expected"); ii=atoi(arg); memcpy(&tbuf[cmlen],&ii,sizeof(int)); cmlen+=sizeof(int); tt=skip_spc(tt); if (*tt!=',') lper(tedname,lno,", is expected"); tt++; ss=skip_spc(tt); typ=takearg(tedname, lno, ss,&arg,&tt); if (typ!=1) lper(tedname, lno, tedname,lno,"integer is expected"); ii=atoi(arg); memcpy(&tbuf[cmlen],&ii,sizeof(int)); cmlen+=sizeof(int); } ss=skip_spc(tt); if (*ss!=')') lper(tedname,lno," ) expected"); ss++; ss=skip_spc(ss); if (*ss==';') ss++; } if ((*cmd=(char *)malloc(cmlen))==NULL) lper(tedname,lno,"malloc err"); *count=fncnt; memcpy(*cmd,tbuf,cmlen); return 1; }
int main() { randomnessGenerator = new TRandom(); system((string("mkdir -p ")+OUTPUT_FOLDER).c_str()); // ########################### // # Prepare final SFR table # // ########################### vector<string> columns = { "SFR-1ltop", "SFR-Wjets" }; vector<string> listAllSignalRegion = listCutAndCounts; vector<string> listRawRegion = listIndividualCuts; Table tableSFRToBeUsed(columns,listAllSignalRegion); Table tableRawSFR(columns,listRawRegion); columns.clear(); columns = {"NormPeak_1ltop", "NormTail_1ltop", "SFR-1ltop", "NormPeak_Wjets", "NormTail_Wjets", "SFR-Wjets"}; Table tableRawNormValues(columns,listRawRegion); // Create observables RooRealVar var(OBSERVABLE_FOR_FIT,OBSERVABLE_FOR_FIT,0,600) ; string varname(OBSERVABLE_FOR_FIT); FitSetup setup; FitResult res; string conditions; // ######################## // # _____ _____ # // # / __ \ ___ / __ \ # // # | / \/( _ ) | / \/ # // # | | / _ \/\ | # // # | \__/\ (_> < \__/\ # // # \____/\___/\/\____/ # // # # // ######################## std::map<string,Figure> SFR_CC_1ltop_map; std::map<string,Figure> SFR_CC_Wjets_map; //Create histos TH1F h_SF_MTpeak_CC_1ltop ("h_SF_MTpeak_CC_1ltop", "", listIndividualCuts_MTtail.size(), 0, listIndividualCuts_MTtail.size()); TH1F h_SF_MTtail_CC_1ltop ("h_SF_MTtail_CC_1ltop", "", listIndividualCuts_MTtail.size(), 0, listIndividualCuts_MTtail.size()); TH1F h_SFR_CC_1ltop ("h_SFR_CC_1ltop", "", listIndividualCuts_MTtail.size(), 0, listIndividualCuts_MTtail.size()); TH1F h_SF_MTpeak_CC_Wjets ("h_SF_MTpeak_CC_Wjets", "", listIndividualCuts_MTtail.size(), 0, listIndividualCuts_MTtail.size()); TH1F h_SF_MTtail_CC_Wjets ("h_SF_MTtail_CC_Wjets", "", listIndividualCuts_MTtail.size(), 0, listIndividualCuts_MTtail.size()); TH1F h_SFR_CC_Wjets ("h_SFR_CC_Wjets", "", listIndividualCuts_MTtail.size(), 0, listIndividualCuts_MTtail.size()); for(unsigned int i=0;i<listIndividualCuts.size();i++) { cout<<"%%%%%%%%%%%%%%%%%% "<<listIndividualCuts_MTtail[i]<<endl; string label = listIndividualCuts[i]; Figure SFR_1ltop; Figure SFR_Wjets; //MT tail setup.Reset(); conditions="sigRegions_CC_tail"; setup.region=listIndividualCuts_MTtail[i]; setup.varname=varname; setup.varMin=0; setup.varMax=600; //test on Ndata /* vector<int> Ndata = {100,200,500,1000,5000,10000}; //vector<int> Ndata = {100,200};//,500,1000,5000,10000}; */ TFile* file = new TFile("closure.root","RECREATE"); //for(unsigned int c=0;c<Ndata.size();c++){ /* TString dirname; dirname+=Ndata[c]; file->mkdir(dirname.Data()); */ TH1F* h_tt1l_Pull = new TH1F("h_tt1l_Pull", "Pull distrib. SF_1ltop", 30, -3, 3); TH1F* h_Wjets_Pull = new TH1F("h_Wjets_Pull", "Pull distrib. SF_1ltop", 30, -3, 3); TH1F* h_tt1l_uncert = new TH1F("h_tt1l_uncert", "Uncertainty on SF_1ltop", 100, 0, 5); TH1F* h_Wjets_uncert = new TH1F("h_Wjets_uncert", "Uncertainty on SF_1ltop", 100, 0, 1); //setup.Ndata = Ndata[c]; for(int np = 0; np<5000; np++){ res = doFit(setup,conditions); Figure NormTail_1ltop(res.SF_1ltop.first,res.SF_1ltop.second); Figure NormTail_Wjets=Figure(res.SF_Wjets.first,res.SF_Wjets.second); cout<<NormTail_1ltop.Print()<<endl; cout<<NormTail_Wjets.Print()<<endl; h_tt1l_Pull->Fill((res.SF_1ltop.first-1)/res.SF_1ltop.second); h_Wjets_Pull->Fill((res.SF_Wjets.first-1)/res.SF_Wjets.second); h_tt1l_uncert->Fill(res.SF_1ltop.second/res.SF_1ltop.first); h_Wjets_uncert->Fill(res.SF_Wjets.second/res.SF_Wjets.first); //cout<<<<" "<<NormTail_Wjets<<endl; //tableRawNormValues.Set("NormTail_1ltop",listIndividualCuts[i],NormTail_1ltop); //tableRawNormValues.Set("NormTail_Wjets",listIndividualCuts[i],NormTail_Wjets); /* h_SF_MTtail_CC_1ltop.SetBinContent(i+1,res.SF_1ltop.first); h_SF_MTtail_CC_1ltop.SetBinError(i+1,res.SF_1ltop.second); h_SF_MTtail_CC_1ltop.GetXaxis()->SetBinLabel(i+1,label.c_str()); h_SF_MTtail_CC_Wjets.SetBinContent(i+1,res.SF_Wjets.first); h_SF_MTtail_CC_Wjets.SetBinError(i+1,res.SF_Wjets.second); h_SF_MTtail_CC_Wjets.GetXaxis()->SetBinLabel(i+1,label.c_str()); */ } //file->cd(dirname.Data()); file->cd(); h_tt1l_Pull->Write(); h_Wjets_Pull->Write(); h_tt1l_uncert->Write(); h_Wjets_uncert->Write(); file->cd(); //} file->Close(); } //Save plots in roofile TFile fCR1_CC((string(OUTPUT_FOLDER)+"/results_CC.root").c_str(),"RECREATE"); h_SF_MTpeak_CC_1ltop.Write(); h_SF_MTpeak_CC_Wjets.Write(); h_SF_MTtail_CC_1ltop.Write(); h_SF_MTtail_CC_Wjets.Write(); h_SFR_CC_1ltop.Write(); h_SFR_CC_Wjets.Write(); //--------------------------------------------- // Results for C&C //--------------------------------------------- initCutAndCountCuts(); vector<string> cuts; for(unsigned int r=0;r<listCutAndCounts.size();r++) { cuts = listCutAndCounts_cuts[listCutAndCounts[r]]; Figure SFR_CC_1ltop; Figure SFR_CC_Wjets; for(unsigned i=0;i<cuts.size();i++) { cout<<cuts[i]<<" "<<SFR_CC_1ltop_map[cuts[i]].Print()<<endl; if(i == 0) SFR_CC_1ltop = SFR_CC_1ltop_map[cuts[i]]; else SFR_CC_1ltop = Figure(SFR_CC_1ltop.value(), sqrt(pow(SFR_CC_1ltop.error(),2) +pow(SFR_CC_1ltop.value() -SFR_CC_1ltop_map[cuts[i].c_str()].value(),2) )); if(i == 0) SFR_CC_Wjets = SFR_CC_Wjets_map[cuts[i]]; else SFR_CC_Wjets = Figure(SFR_CC_Wjets.value(), sqrt(pow(SFR_CC_Wjets.error(),2) +pow(SFR_CC_Wjets.value() -SFR_CC_Wjets_map[cuts[i].c_str()].value(),2) )); } // Add 20% of uncertainty for fit itself (JES, MC stat. ...) SFR_CC_1ltop *= Figure(1.0,TEMPLATE_FIT_METHOD_UNCERTAINTY); SFR_CC_Wjets *= Figure(1.0,TEMPLATE_FIT_METHOD_UNCERTAINTY); tableSFRToBeUsed.Set("SFR-1ltop",listCutAndCounts[r],SFR_CC_1ltop); tableSFRToBeUsed.Set("SFR-Wjets",listCutAndCounts[r],SFR_CC_Wjets); } tableRawSFR.Print(string(OUTPUT_FOLDER)+"/rawSFR.tab" ,4); tableRawNormValues.Print(string(OUTPUT_FOLDER)+"/rawNormValues.tab" ,4); tableSFRToBeUsed.Print(string(OUTPUT_FOLDER)+"/SF_MTtail.tab",4); tableRawSFR.PrintLatex(string(OUTPUT_FOLDER)+"/SF_MTtail.tex",4); }
// Validate gradients with finite differences. void GPCMOptimization::validateGradients( GPCMOptimizable *model // Model to validate gradients for. ) { // Compute gradient. clearGradients(); double center = model->recompute(true); double centerc = 0.0; packGradients(x,g); // std::cout << x << std::endl; // Optionally compute the constraint gradient. VectorXd cg(g.rows()); if (model->hasConstraint()) { clearGradients(); centerc = model->recomputeConstraint(true); packGradients(x,cg); } // Take samples to evaluate finite differences. VectorXd pt = x; VectorXd fdg(params); VectorXd fdgc(params); for (int i = 0; i < params; i++) { // Evaluate upper and lower values. pt.noalias() = x + VectorXd::Unit(params,i)*FD_EPSILON; unpackVariables(pt); double valp = model->recompute(false); double valpc = model->recomputeConstraint(false); pt.noalias() = x - VectorXd::Unit(params,i)*FD_EPSILON; unpackVariables(pt); double valm = model->recompute(false); double valmc = model->recomputeConstraint(false); fdg(i) = 0.5*(valp-valm)/FD_EPSILON; fdgc(i) = 0.5*(valpc-valmc)/FD_EPSILON; DBPRINTLN("Computed finite difference for dimension " << i << " of " << params << ": " << fdg(i)); } // std::cout << x << std::endl; // Reset variables. unpackVariables(x); // Construct gradient names. std::vector<std::string> varname(x.rows()); for (std::vector<GPCMOptVariable>::iterator itr = variables.begin(); itr != variables.end(); itr++) { for (int i = itr->getIndex(); i < itr->getIndex()+itr->getParamCount(); i++) { varname[i] = itr->getName(); if (itr->getParamCount() > 1) varname[i] += std::string(" ") + boost::lexical_cast<std::string>(i-itr->getIndex()); } } // Print gradients. int idx; DBPRINTLN("True gradient / finite-difference gradient:"); for (int i = 0; i < params; i++) { if (model->hasConstraint()) { DBPRINTLN(std::setw(10) << g(i) << " " << std::setw(10) << fdg(i) << std::setw(10) << cg(i) << " " << std::setw(10) << fdgc(i) << std::setw(10) << "(" << x(i) << ")" << " " << varname[i]); } else { DBPRINTLN(std::setw(10) << g(i) << " " << std::setw(10) << fdg(i) << std::setw(10) << "(" << x(i) << ")" << " " << varname[i]); } } // Check objective gradient. double maxDiff = (g-fdg).array().abs().matrix().maxCoeff(&idx); if (maxDiff >= 0.1) DBWARNING("Gradients appear significantly different!"); DBPRINTLN("Max difference: " << maxDiff); DBPRINTLN("Max difference at index " << idx << ":" << std::endl << std::setw(10) << g(idx) << " " << std::setw(10) << fdg(idx) << " " << varname[idx]); if (model->hasConstraint()) { // Check constraint gradient. maxDiff = (cg-fdgc).array().abs().matrix().maxCoeff(&idx); if (maxDiff >= 0.1) DBWARNING("Constraint gradients appear significantly different!"); DBPRINTLN("Max constraint difference: " << maxDiff); DBPRINTLN("Max constraint difference at index " << idx << ":" << std::endl << std::setw(10) << cg(idx) << " " << std::setw(10) << fdgc(idx) << " " << varname[idx]); } }