Exemple #1
0
void VCS_PROB::reportCSV(const std::string& reportFile)
{
    size_t k;
    size_t istart;

    double vol = 0.0;
    string sName;

    FILE* FP = fopen(reportFile.c_str(), "w");
    if (!FP) {
        plogf("Failure to open file\n");
        exit(EXIT_FAILURE);
    }
    double Temp = T;

    std::vector<double> volPM(nspecies, 0.0);
    std::vector<double> activity(nspecies, 0.0);
    std::vector<double> ac(nspecies, 0.0);
    std::vector<double> mu(nspecies, 0.0);
    std::vector<double> mu0(nspecies, 0.0);
    std::vector<double> molalities(nspecies, 0.0);

    vol = 0.0;
    size_t iK = 0;
    for (size_t iphase = 0; iphase < NPhase; iphase++) {
        istart = iK;
        vcs_VolPhase* volP = VPhaseList[iphase];
        //const Cantera::ThermoPhase *tptr = volP->ptrThermoPhase();
        size_t nSpeciesPhase = volP->nSpecies();
        volPM.resize(nSpeciesPhase, 0.0);
        volP->sendToVCS_VolPM(VCS_DATA_PTR(volPM));

        double TMolesPhase = volP->totalMoles();
        double VolPhaseVolumes = 0.0;
        for (k = 0; k < nSpeciesPhase; k++) {
            iK++;
            VolPhaseVolumes += volPM[istart + k] * mf[istart + k];
        }
        VolPhaseVolumes *= TMolesPhase;
        vol += VolPhaseVolumes;
    }

    fprintf(FP,"--------------------- VCS_MULTIPHASE_EQUIL FINAL REPORT"
            " -----------------------------\n");
    fprintf(FP,"Temperature  = %11.5g kelvin\n", Temp);
    fprintf(FP,"Pressure     = %11.5g Pascal\n", PresPA);
    fprintf(FP,"Total Volume = %11.5g m**3\n", vol);
    fprintf(FP,"Number Basis optimizations = %d\n", m_NumBasisOptimizations);
    fprintf(FP,"Number VCS iterations = %d\n", m_Iterations);

    iK = 0;
    for (size_t iphase = 0; iphase < NPhase; iphase++) {
        istart = iK;

        vcs_VolPhase* volP = VPhaseList[iphase];
        const Cantera::ThermoPhase<doublereal>* tp = volP->ptrThermoPhase();
        string phaseName = volP->PhaseName;
        size_t nSpeciesPhase = volP->nSpecies();
        volP->sendToVCS_VolPM(VCS_DATA_PTR(volPM));
        double TMolesPhase = volP->totalMoles();
        //AssertTrace(TMolesPhase == m_mix->phaseMoles(iphase));
        activity.resize(nSpeciesPhase, 0.0);
        ac.resize(nSpeciesPhase, 0.0);

        mu0.resize(nSpeciesPhase, 0.0);
        mu.resize(nSpeciesPhase, 0.0);
        volPM.resize(nSpeciesPhase, 0.0);
        molalities.resize(nSpeciesPhase, 0.0);

        int actConvention = tp->activityConvention();
        tp->getActivities(VCS_DATA_PTR(activity));
        tp->getActivityCoefficients(VCS_DATA_PTR(ac));
        tp->getStandardChemPotentials(VCS_DATA_PTR(mu0));

        tp->getPartialMolarVolumes(VCS_DATA_PTR(volPM));
        tp->getChemPotentials(VCS_DATA_PTR(mu));
        double VolPhaseVolumes = 0.0;
        for (k = 0; k < nSpeciesPhase; k++) {
            VolPhaseVolumes += volPM[k] * mf[istart + k];
        }
        VolPhaseVolumes *= TMolesPhase;
        vol += VolPhaseVolumes;


        if (actConvention == 1) {
            const Cantera::MolalityVPSSTP* mTP = static_cast<const Cantera::MolalityVPSSTP*>(tp);
            tp->getChemPotentials(VCS_DATA_PTR(mu));
            mTP->getMolalities(VCS_DATA_PTR(molalities));
            tp->getChemPotentials(VCS_DATA_PTR(mu));

            if (iphase == 0) {
                fprintf(FP,"        Name,      Phase,  PhaseMoles,  Mole_Fract, "
                        "Molalities,  ActCoeff,   Activity,"
                        "ChemPot_SS0,   ChemPot,   mole_num,       PMVol, Phase_Volume\n");

                fprintf(FP,"            ,           ,      (kmol),            , "
                        "          ,          ,           ,"
                        "   (J/kmol),  (J/kmol),     (kmol), (m**3/kmol),     (m**3)\n");
            }
            for (k = 0; k < nSpeciesPhase; k++) {
                sName = tp->speciesName(k);
                fprintf(FP,"%12s, %11s, %11.3e, %11.3e, %11.3e, %11.3e, %11.3e,"
                        "%11.3e, %11.3e, %11.3e, %11.3e, %11.3e\n",
                        sName.c_str(),
                        phaseName.c_str(), TMolesPhase,
                        mf[istart + k], molalities[k], ac[k], activity[k],
                        mu0[k]*1.0E-6, mu[k]*1.0E-6,
                        mf[istart + k] * TMolesPhase,
                        volPM[k],  VolPhaseVolumes);
            }

        } else {
            if (iphase == 0) {
                fprintf(FP,"        Name,       Phase,  PhaseMoles,  Mole_Fract,  "
                        "Molalities,   ActCoeff,    Activity,"
                        "  ChemPotSS0,     ChemPot,   mole_num,       PMVol, Phase_Volume\n");

                fprintf(FP,"            ,            ,      (kmol),            ,  "
                        "          ,           ,            ,"
                        "    (J/kmol),    (J/kmol),     (kmol), (m**3/kmol),       (m**3)\n");
            }
            for (k = 0; k < nSpeciesPhase; k++) {
                molalities[k] = 0.0;
            }
            for (k = 0; k < nSpeciesPhase; k++) {
                sName = tp->speciesName(k);
                fprintf(FP,"%12s, %11s, %11.3e, %11.3e, %11.3e, %11.3e, %11.3e, "
                        "%11.3e, %11.3e,% 11.3e, %11.3e, %11.3e\n",
                        sName.c_str(),
                        phaseName.c_str(), TMolesPhase,
                        mf[istart + k],  molalities[k], ac[k],
                        activity[k], mu0[k]*1.0E-6, mu[k]*1.0E-6,
                        mf[istart + k] * TMolesPhase,
                        volPM[k],  VolPhaseVolumes);
            }
        }

#ifdef DEBUG_MODE
        /*
         * Check consistency: These should be equal
         */
        tp->getChemPotentials(VCS_DATA_PTR(m_gibbsSpecies)+istart);
        for (k = 0; k < nSpeciesPhase; k++) {
            if (!vcs_doubleEqual(m_gibbsSpecies[istart+k], mu[k])) {
                fprintf(FP,"ERROR: incompatibility!\n");
                fclose(FP);
                plogf("ERROR: incompatibility!\n");
                exit(EXIT_FAILURE);
            }
        }
#endif
        iK += nSpeciesPhase;
    }
    fclose(FP);
}
Exemple #2
0
double cosmology::getM4rs(double M, double conc){
    return M*mu(4.0)/mu(conc);
}
Exemple #3
0
/**
  * Format a summary of the mixture state for output.
  */
std::string MolalityVPSSTP::report(bool show_thermo) const
{


    char p[800];
    string s = "";
    try {
        if (name() != "") {
            sprintf(p, " \n  %s:\n", name().c_str());
            s += p;
        }
        sprintf(p, " \n       temperature    %12.6g  K\n", temperature());
        s += p;
        sprintf(p, "          pressure    %12.6g  Pa\n", pressure());
        s += p;
        sprintf(p, "           density    %12.6g  kg/m^3\n", density());
        s += p;
        sprintf(p, "  mean mol. weight    %12.6g  amu\n", meanMolecularWeight());
        s += p;

        doublereal phi = electricPotential();
        sprintf(p, "         potential    %12.6g  V\n", phi);
        s += p;

        size_t kk = nSpecies();
        vector_fp x(kk);
        vector_fp molal(kk);
        vector_fp mu(kk);
        vector_fp muss(kk);
        vector_fp acMolal(kk);
        vector_fp actMolal(kk);
        getMoleFractions(&x[0]);
        getMolalities(&molal[0]);
        getChemPotentials(&mu[0]);
        getStandardChemPotentials(&muss[0]);
        getMolalityActivityCoefficients(&acMolal[0]);
        getActivities(&actMolal[0]);

        size_t iHp = speciesIndex("H+");
        if (iHp != npos) {
            double pH = -log(actMolal[iHp]) / log(10.0);
            sprintf(p, "                pH    %12.4g  \n", pH);
            s += p;
        }

        if (show_thermo) {
            sprintf(p, " \n");
            s += p;
            sprintf(p, "                          1 kg            1 kmol\n");
            s += p;
            sprintf(p, "                       -----------      ------------\n");
            s += p;
            sprintf(p, "          enthalpy    %12.6g     %12.4g     J\n",
                    enthalpy_mass(), enthalpy_mole());
            s += p;
            sprintf(p, "   internal energy    %12.6g     %12.4g     J\n",
                    intEnergy_mass(), intEnergy_mole());
            s += p;
            sprintf(p, "           entropy    %12.6g     %12.4g     J/K\n",
                    entropy_mass(), entropy_mole());
            s += p;
            sprintf(p, "    Gibbs function    %12.6g     %12.4g     J\n",
                    gibbs_mass(), gibbs_mole());
            s += p;
            sprintf(p, " heat capacity c_p    %12.6g     %12.4g     J/K\n",
                    cp_mass(), cp_mole());
            s += p;
            try {
                sprintf(p, " heat capacity c_v    %12.6g     %12.4g     J/K\n",
                        cv_mass(), cv_mole());
                s += p;
            } catch (CanteraError& err) {
                err.save();
                sprintf(p, " heat capacity c_v    <not implemented>       \n");
                s += p;
            }
        }

        sprintf(p, " \n");
        s += p;
        if (show_thermo) {
            sprintf(p, "                           X        "
                    "   Molalities         Chem.Pot.    ChemPotSS    ActCoeffMolal\n");
            s += p;
            sprintf(p, "                                    "
                    "                      (J/kmol)      (J/kmol)                 \n");
            s += p;
            sprintf(p, "                     -------------  "
                    "  ------------     ------------  ------------    ------------\n");
            s += p;
            for (size_t k = 0; k < kk; k++) {
                if (x[k] > SmallNumber) {
                    sprintf(p, "%18s  %12.6g     %12.6g     %12.6g   %12.6g   %12.6g\n",
                            speciesName(k).c_str(), x[k], molal[k], mu[k], muss[k], acMolal[k]);
                } else {
                    sprintf(p, "%18s  %12.6g     %12.6g          N/A      %12.6g   %12.6g \n",
                            speciesName(k).c_str(), x[k], molal[k], muss[k], acMolal[k]);
                }
                s += p;
            }
        } else {
            sprintf(p, "                           X"
                    "Molalities\n");
            s += p;
            sprintf(p, "                     -------------"
                    "     ------------\n");
            s += p;
            for (size_t k = 0; k < kk; k++) {
                sprintf(p, "%18s   %12.6g     %12.6g\n",
                        speciesName(k).c_str(), x[k], molal[k]);
                s += p;
            }
        }
    } catch (CanteraError& err) {
        err.save();
    }
    return s;
}
void
JvmtiEventController::clear_frame_pop(JvmtiEnvThreadState *ets, JvmtiFramePop fpop) {
  MutexLockerEx mu(SafepointSynchronize::is_at_safepoint() ? NULL : JvmtiThreadState_lock);
  JvmtiEventControllerPrivate::clear_frame_pop(ets, fpop);
}
Exemple #5
0
void cosmology::init_pe_rho_rdelta_phys_Zhao(double M,double z){

    FILE *mcinp;
    char dirname[100];
    getuuid(dirname);

    char *command;
    command =new char[2000];

    sprintf(command,"mkdir -p %s",dirname);
    system((const char *)command);
    
    char fname[105];
    sprintf(fname,"%s/tmpin",dirname);
    mcinp=fopen(fname,"w");
    //mcinp=fopen("tmpin","w");

    fprintf(mcinp,"aumout\n");
    fprintf(mcinp,"%lg %lg \n",Omega0,Omegal);
    fprintf(mcinp,"1 \n");
    fprintf(mcinp,"%lg \n",h);
    fprintf(mcinp,"%lg \n",sigma8);
    fprintf(mcinp,"%lg \n",ns);
    fprintf(mcinp,"%lg %lg \n",Omegab,theta*2.7);
    fprintf(mcinp,"1 \n");
    fprintf(mcinp,"%lg \n",z);
    fprintf(mcinp,"%lg \n",log10(M));
    fclose(mcinp);

    sprintf(command,"cd %s; PATH=$PATH:.. mandc.x < tmpin >> zhao_log; rm s_aumout; rm sigma_aumout; mv mchistory* fileout; awk '{if(NR!=1)print $1,$2,$3}' fileout > fileout.mvir.mah",dirname);
    system((const char *)command);

    /*
    system("PATH=$PATH:. mandc.x < tmpin >> tmp/zhao_log");
    system("rm s_aumout");
    system("rm sigma_aumout");
    system("mv mchistory* fileout");
    system("awk '{if(NR!=1)print $1,$2,$3}' fileout > fileout.mvir.mah");
    */

    
    /// What we want is a spline with rho_boundary(Rvir(z)) all physical 
    /// It allows us to calculate: \int_{R1}^{R2} 4 pi r^2 dr rho(zc,r)
    /// Rho(Rvir)=rhos/cvir/(1+cvir)^2
    /// rho(Rvir)=Mvir/(4 pi rs^3 mu(cvir) )/cvir/(1+cvir)^2

    double zred,mvir,cvir;
    double *xx,*yy,*zz,*xz,*cc;
    int fillmax=125;
    xx=new double [fillmax];
    yy=new double [fillmax];
    xz=new double [fillmax];
    zz=new double [fillmax];
    cc=new double [fillmax];

    sprintf(fname,"%s/fileout.mvir.mah",dirname);
    FILE *fp=fopen(fname,"r");
    int fill=0;
    for (int i=0;i<fillmax;i++){
        fscanf(fp,"%le %le %le",&zred,&mvir,&cvir);
	if(cvir<0.0 || fill>=fillmax){
	    break;
	}
        /// Obtain Rvir from mvir, convert to physical
        double rvir=rvir_from_mvir(mvir, zred);
        rvir=rvir/(1+zred);
        xx[fillmax-fill-1]=rvir;
        double rs=rvir/cvir;
        yy[fillmax-fill-1]=mvir/( 4*M_PI*pow(rs,3)*mu(cvir)*cvir*pow(1.+cvir,2) )*4*M_PI*rvir*rvir;
        zz[fill]=mvir;
        xz[fill]=zred;
        cc[fill]=cvir;
        fprintf(stdout,"%le %le %le\n",zred,mvir,cvir);
	fill++;
    }
    fclose(fp);

    // Shift the arrays yy and xx
    for(int i=0;i<fill;i++){
	yy[i]=yy[fillmax-fill+i];
	xx[i]=xx[fillmax-fill+i];
    }


    pe_rho_rdelta_phys_Zhao_acc=gsl_interp_accel_alloc ();
    pe_rho_rdelta_phys_Zhao_spline=gsl_spline_alloc(gsl_interp_cspline,fill);
    gsl_spline_init(pe_rho_rdelta_phys_Zhao_spline,xx,yy,fill);
    mah_Zhao_acc=gsl_interp_accel_alloc ();
    mah_Zhao_spline=gsl_spline_alloc(gsl_interp_cspline,fill);
    gsl_spline_init(mah_Zhao_spline,xz,zz,fill);
    cvir_mah_Zhao_acc=gsl_interp_accel_alloc ();
    cvir_mah_Zhao_spline=gsl_spline_alloc(gsl_interp_cspline,fill);
    gsl_spline_init(cvir_mah_Zhao_spline,xz,cc,fill);

    Mvir_for_pe=M;
    z_for_pe=z;
    bool_pe_rho_rdelta_phys_Zhao=true;

    delete []xx;
    delete []yy;
    delete []zz;

    sprintf(command,"rm -rf %s",dirname);
    system((const char *)command);

    delete [] command;

}
Exemple #6
0
int main(int argc, char **argv) {
  unsigned int num_pts = 100;
  unsigned int num_pairs = num_pts / 2.0;
  const double alpha = 3.0;
  const double beta = 10.0;
  const double obs_stddev = 1e-3;

  MPI_Init(&argc, &argv);

  QUESO::FullEnvironment env(MPI_COMM_WORLD, "infinite_dim/inverse_options", "", NULL);

  libMesh::LibMeshInit init(argc, argv);

  // Generate the mesh on which the samples live.
  libMesh::Mesh mesh;
  libMesh::MeshTools::Generation::build_line(mesh, num_pts, 0.0, 1.0, EDGE2);

  // Use a helper object to define some of the properties of our samples
  QUESO::FunctionOperatorBuilder fobuilder;
  fobuilder.order = "FIRST";
  fobuilder.family = "LAGRANGE";
  fobuilder.num_req_eigenpairs = num_pairs;

  // Define the mean of the prior
  QUESO::LibMeshFunction mean(fobuilder, mesh);

  // Define the precision operator of the prior
  QUESO::LibMeshNegativeLaplacianOperator precision(fobuilder, mesh);

  // Define the prior measure
  QUESO::InfiniteDimensionalGaussian mu(env, mean, precision, alpha, beta);

  // Create likelihood object
  Likelihood llhd(obs_stddev);

  // The worst hack in the world ever
  // boost::shared_ptr<LibMeshFunction> lm_draw(boost::static_pointer_cast<LibMeshFunction>(mu.draw()));
  // std::cout << "before zero" << std::endl;
  // lm_draw->equation_systems->get_system<ExplicitSystem>("Function").solution->zero();
  // std::cout << "after zero" << std::endl;

  // Create the options helper object that determines what options to pass to
  // the sampler
  QUESO::InfiniteDimensionalMCMCSamplerOptions opts(env, "");

  // Set the number of iterations to do
  opts.m_num_iters = 1000;

  // Set the frequency with which we save samples
  opts.m_save_freq = 10;

  // Set the RWMH step size
  opts.m_rwmh_step = 0.1;

  // Construct the sampler, and set the name of the output file (will only
  // write HDF5 files)
  QUESO::InfiniteDimensionalMCMCSampler s(env, mu, llhd, &opts);

  for (unsigned int i = 0; i < opts.m_num_iters; i++) {
    s.step();
    if (i % 100 == 0) {
      std::cout << "sampler iteration: " << i << std::endl;
      std::cout << "avg acc prob is: " << s.avg_acc_prob() << std::endl;
      std::cout << "l2 norm is: " << s.llhd_val() << std::endl;
    }
  }

  return 0;
}
void
JvmtiEventController::change_field_watch(jvmtiEvent event_type, bool added) {
  MutexLocker mu(JvmtiThreadState_lock);
  JvmtiEventControllerPrivate::change_field_watch(event_type, added);
}
Exemple #8
0
void ootpu_comparison(TString files, TString var, TString title, int nbins, float low, float high, TString comments="") {

  TChain* chain = new TChain("reduced_tree");
  chain->Add(files);

  TH1::SetDefaultSumw2();

  TH1F* hA = new TH1F("hA",title, nbins, low, high);
  TH1F* hB = new TH1F("hB",title, nbins, low, high);
  TH1F* hC = new TH1F("hC",title, nbins, low, high);
  TH1F* hD = new TH1F("hD",title, nbins, low, high);

  TH1F* hA_l = new TH1F("hA_l",title, nbins, low, high);
  TH1F* hB_l = new TH1F("hB_l",title, nbins, low, high);
  TH1F* hC_l = new TH1F("hC_l",title, nbins, low, high);
  TH1F* hD_l = new TH1F("hD_l",title, nbins, low, high);
  hA->SetStats(0);
  hA->GetYaxis()->SetLabelSize(0.04);
  //hA->GetYaxis()->SetTitleOffset(1.3);
  hA->GetXaxis()->SetTitleOffset(1.1);
  hA->GetXaxis()->SetTitleFont(132);
  hA->GetXaxis()->SetTitleSize(0.042);
  hA->GetXaxis()->SetLabelSize(0.04);
  hA->SetLineWidth(2);

  //  hA->StatOverflows(true);
  //  hB->StatOverflows(true);
  //  hC->StatOverflows(true);
  //  hD->StatOverflows(true);

  int n1(0), n2(0), n3(0), n4(0), n5(0);
  if (files.Contains("20bx25")) {
    n1=5;
    n2=17;
    n3=21;
    n4=25;
    n5=40;
  }
  else if (files.Contains("S14")) {
    n1=0;
    n2=25;
    n3=40;
    n4=55;
    n5=120;
  }
  else { // default: 8 TeV scenario
    n1=0;
    n2=15;
    n3=22;
    n4=32;
    n5=70;
  }


  TString mu("num_gen_muons==1&&muon_reco_match>=0");
  //if (files.Contains("PU_S10")) {
  TString cuts = Form("(%s)&&(eoot_pu>=%d&&eoot_pu<%d)",mu.Data(),n1,n2);
  cout << "Cuts: " << cuts.Data() << endl;
  chain->Project("hA", var, cuts);
  cuts = Form("(%s)&&(loot_pu>=%d&&loot_pu<%d)",mu.Data(),n1,n2);
  chain->Project("hA_l", var, cuts);
  cuts = Form("(%s)&&(eoot_pu>=%d&&eoot_pu<%d)",mu.Data(),n2,n3);
  cout << "Cuts: " << cuts.Data() << endl;
  chain->Project("hB", var, cuts);
  cuts = Form("(%s)&&(loot_pu>=%d&&loot_pu<%d)",mu.Data(),n2,n3);
  chain->Project("hB_l", var, cuts);
  cuts = Form("(%s)&&(eoot_pu>=%d&&eoot_pu<%d)",mu.Data(),n3,n4);
  cout << "Cuts: " << cuts.Data() << endl;
  chain->Project("hC", var, cuts);
  cuts = Form("(%s)&&(loot_pu>=%d&&loot_pu<%d)",mu.Data(),n3,n4);
  chain->Project("hC_l", var, cuts);
  cuts = Form("(%s)&&(eoot_pu>=%d)",mu.Data(),n4);
  cout << "Cuts: " << cuts.Data() << endl;
  chain->Project("hD", var, cuts);
  cuts = Form("(%s)&&(loot_pu>=%d)",mu.Data(),n4);
  chain->Project("hD_l", var, cuts);
  // }
  // else {
  //  }
  
  float avg1(hA->GetMean());
  float avg2(hB->GetMean());
  float avg3(hC->GetMean());
  float avg4(hD->GetMean());

  hA->Scale(1/hA->Integral());
  hB->Scale(1/hB->Integral());
  hC->Scale(1/hC->Integral());
  hD->Scale(1/hD->Integral());

  hA->SetLineColor(1);
  hB->SetLineColor(2);
  hC->SetLineColor(3);
  hD->SetLineColor(4);

  hA->SetLineWidth(2);
  hB->SetLineWidth(2);
  hC->SetLineWidth(2);
  hD->SetLineWidth(2);

  float avg1_l(hA_l->GetMean());
  float avg2_l(hB_l->GetMean());
  float avg3_l(hC_l->GetMean());
  float avg4_l(hD_l->GetMean());

  hA_l->Scale(1/hA_l->Integral());
  hB_l->Scale(1/hB_l->Integral());
  hC_l->Scale(1/hC_l->Integral());
  hD_l->Scale(1/hD_l->Integral());

  hA_l->SetLineColor(12);
  hB_l->SetLineColor(46);
  hC_l->SetLineColor(8);
  hD_l->SetLineColor(7);

  hA_l->SetLineWidth(2);
  hB_l->SetLineWidth(2);
  hC_l->SetLineWidth(2);
  hD_l->SetLineWidth(2);

  TCanvas* c1 = new TCanvas();
  float max = TMath::Max(hA->GetMaximum(), hB->GetMaximum());
  if (hC->GetMaximum()>max) max = hC->GetMaximum();
  if (hD->GetMaximum()>max) max = hD->GetMaximum();

  hA->SetMaximum(max*1.1);
  hA->Draw("hist");
  hB->Draw("hist,same");
  hC->Draw("hist,same");
  hD->Draw("hist,same");
  hA_l->Draw("hist,same");
  hB_l->Draw("hist,same");
  hC_l->Draw("hist,same");
  hD_l->Draw("hist,same");

  TLegend* leg = new TLegend(0.42,0.6,0.9,0.9);
  leg->SetFillStyle(0);
  char label[1000];
  sprintf(label,"%d#leqEarly Ints.<%d (#mu=%3.3f)",n1,n2,avg1);
  leg->AddEntry(hA,label,"lp");
  sprintf(label,"%d#leqEarly Ints.<%d (#mu=%3.3f)",n2,n3,avg2);
  leg->AddEntry(hB,label,"lp");
  sprintf(label,"%d#leqEarly Ints.<%d (#mu=%3.3f)",n3,n4,avg3);
  leg->AddEntry(hC,label,"lp");
  sprintf(label,"Early Ints.>%d (#mu=%3.3f)",n4,avg4);
  leg->AddEntry(hD,label,"lp");
  // leg->Draw();

  TString plotTitle ="relIso_vs_early_and_late_OOTPU_"+var+comments+".pdf";
  c1->Print(plotTitle);

  cout << "Rejection rates" << endl;
  Double_t left(0.), lerror(0.), right(0.), rerror(0.);
  left = hA->IntegralAndError(1,12,lerror);
  right = hA->IntegralAndError(13,31,rerror);
  float rat_error=sqrt((left*left*rerror*rerror+right*right*lerror*lerror)/((left+right)*(left+right)));
  printf("bin1: %3.2f +/- %3.3f\n", left/(left+right),rat_error);
  left = hB->IntegralAndError(1,12,lerror);
  right = hB->IntegralAndError(13,31,rerror);
  rat_error=sqrt((left*left*rerror*rerror+right*right*lerror*lerror)/((left+right)*(left+right)));
  printf("bin2: %3.2f +/- %3.3f\n", left/(left+right),rat_error);
  left = hC->IntegralAndError(1,12,lerror);
  right = hC->IntegralAndError(13,31,rerror);
  rat_error=sqrt((left*left*rerror*rerror+right*right*lerror*lerror)/((left+right)*(left+right)));
  printf("bin3: %3.2f +/- %3.3f\n", left/(left+right),rat_error);
  left = hD->IntegralAndError(1,12,lerror);
  right = hD->IntegralAndError(13,31,rerror);
  rat_error=sqrt((left*left*rerror*rerror+right*right*lerror*lerror)/((left+right)*(left+right)));
  printf("bin4: %3.2f +/- %3.3f\n", left/(left+right),rat_error);
}
Foam::tmp<Foam::volScalarField> Foam::twoPhaseMixtureThermo::nu() const
{
    return mu()/(alpha1()*thermo1_->rho() + alpha2()*thermo2_->rho());
}
Exemple #10
0
int main(int argc, char *argv[]){
  boost_po::options_description options("Allowed options");

  std::string trainfname;
  std::string testfname;
  int get_train_err = 0;
  
  options.add_options()
    ("train", boost_po::value<std::string>(&trainfname)->required(), "train")
    ("test", boost_po::value<std::string>(&testfname)->required(), "test")
    ("terr", boost_po::value<int>(&get_train_err), "get train err");
  boost_po::variables_map options_map;
  boost_po::store(boost_po::parse_command_line(argc, argv, options), options_map);
  boost_po::notify(options_map);

  arma::mat X;
  arma::icolvec Y;
  
  clock_t t;
  std::cout << "start loading " << trainfname << std::endl;
  START_TIMER(t);
  X.load(trainfname, arma::csv_ascii);
  END_TIMER(t, t);

  std::cout << "data matrix loaded, size: " << X.n_rows << ", " << X.n_cols << " time = " << TO_SEC(t) << " sec" << std::endl;

  Y = arma::conv_to<arma::icolvec>::from(X.col(X.n_cols - 1));
  X.shed_col(X.n_cols - 1);

  convert_binary(Y);

  const int32_t num_samples = X.n_rows;
  const int32_t num_features = X.n_cols;

  arma::colvec mu(num_features); //gaussian mean
  arma::mat sigma(num_features, num_features); //gaussian covariance  
  double xi = 2;
  double delta = 1;

  //initialize gaussian parameters
  mu.zeros();
  sigma = sigma.eye()*COV_FAC;

  std::cout << "start inverting sigma" << std::endl;
  
  START_TIMER(t);
  arma::mat sigma_inv = sigma.i();
  END_TIMER(t, t);
  std::cout << "finished inverting, time = " << TO_SEC(t) << " secs" << std::endl;

  clock_t ts;
  std::cout << "starts training" << std::endl;
  START_TIMER(ts);
  
  int iter_cnt = 0;
  while(std::abs(delta) > CONVERGE_THRE){
    
    arma::mat post_sigma_inv;
    arma::mat post_sigma;
    arma::colvec post_mu;
    double xi_sqr;
    double post_xi;
    int32_t i;

    for(i = 0; i < num_samples; i++){
      std::cout << "sample = i = " << i << std::endl;
      arma::colvec x = X.row(i).t();
      std::cout << "x.print()" << std::endl;
      x.print();

      post_sigma_inv = get_post_sigma_inv(xi, x, sigma_inv);
  
      post_sigma = post_sigma_inv.i();
      
      post_mu = get_post_mu(x, sigma_inv, post_sigma, mu, Y(i));
      
      xi_sqr = get_xi_sqr(x, post_sigma, post_mu);
      post_xi = sqrt(xi_sqr);
      
      sigma = post_sigma;
      sigma_inv = post_sigma_inv;
      mu = post_mu;

      delta = post_xi - xi;
      xi = post_xi;
      END_TIMER(t, ts);
      std::cout << "xi = " << xi << " delta = " << delta << " time = " << TO_SEC(t) << " sec" << std::endl;
    }
    ++iter_cnt;
    std::cout << "iteration " << iter_cnt << " done. xi = " << xi << " delta = " << delta << " std::abs(delta) = " << std::abs(delta) << " time = " << TO_SEC(t) << " sec" << std::endl;
  }
  
  END_TIMER(t, ts);
  std::cout << "time = " << TO_SEC(t) << " sec" << std::endl;
  std::cout << " training done" << std::endl;
  std::cout << "xi = " << xi << std::endl;

  arma::mat X_test;
  arma::icolvec Y_test;

  std::cout << "start loading test matrix " << testfname << std::endl;
  START_TIMER(t);
  X_test.load(testfname, arma::csv_ascii);
  END_TIMER(t, t);

  std::cout << "test data matrix loaded, size: " << X_test.n_rows << ", " << X_test.n_cols << " time = " << TO_SEC(t) << " sec" << std::endl;

  Y_test = arma::conv_to<arma::icolvec>::from(X_test.col(X_test.n_cols - 1));
  X_test.shed_col(X_test.n_cols - 1);

  double test_err = classification_error(xi, sigma, sigma_inv, mu, X_test, Y_test);
  std::cout << "test error = " << test_err << std::endl;

  if(get_train_err){
    double train_err = classification_error(xi, sigma, sigma_inv, mu, X, Y);
    std::cout << "train error = " << train_err << std::endl;
  }

  sigma.save(trainfname + ".sigma.out", arma::csv_ascii);
  mu.save(trainfname + ".mu.out", arma::csv_ascii);
  X.save(trainfname + ".out", arma::csv_ascii);
  
}
 Real AnalyticBarrierEngine::muSigma() const {
     return (1 + mu()) * stdDeviation();
 }
Exemple #12
0
moveit::core::JointModelGroup::JointModelGroup(const std::string& group_name,
                                               const srdf::Model::Group &config,
                                               const std::vector<const JointModel*> &unsorted_group_joints,
                                               const RobotModel* parent_model)
  : parent_model_(parent_model)
  , name_(group_name)
  , common_root_(NULL)
  , variable_count_(0)
  , is_contiguous_index_list_(true)
  , is_chain_(false)
  , is_single_dof_(true)
  , config_(config)
{
  // sort joints in Depth-First order
  joint_model_vector_ = unsorted_group_joints;
  std::sort(joint_model_vector_.begin(), joint_model_vector_.end(), OrderJointsByIndex());
  joint_model_name_vector_.reserve(joint_model_vector_.size());
  
  // figure out active joints, mimic joints, fixed joints
  // construct index maps, list of variables
  for (std::size_t i = 0 ; i < joint_model_vector_.size() ; ++i)
  {
    joint_model_name_vector_.push_back(joint_model_vector_[i]->getName());
    joint_model_map_[joint_model_vector_[i]->getName()] = joint_model_vector_[i];
    unsigned int vc = joint_model_vector_[i]->getVariableCount();
    if (vc > 0)
    {
      if (vc > 1)
        is_single_dof_ = false;
      const std::vector<std::string>& name_order = joint_model_vector_[i]->getVariableNames();
      if (joint_model_vector_[i]->getMimic() == NULL)
      {
        active_joint_model_vector_.push_back(joint_model_vector_[i]);
        active_joint_model_name_vector_.push_back(joint_model_vector_[i]->getName());
        active_joint_model_start_index_.push_back(variable_count_);
        active_joint_models_bounds_.push_back(&joint_model_vector_[i]->getVariableBounds());
      }
      else
        mimic_joints_.push_back(joint_model_vector_[i]);
      for (std::size_t j = 0; j < name_order.size(); ++j)
      {
        variable_names_.push_back(name_order[j]);
        variable_names_set_.insert(name_order[j]);
      }
      
      int first_index = joint_model_vector_[i]->getFirstVariableIndex();
      for (std::size_t j = 0; j < name_order.size(); ++j)
      {
        variable_index_list_.push_back(first_index + j);
        joint_variables_index_map_[name_order[j]] = variable_count_ + j;
      }
      joint_variables_index_map_[joint_model_vector_[i]->getName()] = variable_count_;
      
      if (joint_model_vector_[i]->getType() == JointModel::REVOLUTE && 
          static_cast<const RevoluteJointModel*>(joint_model_vector_[i])->isContinuous())
        continuous_joint_model_vector_.push_back(joint_model_vector_[i]);

      variable_count_ += vc;
    }
    else
      fixed_joints_.push_back(joint_model_vector_[i]);
  }
  
  // now we need to find all the set of joints within this group
  // that root distinct subtrees
  for (std::size_t i = 0 ; i < active_joint_model_vector_.size() ; ++i)
  {
    // if we find that an ancestor is also in the group, then the joint is not a root
    if (!includesParent(active_joint_model_vector_[i], this))
      joint_roots_.push_back(active_joint_model_vector_[i]);
  }
  
  // when updating this group within a state, it is useful to know
  // if the full state of a group is contiguous within the full state of the robot
  if (variable_index_list_.empty())
    is_contiguous_index_list_ = false;
  else
    for (std::size_t i = 1 ; i < variable_index_list_.size() ; ++i)
      if (variable_index_list_[i] != variable_index_list_[i - 1] + 1)
      {
        is_contiguous_index_list_ = false;
        break;
      }

  // when updating/sampling a group state only, only mimic joints that have their parent within the group get updated.
  for (std::size_t i = 0 ; i < mimic_joints_.size() ; ++i)
    // if the joint we mimic is also in this group, we will need to do updates when sampling
    if (hasJointModel(mimic_joints_[i]->getMimic()->getName()))
    {
      int src = joint_variables_index_map_[mimic_joints_[i]->getMimic()->getName()];
      int dest = joint_variables_index_map_[mimic_joints_[i]->getName()];
      GroupMimicUpdate mu(src, dest, mimic_joints_[i]->getMimicFactor(), mimic_joints_[i]->getMimicOffset());
      group_mimic_update_.push_back(mu);
    }
  
  // now we need to make another pass for group links (we include the fixed joints here)
  std::set<const LinkModel*> group_links_set;
  for (std::size_t i = 0 ; i < joint_model_vector_.size() ; ++i)
    group_links_set.insert(joint_model_vector_[i]->getChildLinkModel());
  for (std::set<const LinkModel*>::iterator it = group_links_set.begin(); it != group_links_set.end(); ++it)
    link_model_vector_.push_back(*it);
  std::sort(link_model_vector_.begin(), link_model_vector_.end(), OrderLinksByIndex());

  for (std::size_t i = 0 ; i < link_model_vector_.size() ; ++i)
  {
    link_model_map_[link_model_vector_[i]->getName()] = link_model_vector_[i];
    link_model_name_vector_.push_back(link_model_vector_[i]->getName());
    if (!link_model_vector_[i]->getShapes().empty())
    {
      link_model_with_geometry_vector_.push_back(link_model_vector_[i]);
      link_model_with_geometry_name_vector_.push_back(link_model_vector_[i]->getName());
    }
  }
  
  // compute the common root of this group
  if (!joint_roots_.empty())
  {
    common_root_ = joint_roots_[0];
    for (std::size_t i = 1 ; i < joint_roots_.size() ; ++i)
      common_root_ = parent_model->getCommonRoot(joint_roots_[i], common_root_);
  }
  
  // compute updated links
  for (std::size_t i = 0 ; i < joint_roots_.size() ; ++i)
  {
    const std::vector<const LinkModel*> &links = joint_roots_[i]->getDescendantLinkModels();
    updated_link_model_set_.insert(links.begin(), links.end());
  }
  for (std::set<const LinkModel*>::iterator it = updated_link_model_set_.begin(); it != updated_link_model_set_.end(); ++it)
  {
    updated_link_model_name_set_.insert((*it)->getName());
    updated_link_model_vector_.push_back(*it);
    if (!(*it)->getShapes().empty())
    {
      updated_link_model_with_geometry_vector_.push_back(*it);
      updated_link_model_with_geometry_set_.insert(*it);
      updated_link_model_with_geometry_name_set_.insert((*it)->getName());
    }
  }
  std::sort(updated_link_model_vector_.begin(), updated_link_model_vector_.end(), OrderLinksByIndex());
  std::sort(updated_link_model_with_geometry_vector_.begin(), updated_link_model_with_geometry_vector_.end(), OrderLinksByIndex());
  for (std::size_t i = 0; i < updated_link_model_vector_.size(); ++i)
    updated_link_model_name_vector_.push_back(updated_link_model_vector_[i]->getName());
  for (std::size_t i = 0; i < updated_link_model_with_geometry_vector_.size(); ++i)
    updated_link_model_with_geometry_name_vector_.push_back(updated_link_model_with_geometry_vector_[i]->getName());
  
  // check if this group should actually be a chain
  if (joint_roots_.size() == 1 && active_joint_model_vector_.size() > 1)
  {
    bool chain = true;
    // due to our sorting, the joints are sorted in a DF fashion, so looking at them in reverse, 
    // we should always get to the parent.    
    for (std::size_t k = joint_model_vector_.size() - 1 ; k > 0 ; --k)
      if (!jointPrecedes(joint_model_vector_[k], joint_model_vector_[k - 1]))
      {
        chain = false;
        break;
      }
    if (chain)
      is_chain_ = true;
  }
}
Foam::tmp<Foam::scalarField> Foam::fluidThermo::nu(const label patchi) const
{
    return mu(patchi)/rho(patchi);
}
Foam::tmp<Foam::volScalarField> Foam::fluidThermo::nu() const
{
    return mu()/rho();
}
void ViscosityL1L2<EvalT, Traits>::
evaluateFields(typename Traits::EvalData workset)
{
  if (visc_type == CONSTANT){
    for (std::size_t cell=0; cell < workset.numCells; ++cell) {
      for (std::size_t qp=0; qp < numQPs; ++qp) {
        mu(cell,qp) = 1.0; 
      }
    }
  }
  else if (visc_type == GLENSLAW) {
    if (n == 1.0) {
      for (std::size_t cell=0; cell < workset.numCells; ++cell) {
        for (std::size_t qp=0; qp < numQPs; ++qp) {
          mu(cell,qp) = 1.0/A; 
        }
      }
    }
    else if (n == 3.0) {
      if (surf_type == BOX) {
        if (homotopyParam == 0.0) {
          for (std::size_t cell=0; cell < workset.numCells; ++cell) {
            for (std::size_t qp=0; qp < numQPs; ++qp) {
              mu(cell,qp) = pow(A, -1.0/3.0);
           }
         }
       }
        else {
          ScalarT ff = pow(10.0, -10.0*homotopyParam);
          for (std::size_t cell=0; cell < workset.numCells; ++cell) {
            for (std::size_t qp=0; qp < numQPs; ++qp) {
               mu(cell,qp) = epsilonB(cell,qp) + ff; 
               mu(cell,qp) = sqrt(mu(cell,qp)); 
               mu(cell,qp) = pow(A, -1.0/3.0)*pow(mu(cell,qp), -2.0/3.0); 
            }
          }
        }
      }
      else if (surf_type == TESTA) { //ISMIP-HOM Test A
        PHX::MDField<ScalarT,Cell,QuadPoint> q;
        PHX::MDField<ScalarT,Cell,QuadPoint> w;
        PHX::MDField<ScalarT,Cell,QuadPoint> tauPar2;
        PHX::MDField<ScalarT,Cell,QuadPoint> Int;
        for (std::size_t cell=0; cell < workset.numCells; ++cell) {
          for (std::size_t qp=0; qp < numQPs; ++qp) {
             MeshScalarT x = coordVec(cell,qp,0);
             MeshScalarT y = coordVec(cell,qp,1);
             MeshScalarT s = -x*tan(alpha);
             MeshScalarT b = s - 1.0 + 0.5*sin(2.0*pi*x/L)*sin(2.0*pi*y/L);
             MeshScalarT dsdx = -tan(alpha);
             MeshScalarT dsdy = 0.0; 
             Int(cell,qp) = 0.0; 
             q(cell,qp) = 1.0/(2.0*A)*sqrt(epsilonB(cell,qp)); //TO DO: need to put in continuation here 
             for (std::size_t qpZ = 0; qp<numQPsZ; ++qpZ) { //apply Trapezoidal rule to compute integral in z
                MeshScalarT zQP = qpZ*(s-b)/(2.0*numQPsZ); 
                MeshScalarT tauPerp2 = rho*rho*g*g*(s-zQP)*(s-zQP)*(dsdx*dsdx + dsdy*dsdy); 
                MeshScalarT p = 1.0/3.0*tauPerp2;
                w(cell,qp) = pow(q(cell,qp) + sqrt(q(cell,qp)*q(cell,qp) + p*p*p), 1.0/3.0); 
                tauPar2(cell,qp) = (w(cell,qp)-p/(3.0*w(cell,qp)))*(w(cell,qp)-p/(3.0*w(cell,qp))); 
                Int(cell,qp) += 1.0/(tauPerp2 + tauPar2(cell,qp));  
             }
            mu(cell,qp) = 1.0/A*Int(cell,qp); 
          }
        }
      }
    }
  }
}
Exemple #16
0
/** the gateway function */
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
    /* [t, b] = ddm_rand_full(mu, sig2, b_lo, b_up, 
                              delta_t, n[, inv_leak[, seed]]) */

    /* Check argument number */
    if (nlhs != 2) {
        mexErrMsgIdAndTxt("ddm_rand_full:WrongOutputs", 
                          "Wrong number of output arguments");
    }
    if (nrhs < 6) {
        mexErrMsgIdAndTxt("ddm_rand_full:WrongInputs",
                          "Too few input arguments");
    }

    /* Process first 8 arguments */
    if (!MEX_ARGIN_IS_REAL_VECTOR(0))
        mexErrMsgIdAndTxt("ddm_rand_full:WrongInput",
                          "First input argument expected to be a vector");
    if (!MEX_ARGIN_IS_REAL_VECTOR(1))
        mexErrMsgIdAndTxt("ddm_rand_full:WrongInput",
                          "Second input argument expected to be a vector");
    if (!MEX_ARGIN_IS_REAL_VECTOR(2))
        mexErrMsgIdAndTxt("ddm_rand_full:WrongInput",
                          "Third input argument expected to be a vector");
    if (!MEX_ARGIN_IS_REAL_VECTOR(3))
        mexErrMsgIdAndTxt("ddm_rand_full:WrongInput",
                          "Fourth input argument expected to be a vector");
    if (!MEX_ARGIN_IS_REAL_DOUBLE(4))
        mexErrMsgIdAndTxt("ddm_rand_full:WrongInput",
                          "Fifth input argument expected to be a double");
    if (!MEX_ARGIN_IS_REAL_DOUBLE(5))
        mexErrMsgIdAndTxt("ddm_rand_full:WrongInput",
                          "Sixth input argument expected to be a double");
    if (nrhs >= 7 && !MEX_ARGIN_IS_REAL_DOUBLE(6))
        mexErrMsgIdAndTxt("ddm_rand_sym:WrongInput",
                          "Seventh input argument expected to be a double");
    if (nrhs >= 8 && !MEX_ARGIN_IS_REAL_DOUBLE(7))
        mexErrMsgIdAndTxt("ddm_rand_sym:WrongInput",
                          "Eighth input argument expected to be a double");
    int mu_size = std::max(mxGetN(prhs[0]), mxGetM(prhs[0]));
    int sig2_size = std::max(mxGetN(prhs[1]), mxGetM(prhs[1]));
    int b_lo_size = std::max(mxGetN(prhs[2]), mxGetM(prhs[2]));
    int b_up_size = std::max(mxGetN(prhs[3]), mxGetM(prhs[3]));
    ExtArray mu(ExtArray::shared_noowner(mxGetPr(prhs[0])), mu_size);
    ExtArray sig2(ExtArray::shared_noowner(mxGetPr(prhs[1])), sig2_size);
    ExtArray b_lo(ExtArray::shared_noowner(mxGetPr(prhs[2])), b_lo_size);
    ExtArray b_up(ExtArray::shared_noowner(mxGetPr(prhs[3])), b_up_size);
    ExtArray b_lo_deriv = ExtArray::const_array(0.0);
    ExtArray b_up_deriv = ExtArray::const_array(0.0);
    double delta_t = mxGetScalar(prhs[4]);
    int n = (int) mxGetScalar(prhs[5]);
    if (delta_t <= 0.0)
        mexErrMsgIdAndTxt("ddm_rand_full:WrongInput",
                          "delta_t needs to be larger than 0.0");
    if (n <= 0)
        mexErrMsgIdAndTxt("ddm_rand_full:WrongInput",
                          "n needs to be larger than 1");
    bool has_leak = false;
    double inv_leak = 0.0;
    if (nrhs >= 7) {
        inv_leak = mxGetScalar(prhs[6]);
        has_leak = (inv_leak != 0.0);
        if (inv_leak < 0.0)
            mexErrMsgIdAndTxt("ddm_rand_full:WrongInput",
                              "inv_leak needs to be non-negative");
    }
    int rngseed = 0;
    if (nrhs >= 8)
        rngseed = (int) mxGetScalar(prhs[7]);
    if (nrhs > 8)
        mexErrMsgIdAndTxt("ddm_rand_full:WrongInputs",
                          "Too many input arguments");

    /* reserve space for output */
    plhs[0] = mxCreateDoubleMatrix(1, n, mxREAL);
    plhs[1] = mxCreateLogicalMatrix(1, n);
    double* t = mxGetPr(plhs[0]);
    mxLogical* b = mxGetLogicals(plhs[1]);

    /* perform sampling */
    DMBase* dm = nullptr;
    if (has_leak)
        dm = DMBase::create(mu, sig2, b_lo, b_up, b_lo_deriv, b_up_deriv,
                            delta_t, inv_leak);
    else
        dm = DMBase::create(mu, sig2, b_lo, b_up, b_lo_deriv, b_up_deriv,
                            delta_t);
    DMBase::rngeng_t rngeng;
    if (rngseed == 0) rngeng.seed(std::random_device()());
    else rngeng.seed(rngseed);
    for (int i = 0; i < n; ++i) {
        DMSample s = dm->rand(rngeng);
        t[i] = s.t();
        b[i] = s.upper_bound() ? 1 : 0;
    }
    delete dm;
}
void ElasticProblem<dim>::assemble_system ()
{
    QGauss<dim>  quadrature_formula(2);

    FEValues<dim> fe_values (fe, quadrature_formula,
            update_values   | update_gradients |
            update_quadrature_points | update_JxW_values);

    TestESM<dim> test_esm;
    double coef[2] = {1.0, 1.0};
    test_esm .set_coefficient(coef);



    const unsigned int   dofs_per_cell = fe.dofs_per_cell;
    const unsigned int   n_q_points    = quadrature_formula.size();

    FullMatrix<double>   cell_matrix (dofs_per_cell, dofs_per_cell);
    Vector<double>       cell_rhs (dofs_per_cell);

    std::vector<unsigned int> local_dof_indices (dofs_per_cell);

    std::vector<double>     lambda_values (n_q_points);
    std::vector<double>     mu_values (n_q_points);

    ConstantFunction<dim> lambda(1.), mu(1.);

    RightHandSide<dim>      right_hand_side;
    std::vector<Vector<double> > rhs_values (n_q_points,
            Vector<double>(dim));

    typename DoFHandler<dim>::active_cell_iterator cell = dof_handler.begin_active(),
             endc = dof_handler.end();
    for (; cell!=endc; ++cell)
    {
        cell_matrix = 0;
        cell_rhs = 0;

        fe_values.reinit (cell);
        lambda.value_list (fe_values.get_quadrature_points(), lambda_values);
        mu.value_list     (fe_values.get_quadrature_points(), mu_values);

        right_hand_side.vector_value_list (fe_values.get_quadrature_points(),
                rhs_values);
        for (unsigned int i=0; i<dofs_per_cell; ++i)
        {
            const unsigned int
                component_i = fe.system_to_component_index(i).first;

            for (unsigned int j=0; j<dofs_per_cell; ++j)
            {
                const unsigned int
                    component_j = fe.system_to_component_index(j).first;

                //              printf("i = %d, j = %d, res = %f\n", i, j,
                //                      test_esm (i, j, quadrature_formula, fe_values));

                cell_matrix(i,j) += test_esm (i, j,
                        quadrature_formula, fe_values);
                ////
                double res = 0;
                for (unsigned int q_point=0; q_point<n_q_points;
                        ++q_point)
                {
                    //		    cell_matrix(i,j)
                    res
                        +=
                        (
                         (fe_values.shape_grad(i,q_point)[component_i] *
                          fe_values.shape_grad(j,q_point)[component_j] *
                          lambda_values[q_point])
                         +
                         (fe_values.shape_grad(i,q_point)[component_j] *
                          fe_values.shape_grad(j,q_point)[component_i] *
                          mu_values[q_point])
                         +
                         ((component_i == component_j) ?
                          (fe_values.shape_grad(i,q_point) *
                           fe_values.shape_grad(j,q_point) *
                           mu_values[q_point])  :
                          0)
                        )
                        *
                        fe_values.JxW(q_point);
                    ////              printf("res=%f\n", res);

                }
            }
        }
        printf("!!!!!!!!!!!!!\n");

        // Assembling the right hand
        // side is also just as
        // discussed in the
        // introduction:
        for (unsigned int i=0; i<dofs_per_cell; ++i)
        {
            const unsigned int
                component_i = fe.system_to_component_index(i).first;

            for (unsigned int q_point=0; q_point<n_q_points; ++q_point)
                cell_rhs(i) += fe_values.shape_value(i,q_point) *
                    rhs_values[q_point](component_i) *
                    fe_values.JxW(q_point);
        }
        cell->get_dof_indices (local_dof_indices);
        for (unsigned int i=0; i<dofs_per_cell; ++i)
        {
            for (unsigned int j=0; j<dofs_per_cell; ++j)
                system_matrix.add (local_dof_indices[i],
                        local_dof_indices[j],
                        cell_matrix(i,j));

            system_rhs(local_dof_indices[i]) += cell_rhs(i);
        }
    }

    //    hanging_node_constraints.condense (system_matrix);
    //    hanging_node_constraints.condense (system_rhs);
    for (size_t i = 0; i < system_matrix.m(); ++i)
        for (size_t j = 0; j < system_matrix.n(); ++j)
            if (system_matrix .el (i,j))
                printf("system_matrix_old(%d,%d)=%f\n", i,j,system_matrix(i,j));

    std::map<unsigned int,double> boundary_values;
    VectorTools::interpolate_boundary_values (dof_handler,
            0,
            ConstantFunction<dim>(0, dim),// 
            //ZeroFunction<dim>(dim),
            boundary_values);
    MatrixTools::apply_boundary_values (boundary_values,
            system_matrix,
            solution,
            system_rhs);
}
Exemple #18
0
bool Simulation::assembleBogusFrictionProblem( 
        CollidingGroup& collisionGroup,
        bogus::MecheFrictionProblem& mecheProblem, 
        std::vector<unsigned> &globalIds,
        VecXx& vels, 
        VecXx& impulses,
        VecXu& startDofs, 
        VecXu& nDofs )
{

    unsigned nContacts = collisionGroup.second.size();

    std::vector<unsigned> nndofs;
    unsigned nSubsystems = collisionGroup.first.size(); 
    globalIds.reserve( nSubsystems );

    nndofs.resize( nSubsystems );
    nDofs.resize( nSubsystems );
    startDofs.resize( nSubsystems );

    unsigned dofCount = 0;
    unsigned subCount = 0;
    std::vector<unsigned> dofIndices;

    // Computes the number of DOFs per strand and the total number of contacts
    for( IndicesMap::const_iterator it = collisionGroup.first.begin();
         it != collisionGroup.first.end(); 
         ++it )
    {
        startDofs[ subCount ] = dofCount;
        dofIndices.push_back( dofCount );
        const unsigned sIdx = it->first;
        globalIds.push_back( sIdx );
        nDofs[subCount] = m_steppers[sIdx]->m_futureVelocities.rows();
        nndofs[subCount] = m_steppers[sIdx]->m_futureVelocities.rows();
        nContacts += m_externalContacts[sIdx].size();
        dofCount += m_steppers[sIdx]->m_futureVelocities.rows();
        ++subCount;
    }

    if( nContacts == 0 ){
        return false; // needs to be false to break out of solvecollidinggroup if statement
    }

    // Prepare the steppers
#pragma omp parallel for
    for ( unsigned i = 0; i < globalIds.size(); ++i )
    { // make sure steppers are ready for us to read their info/members... solve if not yet solved, reset where necessary
        m_steppers[ globalIds[i] ]->prepareForExternalSolve();
    }

    std::vector < SymmetricBandMatrixSolver<double, 10>* > MassMat;
    MassMat.resize( nSubsystems );

    VecXx forces( dofCount );

    vels.resize( dofCount );
    impulses.resize( nContacts * 3 );
    impulses.setZero();

    VecXx mu( nContacts );

    std::vector < Eigen::Matrix< double, 3, 3 > > E; E.resize( nContacts );

    VecXx u_frees( nContacts * 3 );
    u_frees.setZero();

    int ObjA[ nContacts ];
    int ObjB[ nContacts ];

    std::vector < SparseRowMatx* > H_0; H_0.resize( nContacts );
    std::vector < SparseRowMatx* > H_1; H_1.resize( nContacts );

    unsigned objectId = 0, collisionId = 0, currDof = 0;

    // Setting up objects and adding external constraints
    for ( IndicesMap::const_iterator it = collisionGroup.first.begin(); it != collisionGroup.first.end(); ++it )
    {
        const unsigned sIdx = it->first;
        ImplicitStepper& stepper = *m_steppers[sIdx];

        JacobianSolver *M = &stepper.linearSolver();
        MassMat[ objectId++ ] = M;

        if( m_params.m_alwaysUseNonLinear )
        {
            forces.segment( currDof, stepper.rhs().size() ) = -stepper.rhs();
            currDof += stepper.rhs().size();
        }
        else
        {
            forces.segment( currDof, stepper.impulse_rhs().size() ) = -stepper.impulse_rhs();
            currDof += stepper.impulse_rhs().size();
        }

        CollidingPairs & externalCollisions = m_externalContacts[sIdx];
        for ( unsigned i = 0; i < externalCollisions.size(); ++i, ++collisionId )
        {
            CollidingPair& c = externalCollisions[i];

            mu[ collisionId ] = c.m_mu;
            E [ collisionId ] = c.m_transformationMatrix;
            // u_frees.segment<3>( ( collisionId ) * 3 ) = c.objects.first.freeVel - c.objects.second.freeVel;
            ObjA[ collisionId ] = (int) it->second;
            ObjB[ collisionId ] = -1;
            H_0 [ collisionId ] = c.objects.first.defGrad;
            H_1 [ collisionId ] = NULL;
        }
    }

    // Setting up RodRod constraints
#pragma omp parallel for
    for ( unsigned i = 0; i < collisionGroup.second.size(); ++i )
    {
        CollidingPair& collision = collisionGroup.second[i];
        const int oId1 = collisionGroup.first.find( collision.objects.first.globalIndex )->second;
        const int oId2 = collisionGroup.first.find( collision.objects.second.globalIndex )->second;

        mu[ collisionId + i ] = collision.m_mu;
        E [ collisionId + i ] = collision.m_transformationMatrix;
        // u_frees.segment<3>( ( collisionId + i ) * 3 ) = collision.objects.first.freeVel - collision.objects.second.freeVel;
        ObjA[ collisionId + i ] = oId1;
        ObjB[ collisionId + i ] = oId2;
        H_0 [ collisionId + i ] = collision.objects.first.defGrad;
        H_1 [ collisionId + i ] = collision.objects.second.defGrad;
    }
    assert( collisionId + collisionGroup.second.size() == nContacts );

    mecheProblem.fromPrimal( 
                    nSubsystems,
                    nndofs,
                    MassMat, 
                    forces,
                    nContacts, 
                    mu, 
                    E, 
                    u_frees, // this is what we want the velocity to be given resting contact, set it to zero?
                    ObjA, 
                    ObjB, 
                    H_0, 
                    H_1,
                    dofIndices );

    return true;
}
Exemple #19
0
void print_statistics() {

#ifdef ASSERT

  if (CountRuntimeCalls) {
    extern Histogram *RuntimeHistogram;
    RuntimeHistogram->print();
  }

  if (CountJNICalls) {
    extern Histogram *JNIHistogram;
    JNIHistogram->print();
  }

  if (CountJVMCalls) {
    extern Histogram *JVMHistogram;
    JVMHistogram->print();
  }

#endif

  if (MemProfiling) {
    MemProfiler::disengage();
  }

  if (CITime) {
    CompileBroker::print_times();
  }

#ifdef COMPILER1
  if ((PrintC1Statistics || LogVMOutput || LogCompilation) && UseCompiler) {
    FlagSetting fs(DisplayVMOutput, DisplayVMOutput && PrintC1Statistics);
    Runtime1::print_statistics();
    Deoptimization::print_statistics();
    nmethod::print_statistics();
  }
#endif /* COMPILER1 */

#ifdef COMPILER2
  if ((PrintOptoStatistics || LogVMOutput || LogCompilation) && UseCompiler) {
    FlagSetting fs(DisplayVMOutput, DisplayVMOutput && PrintOptoStatistics);
    Compile::print_statistics();
#ifndef COMPILER1
    Deoptimization::print_statistics();
    nmethod::print_statistics();
#endif //COMPILER1
    SharedRuntime::print_statistics();
    os::print_statistics();
  }

  if (PrintLockStatistics || PrintPreciseBiasedLockingStatistics) {
    OptoRuntime::print_named_counters();
  }

  if (TimeLivenessAnalysis) {
    MethodLiveness::print_times();
  }
#ifdef ASSERT
  if (CollectIndexSetStatistics) {
    IndexSet::print_statistics();
  }
#endif // ASSERT
#endif // COMPILER2
  if (CountCompiledCalls) {
    print_method_invocation_histogram();
  }
  if (ProfileInterpreter || Tier1UpdateMethodData) {
    print_method_profiling_data();
  }
  if (TimeCompiler) {
    COMPILER2_PRESENT(Compile::print_timers();)
  }
  if (TimeCompilationPolicy) {
    CompilationPolicy::policy()->print_time();
  }
  if (TimeOopMap) {
    GenerateOopMap::print_time();
  }
  if (ProfilerCheckIntervals) {
    PeriodicTask::print_intervals();
  }
  if (PrintSymbolTableSizeHistogram) {
    SymbolTable::print_histogram();
  }
  if (CountBytecodes || TraceBytecodes || StopInterpreterAt) {
    BytecodeCounter::print();
  }
  if (PrintBytecodePairHistogram) {
    BytecodePairHistogram::print();
  }

  if (PrintCodeCache) {
    MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
    CodeCache::print();
  }

  if (PrintCodeCache2) {
    MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
    CodeCache::print_internals();
  }

  if (PrintClassStatistics) {
    SystemDictionary::print_class_statistics();
  }
  if (PrintMethodStatistics) {
    SystemDictionary::print_method_statistics();
  }

  if (PrintVtableStats) {
    klassVtable::print_statistics();
    klassItable::print_statistics();
  }
  if (VerifyOops) {
    tty->print_cr("+VerifyOops count: %d", StubRoutines::verify_oop_count());
  }

  print_bytecode_count();
  if (WizardMode) {
    tty->print("allocation stats: ");
    alloc_stats.print();
    tty->cr();
  }

  if (PrintSystemDictionaryAtExit) {
    SystemDictionary::print();
  }

  if (PrintBiasedLockingStatistics) {
    BiasedLocking::print_counters();
  }

#ifdef ENABLE_ZAP_DEAD_LOCALS
#ifdef COMPILER2
  if (ZapDeadCompiledLocals) {
    tty->print_cr("Compile::CompiledZap_count = %d", Compile::CompiledZap_count);
    tty->print_cr("OptoRuntime::ZapDeadCompiledLocals_count = %d", OptoRuntime::ZapDeadCompiledLocals_count);
  }
#endif // COMPILER2
#endif // ENABLE_ZAP_DEAD_LOCALS
}
Real
SymmIsotropicElasticityTensor::shearModulus() const
{
  return mu();
}
// Compute truly enabled events - meaning if the event can and could be
// sent.  An event is truly enabled if it is user enabled on the thread
// or globally user enabled, but only if there is a callback or event hook
// for it and, for field watch and frame pop, one has been set.
// Compute if truly enabled, per thread, per environment, per combination
// (thread x environment), and overall.  These merges are true if any is true.
// True per thread if some environment has callback set and the event is globally
// enabled or enabled for this thread.
// True per environment if the callback is set and the event is globally
// enabled in this environment or enabled for any thread in this environment.
// True per combination if the environment has the callback set and the
// event is globally enabled in this environment or the event is enabled
// for this thread and environment.
//
// All states transitions dependent on these transitions are also handled here.
void
JvmtiEventControllerPrivate::recompute_enabled() {
  assert(Threads::number_of_threads() == 0 || JvmtiThreadState_lock->is_locked(), "sanity check");

  // event enabled for any thread in any environment
  jlong was_any_env_thread_enabled = JvmtiEventController::_universal_global_event_enabled.get_bits();
  jlong any_env_thread_enabled = 0;

  EC_TRACE(("JVMTI [-] # recompute enabled - before " UINT64_FORMAT_X, was_any_env_thread_enabled));

  // compute non-thread-filters events.
  // This must be done separately from thread-filtered events, since some
  // events can occur before any threads exist.
  JvmtiEnvIterator it;
  for (JvmtiEnvBase* env = it.first(); env != NULL; env = it.next(env)) {
    any_env_thread_enabled |= recompute_env_enabled(env);
  }

  // We need to create any missing jvmti_thread_state if there are globally set thread
  // filtered events and there weren't last time
  if (    (any_env_thread_enabled & THREAD_FILTERED_EVENT_BITS) != 0 &&
      (was_any_env_thread_enabled & THREAD_FILTERED_EVENT_BITS) == 0) {
    assert(JvmtiEnv::is_vm_live() || (JvmtiEnv::get_phase()==JVMTI_PHASE_START),
      "thread filtered events should not be enabled when VM not in start or live phase");
    {
      MutexLocker mu(Threads_lock);   //hold the Threads_lock for the iteration
      for (JavaThread *tp = Threads::first(); tp != NULL; tp = tp->next()) {
        // state_for_while_locked() makes tp->is_exiting() check
        JvmtiThreadState::state_for_while_locked(tp);  // create the thread state if missing
      }
    }// release Threads_lock
  }

  // compute and set thread-filtered events
  for (JvmtiThreadState *state = JvmtiThreadState::first(); state != NULL; state = state->next()) {
    any_env_thread_enabled |= recompute_thread_enabled(state);
  }

  // set universal state (across all envs and threads)
  jlong delta = any_env_thread_enabled ^ was_any_env_thread_enabled;
  if (delta != 0) {
    JvmtiExport::set_should_post_field_access((any_env_thread_enabled & FIELD_ACCESS_BIT) != 0);
    JvmtiExport::set_should_post_field_modification((any_env_thread_enabled & FIELD_MODIFICATION_BIT) != 0);
    JvmtiExport::set_should_post_class_load((any_env_thread_enabled & CLASS_LOAD_BIT) != 0);
    JvmtiExport::set_should_post_class_file_load_hook((any_env_thread_enabled & CLASS_FILE_LOAD_HOOK_BIT) != 0);
    JvmtiExport::set_should_post_native_method_bind((any_env_thread_enabled & NATIVE_METHOD_BIND_BIT) != 0);
    JvmtiExport::set_should_post_dynamic_code_generated((any_env_thread_enabled & DYNAMIC_CODE_GENERATED_BIT) != 0);
    JvmtiExport::set_should_post_data_dump((any_env_thread_enabled & DATA_DUMP_BIT) != 0);
    JvmtiExport::set_should_post_class_prepare((any_env_thread_enabled & CLASS_PREPARE_BIT) != 0);
    JvmtiExport::set_should_post_class_unload((any_env_thread_enabled & CLASS_UNLOAD_BIT) != 0);
    JvmtiExport::set_should_post_monitor_contended_enter((any_env_thread_enabled & MONITOR_CONTENDED_ENTER_BIT) != 0);
    JvmtiExport::set_should_post_monitor_contended_entered((any_env_thread_enabled & MONITOR_CONTENDED_ENTERED_BIT) != 0);
    JvmtiExport::set_should_post_monitor_wait((any_env_thread_enabled & MONITOR_WAIT_BIT) != 0);
    JvmtiExport::set_should_post_monitor_waited((any_env_thread_enabled & MONITOR_WAITED_BIT) != 0);
    JvmtiExport::set_should_post_garbage_collection_start((any_env_thread_enabled & GARBAGE_COLLECTION_START_BIT) != 0);
    JvmtiExport::set_should_post_garbage_collection_finish((any_env_thread_enabled & GARBAGE_COLLECTION_FINISH_BIT) != 0);
    JvmtiExport::set_should_post_object_free((any_env_thread_enabled & OBJECT_FREE_BIT) != 0);
    JvmtiExport::set_should_post_resource_exhausted((any_env_thread_enabled & RESOURCE_EXHAUSTED_BIT) != 0);
    JvmtiExport::set_should_post_compiled_method_load((any_env_thread_enabled & COMPILED_METHOD_LOAD_BIT) != 0);
    JvmtiExport::set_should_post_compiled_method_unload((any_env_thread_enabled & COMPILED_METHOD_UNLOAD_BIT) != 0);
    JvmtiExport::set_should_post_vm_object_alloc((any_env_thread_enabled & VM_OBJECT_ALLOC_BIT) != 0);

    // need this if we want thread events or we need them to init data
    JvmtiExport::set_should_post_thread_life((any_env_thread_enabled & NEED_THREAD_LIFE_EVENTS) != 0);

    // If single stepping is turned on or off, execute the VM op to change it.
    if (delta & SINGLE_STEP_BIT) {
      switch (JvmtiEnv::get_phase()) {
      case JVMTI_PHASE_DEAD:
        // If the VM is dying we can't execute VM ops
        break;
      case JVMTI_PHASE_LIVE: {
        VM_ChangeSingleStep op((any_env_thread_enabled & SINGLE_STEP_BIT) != 0);
        VMThread::execute(&op);
        break;
      }
      default:
        assert(false, "should never come here before live phase");
        break;
      }
    }

    // set global truly enabled, that is, any thread in any environment
    JvmtiEventController::_universal_global_event_enabled.set_bits(any_env_thread_enabled);

    // set global should_post_on_exceptions
    JvmtiExport::set_should_post_on_exceptions((any_env_thread_enabled & SHOULD_POST_ON_EXCEPTIONS_BITS) != 0);

  }

  EC_TRACE(("JVMTI [-] # recompute enabled - after " UINT64_FORMAT_X, any_env_thread_enabled));
}
Exemple #22
0
static cv::Mat recoverResponseCurve()
{
  const float lambda = 30.0f;
  constexpr int numSamples = 128;
  cv::Size size = getImage(0).size();
  
  cv::Mat_<float> result(256, 3);
  
  // Sample Pixels
  std::vector<cv::Point> samples(numSamples);
  {
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<> xdis(0, size.width-1);
    std::uniform_int_distribution<> ydis(0, size.height-1);
    for (int i = 0; i < numSamples; ++i) {
      samples[i].x = xdis(gen);
      samples[i].y = ydis(gen);
    }
  }
  if (1) {
    cv::Mat tmp;
    cv::cvtColor(getImage(numImages()/2), tmp, cv::COLOR_YCrCb2BGR);
    tmp = getImage(numImages()/2).clone();
    for (int i = 0; i < numSamples; ++i)
      cv::circle(tmp, samples[i], 10, cv::Scalar(0, 0, 255), 3);
    cv::imshow("samples", tmp);
    //cv::waitKey(0);
  }
  
  // Solve
  for (int channel = 0; channel < 3; ++channel) {
    
    int row = numSamples * numImages() + 1 + 254;
    int col = 256 + numSamples;
    
    cv::Mat_<float> b(row, 1, 0.0f);
    cv::Mat_<float> ma(row, col, 0.0f);
    
    int k = 0;
    for (int i = 0; i < numSamples; ++i) {
      int x = samples[i].x, y = samples[i].y;
      
      for (int j = 0, n = numImages(); j < n; ++j) {
        const cv::Mat& img = getImage(j);
        float exposureTime = getExposureTime(j);
        
        int z = img.at<cv::Vec3b>(y, x)[channel];
        float w = weight(z);
        
        ma.at<float>(k, z) = w;
        ma.at<float>(k, 256+i) = -w;
        b.at<float>(k, 0) = w * std::log(exposureTime);
        
        ++k;
      }
    }
    
    ma.at<float>(k, 128) = 1.0f;
    ++k;
    
    for (int i = 0; i < 254; ++i) {
      float w = weight(i+1);
      
      ma.at<float>(k, i) = lambda * w;
      ma.at<float>(k, i+1) = -2.0f * lambda * w;
      ma.at<float>(k, i+2) = lambda * w;
      
      ++k;
    }
    
    cv::Mat_<float> x(col, 1, 0.0f);
    cv::Mat_<float> mu(row, row), mw(row, col), mv(col, col);
    
    cv::SVD::compute(ma, mw, mu, mv, cv::SVD::MODIFY_A);
    cv::SVD::backSubst(mw, mu, mv, b, x);
    
    // Get Result
    for (int i = 0; i < 256; ++i) {
      result.at<float>(i, channel) = x.at<float>(i, 0);
    }
  }
  
  return result;
}
Exemple #23
0
void cosmology::pevolve_fixed(double cdel, int opt, double z, double
&cdelz, double &fdelz, double zstart){

    double fac;
    if(opt==1){
        fac=pow(cdel*(1.+zstart)/(1.+z),3)/mu(cdel);
    }else if(opt==2){
        fac=pow(cdel,3)/mu(cdel);
        fac=fac*pow(Eofz(zstart)/Eofz(z),2);
        fac=fac*Delta_crit(zstart)/Delta_crit(z);
    }else if(opt==3){
        fac=pow(cdel,3)/mu(cdel);
        fac=fac*pow(Eofz(zstart)/Eofz(z),2);
    }else{
        fprintf(stderr,"Option %d not supported yet, bailing out...",opt);
        exit(100);
    }

    int status;
    int iter = 0, max_iter = 100;
    double res;

    const gsl_root_fsolver_type *T;
    gsl_root_fsolver *s;

    double c_lo = 0.01*cdel, c_hi = 100000.0*cdel;

    gsl_function F;
    march_params p;
    p.fac = fac;

    F.function = &findcmarch;
    F.params = &p;
   
    T = gsl_root_fsolver_brent;
    s = gsl_root_fsolver_alloc (T);
    gsl_root_fsolver_set (s, &F, c_lo, c_hi);

    do
    {
        iter++;
        status = gsl_root_fsolver_iterate (s);
        res = gsl_root_fsolver_root (s);
        c_lo = gsl_root_fsolver_x_lower (s);
        c_hi = gsl_root_fsolver_x_upper (s);
        status = gsl_root_test_interval (c_lo, c_hi,0, 1e-6);

        if (status == GSL_SUCCESS)
        {
            //std::cout<<"# "<<"zcollapse:Brent converged after "<< iter<<" iterations"<<std::endl;
        }


    }while (status == GSL_CONTINUE && iter < max_iter);

    gsl_root_fsolver_free (s);

    cdelz=res;
    fdelz=mu(cdelz)/mu(cdel);

}
AlphaReal MultiThresholdStumpLearner::run() {
	const int numClasses = _pTrainingData->getNumClasses();
	const int numColumns = _pTrainingData->getNumAttributes();

	// set the smoothing value to avoid numerical problem
	// when theta=0.
	setSmoothingVal(1.0 / (AlphaReal) _pTrainingData->getNumExamples() * 0.01);

	vector<sRates> mu(numClasses); // The class-wise rates. See BaseLearner::sRates for more info.

	vector<AlphaReal> tmpV(numClasses); // The class-wise votes/abstentions
	vector<FeatureReal> tmpThresholds(numClasses);
	AlphaReal tmpAlpha;

	AlphaReal bestEnergy = numeric_limits<AlphaReal>::max();
	AlphaReal tmpEnergy;

	StumpAlgorithm<FeatureReal> sAlgo(numClasses);
	sAlgo.initSearchLoop(_pTrainingData);

	int numOfDimensions = _maxNumOfDimensions;
	for (int j = 0; j < numColumns; ++j) {
		// Tricky way to select numOfDimensions columns randomly out of numColumns
		int rest = numColumns - j;
		float r = rand() / static_cast<float> (RAND_MAX);

		if (static_cast<float> (numOfDimensions) / rest > r) {
			--numOfDimensions;
			const pair<vpIterator, vpIterator>
					dataBeginEnd =
							static_cast<SortedData*> (_pTrainingData)->getFileteredBeginEnd(
									j);

			const vpIterator dataBegin = dataBeginEnd.first;
			const vpIterator dataEnd = dataBeginEnd.second;

			sAlgo.findMultiThresholdsWithInit(dataBegin, dataEnd,
					_pTrainingData, tmpThresholds, &mu, &tmpV);

			tmpEnergy = getEnergy(mu, tmpAlpha, tmpV);
			if (tmpEnergy < bestEnergy && tmpAlpha > 0) {
				// Store it in the current algorithm
				// note: I don't really like having so many temp variables
				// but the alternative would be a structure, which would need
				// to be inheritable to make things more consistent. But this would
				// make it less flexible. Therefore, I am still undecided. This
				// might change!

				_alpha = tmpAlpha;
				_v = tmpV;
				_selectedColumn = j;
				_thresholds = tmpThresholds;

				bestEnergy = tmpEnergy;
			}
		}
	}

	return bestEnergy;

}
Exemple #25
0
double cosmology::dMcaustic_dMvir(double mvir0,double z0,double z1,double z2){
    if(!bool_pe_rho_rdelta_phys_Zhao || mvir0!=Mvir_for_pe || z0!=z_for_pe){
        std::cout<<"# Initializing physical density profile for "<<mvir0<<" at z="<<z0<<std::endl<<std::endl;
        init_pe_rho_rdelta_phys_Zhao(mvir0,z0);
    }
    if(z0>z1 || z0>z2){
        std::cout<<"# z0 should be smaller than z1 and z2\n";
        return 0;
    }
    if(z2<z1){
        std::cout<<"# z1 should be smaller than z2\n";
        return 0;
    }
    /// Calculate the total mass evolution
    double Mvir1=gsl_spline_eval(mah_Zhao_spline,z1,mah_Zhao_acc);
    double z1step=pow(10.,log10(1.+z1)+0.2)-1.0;
    double Mvir1_step=gsl_spline_eval(mah_Zhao_spline,z1step,mah_Zhao_acc);
    double dlogMdloga_1=-(log10(Mvir1)-log10(Mvir1_step))/( log10(1.+z1) - log10(1.+z1step) );

    double Mvir2=gsl_spline_eval(mah_Zhao_spline,z2,mah_Zhao_acc);
    double z2step=pow(10.,log10(1.+z2)+0.2)-1.0;
    double Mvir2_step=gsl_spline_eval(mah_Zhao_spline,z2step,mah_Zhao_acc);
    double dlogMdloga_2=-(log10(Mvir2)-log10(Mvir2_step))/( log10(1.+z2) - log10(1.+z2step) );

    //printf("z1:%e z1step:%e z2:%e z2step:%e\n",z1,z1step,z2,z2step);

    //mofz=(Mvir1+Mvir2)/2.;

    /*
    double Rvir1=rvir_from_mvir(Mvir1,z1);
    Rvir1=Rvir1/(1+z1);
    double Rvir2=rvir_from_mvir(Mvir2,z2);
    Rvir2=Rvir2/(1+z2);
    */

    double dMvir=Mvir1-Mvir2;


    // First calculate concentration of these halos
    double conc1= gsl_spline_eval(cvir_mah_Zhao_spline,z1,cvir_mah_Zhao_acc); //conc(Mvir1,z1);
    double conc2= gsl_spline_eval(cvir_mah_Zhao_spline,z2,cvir_mah_Zhao_acc); //conc(Mvir2,z2);

    // Get the c200_mean of these halos
    double c200m_1=getcDel(conc1,z1,200.0);
    double c200m_2=getcDel(conc2,z2,200.0);

    // Normalization factor for the Rt-R200m relation, based on Benedikt's new
    // fitting formulae
    double norm_1=0.42+0.40*Omega(z1);
    double norm_2=0.42+0.40*Omega(z2);

    double c_caustic_1=c200m_1*norm_1*( 1.+2.15*exp(-dlogMdloga_1/1.96) );
    double c_caustic_2=c200m_2*norm_2*( 1.+2.15*exp(-dlogMdloga_2/1.96) );

    double Mcaustic1=Mvir1*mu(c_caustic_1)/mu(conc1);
    double Mcaustic2=Mvir2*mu(c_caustic_2)/mu(conc2);
    //printf("dlogMdloga_1:%e log10 Mvir1:%e z1:%e Mcaustic1:%e dlogMdloga_1:%e log10 Mvir2:%e z2:%e Mcaustic2:%e\n",dlogMdloga_1,log10(Mvir1),z1,Mcaustic1,dlogMdloga_2,log10(Mvir2),z2,Mcaustic2);

    double dMcaustic=(Mcaustic1-Mcaustic2);
    //fprintf(stderr,"# Mvir1:%e Mvir2:%e Mpe:%e dMvir:%e M4rs1:%e M4rs2:%e dM4rs:%e\n",Mvir1,Mvir2,Mpe,dMvir,M4rs1,M4rs2,dM4rs);

    if(dMcaustic<0)
        return -1.0;
    else
        return dMcaustic/dMvir;
}
std::string ThermoPhase::report(bool show_thermo, doublereal threshold) const
{
    fmt::MemoryWriter b;
    try {
        if (name() != "") {
            b.write("\n  {}:\n", name());
        }
        b.write("\n");
        b.write("       temperature    {:12.6g}  K\n", temperature());
        b.write("          pressure    {:12.6g}  Pa\n", pressure());
        b.write("           density    {:12.6g}  kg/m^3\n", density());
        b.write("  mean mol. weight    {:12.6g}  amu\n", meanMolecularWeight());

        doublereal phi = electricPotential();
        if (phi != 0.0) {
            b.write("         potential    {:12.6g}  V\n", phi);
        }
        if (show_thermo) {
            b.write("\n");
            b.write("                          1 kg            1 kmol\n");
            b.write("                       -----------      ------------\n");
            b.write("          enthalpy    {:12.5g}     {:12.4g}     J\n",
                    enthalpy_mass(), enthalpy_mole());
            b.write("   internal energy    {:12.5g}     {:12.4g}     J\n",
                    intEnergy_mass(), intEnergy_mole());
            b.write("           entropy    {:12.5g}     {:12.4g}     J/K\n",
                    entropy_mass(), entropy_mole());
            b.write("    Gibbs function    {:12.5g}     {:12.4g}     J\n",
                    gibbs_mass(), gibbs_mole());
            b.write(" heat capacity c_p    {:12.5g}     {:12.4g}     J/K\n",
                    cp_mass(), cp_mole());
            try {
                b.write(" heat capacity c_v    {:12.5g}     {:12.4g}     J/K\n",
                        cv_mass(), cv_mole());
            } catch (NotImplementedError&) {
                b.write(" heat capacity c_v    <not implemented>       \n");
            }
        }

        vector_fp x(m_kk);
        vector_fp y(m_kk);
        vector_fp mu(m_kk);
        getMoleFractions(&x[0]);
        getMassFractions(&y[0]);
        getChemPotentials(&mu[0]);
        int nMinor = 0;
        doublereal xMinor = 0.0;
        doublereal yMinor = 0.0;
        b.write("\n");
        if (show_thermo) {
            b.write("                           X     "
                    "            Y          Chem. Pot. / RT\n");
            b.write("                     -------------     "
                    "------------     ------------\n");
            for (size_t k = 0; k < m_kk; k++) {
                if (abs(x[k]) >= threshold) {
                    if (abs(x[k]) > SmallNumber) {
                        b.write("{:>18s}   {:12.6g}     {:12.6g}     {:12.6g}\n",
                                speciesName(k), x[k], y[k], mu[k]/RT());
                    } else {
                        b.write("{:>18s}   {:12.6g}     {:12.6g}\n",
                                speciesName(k), x[k], y[k]);
                    }
                } else {
                    nMinor++;
                    xMinor += x[k];
                    yMinor += y[k];
                }
            }
        } else {
            b.write("                           X                 Y\n");
            b.write("                     -------------     ------------\n");
            for (size_t k = 0; k < m_kk; k++) {
                if (abs(x[k]) >= threshold) {
                    b.write("{:>18s}   {:12.6g}     {:12.6g}\n",
                            speciesName(k), x[k], y[k]);
                } else {
                    nMinor++;
                    xMinor += x[k];
                    yMinor += y[k];
                }
            }
        }
        if (nMinor) {
            b.write("     [{:+5d} minor]   {:12.6g}     {:12.6g}\n",
                    nMinor, xMinor, yMinor);
        }
    } catch (CanteraError& err) {
        return b.str() + err.what();
    }
    return b.str();
}
double ChLcpIterativePCG::Solve(
					ChLcpSystemDescriptor& sysd		///< system description with constraints and variables	
					)
{
	std::vector<ChLcpConstraint*>& mconstraints = sysd.GetConstraintsList();
	std::vector<ChLcpVariables*>&  mvariables	= sysd.GetVariablesList();

	tot_iterations = 0;
	double maxviolation = 0.;


	// Update auxiliary data in all constraints before starting,
	// that is: g_i=[Cq_i]*[invM_i]*[Cq_i]' and  [Eq_i]=[invM_i]*[Cq_i]'
	for (unsigned int ic = 0; ic< mconstraints.size(); ic++)
		mconstraints[ic]->Update_auxiliary();


	// Allocate auxiliary vectors;
	
	int nc = sysd.CountActiveConstraints();
	if (verbose) GetLog() <<"\n-----Projected CG, solving nc=" << nc << "unknowns \n";

	ChMatrixDynamic<> ml(nc,1);
	ChMatrixDynamic<> mb(nc,1);
	ChMatrixDynamic<> mu(nc,1);
	ChMatrixDynamic<> mp(nc,1);
	ChMatrixDynamic<> mw(nc,1);
	ChMatrixDynamic<> mz(nc,1);
	ChMatrixDynamic<> mNp(nc,1);
	ChMatrixDynamic<> mtmp(nc,1);

	double graddiff= 0.00001; // explorative search step for gradient


	// ***TO DO*** move the following thirty lines in a short function ChLcpSystemDescriptor::ShurBvectorCompute() ?

	// Compute the b_shur vector in the Shur complement equation N*l = b_shur
	// with 
	//   N_shur  = D'* (M^-1) * D
	//   b_shur  = - c + D'*(M^-1)*k = b_i + D'*(M^-1)*k
	// but flipping the sign of lambdas,  b_shur = - b_i - D'*(M^-1)*k
	// Do this in three steps:
	
	// Put (M^-1)*k    in  q  sparse vector of each variable..
	for (unsigned int iv = 0; iv< mvariables.size(); iv++)
		if (mvariables[iv]->IsActive())
			mvariables[iv]->Compute_invMb_v(mvariables[iv]->Get_qb(), mvariables[iv]->Get_fb()); // q = [M]'*fb 

	// ...and now do  b_shur = - D' * q  ..
	int s_i = 0;
	for (unsigned int ic = 0; ic< mconstraints.size(); ic++)
		if (mconstraints[ic]->IsActive())
		{
			mb(s_i, 0) = - mconstraints[ic]->Compute_Cq_q();
			++s_i;
		}

	// ..and finally do   b_shur = b_shur - c
	sysd.BuildBiVector(mtmp);	// b_i   =   -c   = phi/h 
	mb.MatrDec(mtmp);  


		// Optimization: backup the  q  sparse data computed above, 
		// because   (M^-1)*k   will be needed at the end when computing primals.
	ChMatrixDynamic<> mq; 
	sysd.FromVariablesToVector(mq, true);	



	// Initialize lambdas
	if (warm_start)
		sysd.FromConstraintsToVector(ml);
	else
		ml.FillElem(0);

	// Initial projection of ml   ***TO DO***?
	// ...


	std::vector<bool> en_l(nc);
	// Initially all constraints are enabled
	for (int ie= 0; ie < nc; ie++)
		en_l[ie] = true;


	// u = -N*l+b 
	sysd.ShurComplementProduct(mu, &ml, &en_l);		// 1)  u = N*l ...        #### MATR.MULTIPLICATION!!!###
	mu.MatrNeg();								// 2)  u =-N*l
	mu.MatrInc(mb);								// 3)  u =-N*l+b
	mp = mu;
	

	//
	// THE LOOP
	//

	std::vector<double> f_hist;

	for (int iter = 0; iter < max_iterations; iter++)
	{
		// alpha =  u'*p / p'*N*p 
		sysd.ShurComplementProduct(mNp, &mp, &en_l);// 1)  Np = N*p ...    #### MATR.MULTIPLICATION!!!###
		double pNp = mp.MatrDot(&mp,&mNp);			// 2)  pNp = p'*N*p
		double up =  mu.MatrDot(&mu,&mp);			// 3)  up = u'*p
		double alpha = up/pNp;						// 4)  alpha =  u'*p / p'*N*p 

		if (fabs(pNp)<10e-10) GetLog() << "Rayleygh quotient pNp breakdown \n";

		// l = l + alpha * p;
		mtmp.CopyFromMatrix(mp);
		mtmp.MatrScale(alpha);
		ml.MatrInc(mtmp);

		double maxdeltalambda = mtmp.NormInf();

		// l = Proj(l)
		sysd.ConstraintsProject(ml);				// 5) l = P(l) 

		// u = -N*l+b 
		sysd.ShurComplementProduct(mu, &ml, 0);		// 6)  u = N*l ...        #### MATR.MULTIPLICATION!!!###
		mu.MatrNeg();								// 7)  u =-N*l
		mu.MatrInc(mb);								// 8)  u =-N*l+b

		// w = (Proj(l+lambda*u) -l) /lambda;
		mw.CopyFromMatrix(mu);
		mw.MatrScale(graddiff);
		mw.MatrInc(ml);
		sysd.ConstraintsProject(mw);				// 9) w = P(l+lambda*u) ...
		mw.MatrDec(ml);
		mw.MatrScale(1.0/graddiff);					//10) w = (P(l+lambda*u)-l)/lambda ...

		// z = (Proj(l+lambda*p) -l) /lambda;
		mz.CopyFromMatrix(mp);
		mz.MatrScale(graddiff);
		mz.MatrInc(ml);
		sysd.ConstraintsProject(mz);				//11) z = P(l+lambda*u) ...
		mz.MatrDec(ml);
		mz.MatrScale(1.0/graddiff);					//12) z = (P(l+lambda*u)-l)/lambda ...

		// beta = w'*Np / pNp;
		double wNp = mw.MatrDot(&mw, &mNp);
		double beta = wNp / pNp;

		// p = w + beta * z;
		mp.CopyFromMatrix(mz);
		mp.MatrScale(beta);
		mp.MatrInc(mw);

		// METRICS - convergence, plots, etc
		double maxd			  = mu.NormInf();  // ***TO DO***  should be max violation, but just for test...
			
		// For recording into correction/residuals/violation history, if debugging
		if (this->record_violation_history)
			AtIterationEnd(maxd, maxdeltalambda, iter);

		tot_iterations++;
	}
	

	// Resulting DUAL variables:
	// store ml temporary vector into ChLcpConstraint 'l_i' multipliers
	sysd.FromVectorToConstraints(ml); 


	// Resulting PRIMAL variables:
	// compute the primal variables as   v = (M^-1)(k + D*l) 

		// v = (M^-1)*k  ...    (by rewinding to the backup vector computed ad the beginning)
	sysd.FromVectorToVariables(mq);


		// ... + (M^-1)*D*l     (this increment and also stores 'qb' in the ChLcpVariable items)
	for (unsigned int ic = 0; ic < mconstraints.size(); ic++)
	{	
		if (mconstraints[ic]->IsActive())
			mconstraints[ic]->Increment_q( mconstraints[ic]->Get_l_i() );
	}
	

	if (verbose) GetLog() <<"-----\n";

	return maxviolation;

}
RooWorkspace* makeInvertedANFit(TTree* tree, float forceSigma=-1, bool constrainMu=false, float forceMu=-1) {
  RooWorkspace *ws = new RooWorkspace("ws","");

  std::vector< TString (*)(TString, RooRealVar&, RooWorkspace&) > bkgPdfList;
  bkgPdfList.push_back(makeSingleExp);
  bkgPdfList.push_back(makeDoubleExp);
#if DEBUG==0
  //bkgPdfList.push_back(makeTripleExp);
  bkgPdfList.push_back(makeModExp);
  bkgPdfList.push_back(makeSinglePow);
  bkgPdfList.push_back(makeDoublePow);
  bkgPdfList.push_back(makePoly2);
  bkgPdfList.push_back(makePoly3);
#endif



  RooRealVar mgg("mgg","m_{#gamma#gamma}",103,160,"GeV");
  mgg.setBins(38);

  mgg.setRange("sideband_low", 103,120);
  mgg.setRange("sideband_high",131,160);
  mgg.setRange("signal",120,131);

  RooRealVar MR("MR","",0,3000,"GeV");
  MR.setBins(60);
  
  RooRealVar Rsq("t1Rsq","",0,1,"GeV");
  Rsq.setBins(20);

  RooRealVar hem1_M("hem1_M","",-1,2000,"GeV");
  hem1_M.setBins(40);

  RooRealVar hem2_M("hem2_M","",-1,2000,"GeV");
  hem2_M.setBins(40);

  RooRealVar ptgg("ptgg","p_{T}^{#gamma#gamma}",0,500,"GeV");
  ptgg.setBins(50);

  RooDataSet data("data","",tree,RooArgSet(mgg,MR,Rsq,hem1_M,hem2_M,ptgg));

  RooDataSet* blind_data = (RooDataSet*)data.reduce("mgg<121 || mgg>130");

  std::vector<TString> tags;
  //fit many different background models
  for(auto func = bkgPdfList.begin(); func != bkgPdfList.end(); func++) {
    TString tag = (*func)("bonly",mgg,*ws);
    tags.push_back(tag);
    ws->pdf("bonly_"+tag+"_ext")->fitTo(data,RooFit::Strategy(0),RooFit::Extended(kTRUE),RooFit::Range("sideband_low,sideband_high"));
    RooFitResult* bres = ws->pdf("bonly_"+tag+"_ext")->fitTo(data,RooFit::Strategy(2),RooFit::Save(kTRUE),RooFit::Extended(kTRUE),RooFit::Range("sideband_low,sideband_high"));
    bres->SetName(tag+"_bonly_fitres");
    ws->import(*bres);

    //make blinded fit
    RooPlot *fmgg_b = mgg.frame();
    blind_data->plotOn(fmgg_b,RooFit::Range("sideband_low,sideband_high"));
    TBox blindBox(121,fmgg_b->GetMinimum()-(fmgg_b->GetMaximum()-fmgg_b->GetMinimum())*0.015,130,fmgg_b->GetMaximum());
    blindBox.SetFillColor(kGray);
    fmgg_b->addObject(&blindBox);
    ws->pdf("bonly_"+tag+"_ext")->plotOn(fmgg_b,RooFit::LineColor(kRed),RooFit::Range("Full"),RooFit::NormRange("sideband_low,sideband_high"));
    fmgg_b->SetName(tag+"_blinded_frame");
    ws->import(*fmgg_b);
    delete fmgg_b;
    

    //set all the parameters constant
    RooArgSet* vars = ws->pdf("bonly_"+tag)->getVariables();
    RooFIter iter = vars->fwdIterator();
    RooAbsArg* a;
    while( (a = iter.next()) ){
      if(string(a->GetName()).compare("mgg")==0) continue;
      static_cast<RooRealVar*>(a)->setConstant(kTRUE);
    }

    //make the background portion of the s+b fit
    (*func)("b",mgg,*ws);

    RooRealVar sigma(tag+"_s_sigma","",5,0,100);
    if(forceSigma!=-1) {
      sigma.setVal(forceSigma);
      sigma.setConstant(true);
    }
    RooRealVar mu(tag+"_s_mu","",126,120,132);
    if(forceMu!=-1) {
      mu.setVal(forceMu);
      mu.setConstant(true);
    }
    RooGaussian sig(tag+"_sig_model","",mgg,mu,sigma);
    RooRealVar Nsig(tag+"_sb_Ns","",5,0,100);
    RooRealVar Nbkg(tag+"_sb_Nb","",100,0,100000);
    

    RooRealVar HiggsMass("HiggsMass","",125.1);
    RooRealVar HiggsMassError("HiggsMassError","",0.24);
    RooGaussian HiggsMassConstraint("HiggsMassConstraint","",mu,HiggsMass,HiggsMassError);


    RooAddPdf fitModel(tag+"_sb_model","",RooArgList( *ws->pdf("b_"+tag), sig ),RooArgList(Nbkg,Nsig));

    RooFitResult* sbres;
    RooAbsReal* nll;
    if(constrainMu) {
      fitModel.fitTo(data,RooFit::Strategy(0),RooFit::Extended(kTRUE),RooFit::ExternalConstraints(RooArgSet(HiggsMassConstraint)));
      sbres = fitModel.fitTo(data,RooFit::Strategy(2),RooFit::Save(kTRUE),RooFit::Extended(kTRUE),RooFit::ExternalConstraints(RooArgSet(HiggsMassConstraint)));
      nll = fitModel.createNLL(data,RooFit::NumCPU(4),RooFit::Extended(kTRUE),RooFit::ExternalConstraints(RooArgSet(HiggsMassConstraint)));
    } else {
      fitModel.fitTo(data,RooFit::Strategy(0),RooFit::Extended(kTRUE));
      sbres = fitModel.fitTo(data,RooFit::Strategy(2),RooFit::Save(kTRUE),RooFit::Extended(kTRUE));
      nll = fitModel.createNLL(data,RooFit::NumCPU(4),RooFit::Extended(kTRUE));
    }
    sbres->SetName(tag+"_sb_fitres");
    ws->import(*sbres);
    ws->import(fitModel);

    RooPlot *fmgg = mgg.frame();
    data.plotOn(fmgg);
    fitModel.plotOn(fmgg);
    ws->pdf("b_"+tag+"_ext")->plotOn(fmgg,RooFit::LineColor(kRed),RooFit::Range("Full"),RooFit::NormRange("Full"));
    fmgg->SetName(tag+"_frame");
    ws->import(*fmgg);
    delete fmgg;


    RooMinuit(*nll).migrad();

    RooPlot *fNs = Nsig.frame(0,25);
    fNs->SetName(tag+"_Nsig_pll");
    RooAbsReal *pll = nll->createProfile(Nsig);
    //nll->plotOn(fNs,RooFit::ShiftToZero(),RooFit::LineColor(kRed));
    pll->plotOn(fNs);
    ws->import(*fNs);

    delete fNs;

    RooPlot *fmu = mu.frame(125,132);
    fmu->SetName(tag+"_mu_pll");
    RooAbsReal *pll_mu = nll->createProfile(mu);
    pll_mu->plotOn(fmu);
    ws->import(*fmu);

    delete fmu;

  }

  RooArgSet weights("weights");
  RooArgSet pdfs_bonly("pdfs_bonly");
  RooArgSet pdfs_b("pdfs_b");

  RooRealVar minAIC("minAIC","",1E10);
  //compute AIC stuff
  for(auto t = tags.begin(); t!=tags.end(); t++) {
    RooAbsPdf *p_bonly = ws->pdf("bonly_"+*t);
    RooAbsPdf *p_b = ws->pdf("b_"+*t);
    RooFitResult *sb = (RooFitResult*)ws->obj(*t+"_bonly_fitres");
    RooRealVar k(*t+"_b_k","",p_bonly->getParameters(RooArgSet(mgg))->getSize());
    RooRealVar nll(*t+"_b_minNll","",sb->minNll());
    RooRealVar Npts(*t+"_b_N","",blind_data->sumEntries());
    RooFormulaVar AIC(*t+"_b_AIC","2*@0+2*@1+2*@1*(@1+1)/(@2-@1-1)",RooArgSet(nll,k,Npts));
    ws->import(AIC);
    if(AIC.getVal() < minAIC.getVal()) {
      minAIC.setVal(AIC.getVal());
    }
    //aicExpSum+=TMath::Exp(-0.5*AIC.getVal()); //we will need this precomputed  for the next step
    pdfs_bonly.add(*p_bonly);
    pdfs_b.add(*p_b);
  }
  ws->import(minAIC);
  //compute the AIC weight
  float aicExpSum=0;
  for(auto t = tags.begin(); t!=tags.end(); t++) {
    RooFormulaVar *AIC = (RooFormulaVar*)ws->obj(*t+"_b_AIC");
    aicExpSum+=TMath::Exp(-0.5*(AIC->getVal()-minAIC.getVal())); //we will need this precomputed  for the next step    
  }
  std::cout << "aicExpSum: " << aicExpSum << std::endl;

  for(auto t = tags.begin(); t!=tags.end(); t++) {
    RooFormulaVar *AIC = (RooFormulaVar*)ws->obj(*t+"_b_AIC");
    RooRealVar *AICw = new RooRealVar(*t+"_b_AICWeight","",TMath::Exp(-0.5*(AIC->getVal()-minAIC.getVal()))/aicExpSum);
    if( TMath::IsNaN(AICw->getVal()) ) {AICw->setVal(0);}
    ws->import(*AICw);
    std::cout << *t << ":  " << AIC->getVal()-minAIC.getVal() << "    " << AICw->getVal() << std::endl;
    weights.add(*AICw);
  }
  RooAddPdf bonly_AIC("bonly_AIC","",pdfs_bonly,weights);
  RooAddPdf b_AIC("b_AIC","",pdfs_b,weights);

  //b_AIC.fitTo(data,RooFit::Strategy(0),RooFit::Extended(kTRUE),RooFit::Range("sideband_low,sideband_high"));
  //RooFitResult* bres = b_AIC.fitTo(data,RooFit::Strategy(2),RooFit::Save(kTRUE),RooFit::Extended(kTRUE),RooFit::Range("sideband_low,sideband_high"));
  //bres->SetName("AIC_b_fitres");
  //ws->import(*bres);

  //make blinded fit
  RooPlot *fmgg_b = mgg.frame(RooFit::Range("sideband_low,sideband_high"));
  blind_data->plotOn(fmgg_b,RooFit::Range("sideband_low,sideband_high"));
  TBox blindBox(121,fmgg_b->GetMinimum()-(fmgg_b->GetMaximum()-fmgg_b->GetMinimum())*0.015,130,fmgg_b->GetMaximum());
  blindBox.SetFillColor(kGray);
  fmgg_b->addObject(&blindBox);
  bonly_AIC.plotOn(fmgg_b,RooFit::LineColor(kRed),RooFit::Range("Full"),RooFit::NormRange("sideband_low,sideband_high"));
  fmgg_b->SetName("AIC_blinded_frame");
  ws->import(*fmgg_b);
  delete fmgg_b;
    
#if 1

  RooRealVar sigma("AIC_s_sigma","",5,0,100);
  if(forceSigma!=-1) {
    sigma.setVal(forceSigma);
    sigma.setConstant(true);
  }
  RooRealVar mu("AIC_s_mu","",126,120,132);
  if(forceMu!=-1) {
    mu.setVal(forceMu);
    mu.setConstant(true);
  }
  RooGaussian sig("AIC_sig_model","",mgg,mu,sigma);
  RooRealVar Nsig("AIC_sb_Ns","",5,0,100);
  RooRealVar Nbkg("AIC_sb_Nb","",100,0,100000);
  
  
  RooRealVar HiggsMass("HiggsMass","",125.1);
  RooRealVar HiggsMassError("HiggsMassError","",0.24);
  RooGaussian HiggsMassConstraint("HiggsMassConstraint","",mu,HiggsMass,HiggsMassError);
  
  
  RooAddPdf fitModel("AIC_sb_model","",RooArgList( b_AIC, sig ),RooArgList(Nbkg,Nsig));

  RooFitResult* sbres;
  RooAbsReal *nll;

  if(constrainMu) {
    fitModel.fitTo(data,RooFit::Strategy(0),RooFit::Extended(kTRUE),RooFit::ExternalConstraints(RooArgSet(HiggsMassConstraint)));
    sbres = fitModel.fitTo(data,RooFit::Strategy(2),RooFit::Save(kTRUE),RooFit::Extended(kTRUE),RooFit::ExternalConstraints(RooArgSet(HiggsMassConstraint)));
    nll = fitModel.createNLL(data,RooFit::NumCPU(4),RooFit::Extended(kTRUE),RooFit::ExternalConstraints(RooArgSet(HiggsMassConstraint)));
  } else {
    fitModel.fitTo(data,RooFit::Strategy(0),RooFit::Extended(kTRUE));
    sbres = fitModel.fitTo(data,RooFit::Strategy(2),RooFit::Save(kTRUE),RooFit::Extended(kTRUE));
    nll = fitModel.createNLL(data,RooFit::NumCPU(4),RooFit::Extended(kTRUE));
  }

  assert(nll!=0);
  
  sbres->SetName("AIC_sb_fitres");
  ws->import(*sbres);
  ws->import(fitModel);
  
  RooPlot *fmgg = mgg.frame();
  data.plotOn(fmgg);
  fitModel.plotOn(fmgg);
  ws->pdf("b_AIC")->plotOn(fmgg,RooFit::LineColor(kRed),RooFit::Range("Full"),RooFit::NormRange("Full"));
  fmgg->SetName("AIC_frame");
  ws->import(*fmgg);
  delete fmgg;

  RooMinuit(*nll).migrad();
  
  RooPlot *fNs = Nsig.frame(0,25);
  fNs->SetName("AIC_Nsig_pll");
  RooAbsReal *pll = nll->createProfile(Nsig);
  //nll->plotOn(fNs,RooFit::ShiftToZero(),RooFit::LineColor(kRed));
  pll->plotOn(fNs);
  ws->import(*fNs);
  delete fNs;


  RooPlot *fmu = mu.frame(125,132);
  fmu->SetName("AIC_mu_pll");
  RooAbsReal *pll_mu = nll->createProfile(mu);
  pll_mu->plotOn(fmu);
  ws->import(*fmu);

  delete fmu;

  std::cout << "min AIC: " << minAIC.getVal() << std::endl;
  for(auto t = tags.begin(); t!=tags.end(); t++) {
    RooFormulaVar *AIC = (RooFormulaVar*)ws->obj(*t+"_b_AIC");
    RooRealVar *AICw = ws->var(*t+"_b_AICWeight");
    RooRealVar* k = ws->var(*t+"_b_k");
    printf("%s & %0.0f & %0.2f & %0.2f \\\\\n",t->Data(),k->getVal(),AIC->getVal()-minAIC.getVal(),AICw->getVal());
    //std::cout << k->getVal() << " " << AIC->getVal()-minAIC.getVal() << " " << AICw->getVal() << std::endl;
  }
#endif
  return ws;
}
Exemple #29
0
void ootpu_fit(TString files, TString comments="") {

  TChain* chain = new TChain("reduced_tree");
  chain->Add(files);

  TH1::SetDefaultSumw2();

  TH1F* hrelIso = new TH1F("hrelIso","", 30, 0, 0.5);
  TH1F* hOOTPU = new TH1F("hOOTPU","", 75, 0, 75);
  TH1F* hOOTPUvsIso = new TH1F("hOOTPUvsIso",";Out-of-time ints.;Isolation cut efficiency", 15, 0, 75);

  hrelIso->StatOverflows(true);
  
  int n1(0), n2(0);
  if (files.Contains("20bx25")) {
    n1=15;
    n2=75;
  }
  else if (files.Contains("S14")) {
    n1=0;
    n2=120;
  }
  else { // default: 8 TeV scenario
    n1=0;
    n2=70;
  }


  TString mu("num_gen_muons==1&&muon_reco_match>=0");
  int low = 15; 
  for (int bin(1); bin<hOOTPUvsIso->GetNbinsX()+1; bin++) {
    if (bin<4) continue;
    if (bin>4) low=low+5;
    if (low>hOOTPUvsIso->GetBinLowEdge(hOOTPUvsIso->GetNbinsX())) break;
    TString cuts = Form("(%s)&&(oot_pu>=%d&&oot_pu<%d)",mu.Data(),low,low+4);
    cout << "Cuts: " << cuts.Data() << endl;
    chain->Project(hrelIso->GetName(), "muon_relIso", cuts);
    chain->Project(hOOTPU->GetName(), "oot_pu", cuts);
    hrelIso->Scale(1/hrelIso->GetEntries());
    Double_t left(0.), lerror(0.), right(0.), rerror(0.);
    left = hrelIso->IntegralAndError(1,12,lerror);
    right = hrelIso->IntegralAndError(13,31,rerror);
    float rat_error=sqrt((left*left*rerror*rerror+right*right*lerror*lerror)/((left+right)*(left+right)));
    printf("bin1: %3.2f +/- %3.3f\n", left/(left+right),rat_error);
    hOOTPUvsIso->SetBinContent(bin,left/(left+right));
    hOOTPUvsIso->SetBinError(bin,rat_error);
  }
  
  hOOTPUvsIso->SetLineColor(1);
  hOOTPUvsIso->SetMarkerColor(1);
  hOOTPUvsIso->SetMarkerStyle(20);

  TCanvas* c1 = new TCanvas();

  hOOTPUvsIso->Draw("e1");

  // do a linear fit
  TF1 *flin = new TF1("flin", "1 ++ x", 15, 75);
  hOOTPUvsIso->Fit(flin);
  flin=hOOTPUvsIso->GetFunction("flin");
  flin->SetLineColor(kBlue);
  flin->SetLineWidth(2);

  TString plotTitle ="OOTPU_fit"+comments+".pdf";
  c1->Print(plotTitle);

  // cout << "Rejection rates" << endl;
  // Double_t left(0.), lerror(0.), right(0.), rerror(0.);
  // left = hA->IntegralAndError(1,12,lerror);
  // right = hA->IntegralAndError(13,31,rerror);
  // float rat_error=sqrt((left*left*rerror*rerror+right*right*lerror*lerror)/((left+right)*(left+right)));
  // printf("bin1: %3.2f +/- %3.3f\n", left/(left+right),rat_error);
  // left = hB->IntegralAndError(1,12,lerror);
  // right = hB->IntegralAndError(13,31,rerror);
  // rat_error=sqrt((left*left*rerror*rerror+right*right*lerror*lerror)/((left+right)*(left+right)));
  // printf("bin2: %3.2f +/- %3.3f\n", left/(left+right),rat_error);
  // left = hC->IntegralAndError(1,12,lerror);
  // right = hC->IntegralAndError(13,31,rerror);
  // rat_error=sqrt((left*left*rerror*rerror+right*right*lerror*lerror)/((left+right)*(left+right)));
  // printf("bin3: %3.2f +/- %3.3f\n", left/(left+right),rat_error);
  // left = hD->IntegralAndError(1,12,lerror);
  // right = hD->IntegralAndError(13,31,rerror);
  // rat_error=sqrt((left*left*rerror*rerror+right*right*lerror*lerror)/((left+right)*(left+right)));
  // printf("bin4: %3.2f +/- %3.3f\n", left/(left+right),rat_error);
}
Exemple #30
0
 double IndependentMvnModel::mu(int i)const{
   return mu()[i];
 }