Exemple #1
0
/**
* Parse attribute data based on attribute type
*
* \details
*      Parses the attribute data based on the passed attribute type.
*      Parsed_data will be updated based on the attribute data parsed.
*
* \param [in]   attr_type      Attribute type
* \param [in]   attr_len       Length of the attribute data
* \param [in]   data           Pointer to the attribute data
* \param [out]  parsed_update  Reference to parsed_update; will be updated with all parsed data
*/
void parseBgpLib::parseAttrData(u_char attr_type, uint16_t attr_len, u_char *data, parsed_update &update, MD5 &hash) {
    u_char ipv4_raw[4];
    char ipv4_char[16];
    uint32_t value32bit;
    uint16_t value16bit;

    if (p_info)
        hash.update((unsigned char *) p_info->peer_hash_str.c_str(), p_info->peer_hash_str.length());

        /*
         * Parse based on attribute type
         */
    switch (attr_type) {

        case ATTR_TYPE_ORIGIN : // Origin
            update.attrs[LIB_ATTR_ORIGIN].official_type = ATTR_TYPE_ORIGIN;
            update.attrs[LIB_ATTR_ORIGIN].name = parse_bgp_lib::parse_bgp_lib_attr_names[LIB_ATTR_ORIGIN];
            switch (data[0]) {
                case 0 :
                    update.attrs[LIB_ATTR_ORIGIN].value.push_back(std::string("igp"));
                    break;
                case 1 :
                    update.attrs[LIB_ATTR_ORIGIN].value.push_back(std::string("egp"));
                    break;
                case 2 :
                    update.attrs[LIB_ATTR_ORIGIN].value.push_back(std::string("incomplete"));
                    break;
            }
            update_hash(&update.attrs[LIB_ATTR_ORIGIN].value, &hash);

            break;

        case ATTR_TYPE_AS_PATH : // AS_PATH
            parseAttrDataAsPath(attr_len, data, update);
            update_hash(&update.attrs[LIB_ATTR_AS_PATH].value, &hash);
            break;

        case ATTR_TYPE_NEXT_HOP : // Next hop v4
            memcpy(ipv4_raw, data, 4);
            inet_ntop(AF_INET, ipv4_raw, ipv4_char, sizeof(ipv4_char));
            update.attrs[LIB_ATTR_NEXT_HOP].official_type = ATTR_TYPE_NEXT_HOP;
            update.attrs[LIB_ATTR_NEXT_HOP].name = parse_bgp_lib::parse_bgp_lib_attr_names[LIB_ATTR_NEXT_HOP];
            update.attrs[LIB_ATTR_NEXT_HOP].value.push_back(std::string(ipv4_char));
            update_hash(&update.attrs[LIB_ATTR_NEXT_HOP].value, &hash);

            break;

        case ATTR_TYPE_MED : // MED value
        {
            memcpy(&value32bit, data, 4);
            parse_bgp_lib::SWAP_BYTES(&value32bit);

            std::ostringstream numString;
            numString << value32bit;
            update.attrs[LIB_ATTR_MED].official_type = ATTR_TYPE_MED;
            update.attrs[LIB_ATTR_MED].name = parse_bgp_lib::parse_bgp_lib_attr_names[LIB_ATTR_MED];
            update.attrs[LIB_ATTR_MED].value.push_back(numString.str());
            update_hash(&update.attrs[LIB_ATTR_MED].value, &hash);
            break;
        }
        case ATTR_TYPE_LOCAL_PREF : // local pref value
        {
            memcpy(&value32bit, data, 4);
            parse_bgp_lib::SWAP_BYTES(&value32bit);

             std::ostringstream numString;
            numString << value32bit;
            char numstring[100] = {0};
            update.attrs[LIB_ATTR_LOCAL_PREF].official_type = ATTR_TYPE_LOCAL_PREF;
            update.attrs[LIB_ATTR_LOCAL_PREF].name = parse_bgp_lib::parse_bgp_lib_attr_names[LIB_ATTR_LOCAL_PREF];
            update.attrs[LIB_ATTR_LOCAL_PREF].value.push_back(numString.str());
            update_hash(&update.attrs[LIB_ATTR_LOCAL_PREF].value, &hash);

            break;
        }
        case ATTR_TYPE_ATOMIC_AGGREGATE : // Atomic aggregate
            update.attrs[LIB_ATTR_ATOMIC_AGGREGATE].official_type = ATTR_TYPE_ATOMIC_AGGREGATE;
            update.attrs[LIB_ATTR_ATOMIC_AGGREGATE].name = parse_bgp_lib::parse_bgp_lib_attr_names[LIB_ATTR_ATOMIC_AGGREGATE];
            update.attrs[LIB_ATTR_ATOMIC_AGGREGATE].value.push_back(std::string("1"));
            break;

        case ATTR_TYPE_AGGREGATOR : // Aggregator
            parseAttrDataAggregator(attr_len, data, update);
            update_hash(&update.attrs[LIB_ATTR_AGGREGATOR].value, &hash);

            break;

        case ATTR_TYPE_ORIGINATOR_ID : // Originator ID
            memcpy(ipv4_raw, data, 4);
            inet_ntop(AF_INET, ipv4_raw, ipv4_char, sizeof(ipv4_char));
            update.attrs[LIB_ATTR_ORIGINATOR_ID].official_type = ATTR_TYPE_ORIGINATOR_ID;
            update.attrs[LIB_ATTR_ORIGINATOR_ID].name = parse_bgp_lib::parse_bgp_lib_attr_names[LIB_ATTR_ORIGINATOR_ID];
            update.attrs[LIB_ATTR_ORIGINATOR_ID].value.push_back(std::string(ipv4_char));
            break;

        case ATTR_TYPE_CLUSTER_LIST : // Cluster List (RFC 4456)
            // According to RFC 4456, the value is a sequence of cluster id's
            update.attrs[LIB_ATTR_CLUSTER_LIST].official_type = ATTR_TYPE_CLUSTER_LIST;
            update.attrs[LIB_ATTR_CLUSTER_LIST].name = parse_bgp_lib::parse_bgp_lib_attr_names[LIB_ATTR_CLUSTER_LIST];
            for (int i = 0; i < attr_len; i += 4) {
                memcpy(ipv4_raw, data, 4);
                data += 4;
                inet_ntop(AF_INET, ipv4_raw, ipv4_char, sizeof(ipv4_char));
                update.attrs[LIB_ATTR_CLUSTER_LIST].value.push_back(std::string(ipv4_char));
            }
            break;

        case ATTR_TYPE_COMMUNITIES : // Community list
        {
            update.attrs[LIB_ATTR_COMMUNITIES].official_type = ATTR_TYPE_COMMUNITIES;
            update.attrs[LIB_ATTR_COMMUNITIES].name = parse_bgp_lib::parse_bgp_lib_attr_names[LIB_ATTR_COMMUNITIES];
            for (int i = 0; i < attr_len; i += 4) {
                std::ostringstream numString;
                // Add entry
                memcpy(&value16bit, data, 2);
                data += 2;
                parse_bgp_lib::SWAP_BYTES(&value16bit);
                numString << value16bit;
                numString << ":";

                memcpy(&value16bit, data, 2);
                data += 2;
                parse_bgp_lib::SWAP_BYTES(&value16bit);
                numString << value16bit;
                update.attrs[LIB_ATTR_COMMUNITIES].value.push_back(numString.str());
            }
            update_hash(&update.attrs[LIB_ATTR_COMMUNITIES].value, &hash);

            break;
        }
        case ATTR_TYPE_EXT_COMMUNITY : // extended community list (RFC 4360)
        {
            update.attrs[LIB_ATTR_EXT_COMMUNITY].official_type = ATTR_TYPE_EXT_COMMUNITY;
            update.attrs[LIB_ATTR_EXT_COMMUNITY].name = parse_bgp_lib::parse_bgp_lib_attr_names[LIB_ATTR_EXT_COMMUNITY];
            parse_bgp_lib::ExtCommunity ec(this, logger, debug);
            ec.parseExtCommunities(attr_len, data, update);
            update_hash(&update.attrs[LIB_ATTR_EXT_COMMUNITY].value, &hash);

            break;
        }

        case ATTR_TYPE_IPV6_EXT_COMMUNITY : // IPv6 specific extended community list (RFC 5701)
        {
            update.attrs[LIB_ATTR_IPV6_EXT_COMMUNITY].official_type = ATTR_TYPE_IPV6_EXT_COMMUNITY;
            update.attrs[LIB_ATTR_IPV6_EXT_COMMUNITY].name = parse_bgp_lib::parse_bgp_lib_attr_names[LIB_ATTR_IPV6_EXT_COMMUNITY];
            parse_bgp_lib::ExtCommunity ec6(this, logger, debug);
            ec6.parsev6ExtCommunities(attr_len, data, update);
            break;
        }

        case ATTR_TYPE_MP_REACH_NLRI :  // RFC4760
        {
            parse_bgp_lib::MPReachAttr mp(this, logger, debug);
            mp.parseReachNlriAttr(attr_len, data, update);
            break;
        }

        case ATTR_TYPE_MP_UNREACH_NLRI : // RFC4760
        {
            parse_bgp_lib::MPUnReachAttr mp(this, logger, debug);
            mp.parseUnReachNlriAttr(attr_len, data, update);
            break;
        }

        case ATTR_TYPE_AS_PATHLIMIT : // deprecated
        {
            break;
        }

        case ATTR_TYPE_BGP_LS: {
            MPLinkStateAttr ls(this, logger, &update, debug);
            ls.parseAttrLinkState(attr_len, data);
            break;
        }

        case ATTR_TYPE_AS4_PATH: {
            SELF_DEBUG("%sAttribute type AS4_PATH is not yet implemented, skipping for now.", debug_prepend_string.c_str());
            break;
        }

        case ATTR_TYPE_AS4_AGGREGATOR: {
            SELF_DEBUG("%sAttribute type AS4_AGGREGATOR is not yet implemented, skipping for now.", debug_prepend_string.c_str());
            break;
        }

        default:
            LOG_INFO("%sAttribute type %d is not yet implemented or intentionally ignored, skipping for now.",
                     debug_prepend_string.c_str(), attr_type);
            break;

    } // END OF SWITCH ATTR TYPE
}
Exemple #2
0
int main(int argc, char* argv[])
{
  // load the mesh
  Mesh mesh;
  H2DReader mloader;
  mloader.load("square_quad.mesh", &mesh);

  // initial mesh refinement
  for (int i=0; i < INIT_REF_NUM; i++) mesh.refine_all_elements();

  // initialize the shapeset and the cache
  H1Shapeset shapeset;
  PrecalcShapeset pss(&shapeset);

  // create finite element space
  H1Space space(&mesh, &shapeset);
  space.set_bc_types(bc_types);
  space.set_bc_values(bc_values);
  space.set_uniform_order(P_INIT);

  // enumerate basis functions
  space.assign_dofs();

  // initialize the weak formulation
  WeakForm wf(1);
  wf.add_biform(0, 0, callback(bilinear_form), SYM);
  wf.add_liform(0, linear_form, linear_form_ord);

  // visualize solution and mesh
  ScalarView sview("Coarse solution", 0, 100, 798, 700);
  OrderView  oview("Polynomial orders", 800, 100, 798, 700);

  // matrix solver
  UmfpackSolver solver;

  // prepare selector
  RefinementSelectors::H1UniformHP selector(ISO_ONLY, ADAPT_TYPE, 1.0, H2DRS_DEFAULT_ORDER, &shapeset);

  // DOF and CPU convergence graphs
  SimpleGraph graph_dof_est, graph_dof_exact, graph_cpu_est, graph_cpu_exact;

  // adaptivity loop
  int it = 1, ndofs;
  bool done = false;
  double cpu = 0.0;
  Solution sln_coarse, sln_fine;
  do
  {
    info("\n---- Adaptivity step %d ---------------------------------------------\n", it++);

    // time measurement
    begin_time();

    // solve the coarse mesh problem
    LinSystem ls(&wf, &solver);
    ls.set_spaces(1, &space);
    ls.set_pss(1, &pss);
    ls.assemble();
    ls.solve(1, &sln_coarse);

    // time measurement
    cpu += end_time();

    // calculate error wrt. exact solution
    ExactSolution exact(&mesh, fndd);
    double error = h1_error(&sln_coarse, &exact) * 100;
    info("\nExact solution error: %g%%", error);

    // view the solution
    sview.show(&sln_coarse);
    oview.show(&space);

    // time measurement
    begin_time();

    // solve the fine mesh problem
    RefSystem rs(&ls);
    rs.assemble();
    rs.solve(1, &sln_fine);

    // calculate error estimate wrt. fine mesh solution
    H1AdaptHP hp(1, &space);
    double err_est = hp.calc_error(&sln_coarse, &sln_fine) * 100;
    info("Estimate of error: %g%%", err_est);

    // add entries to DOF convergence graphs
    graph_dof_exact.add_values(space.get_num_dofs(), error);
    graph_dof_exact.save("conv_dof_exact.dat");
    graph_dof_est.add_values(space.get_num_dofs(), err_est);
    graph_dof_est.save("conv_dof_est.dat");

    // add entries to CPU convergence graphs
    graph_cpu_exact.add_values(cpu, error);
    graph_cpu_exact.save("conv_cpu_exact.dat");
    graph_cpu_est.add_values(cpu, err_est);
    graph_cpu_est.save("conv_cpu_est.dat");

    // if err_est too large, adapt the mesh
    if (err_est < ERR_STOP) done = true;
    else {
      hp.adapt(THRESHOLD, STRATEGY, &selector, MESH_REGULARITY);
      ndofs = space.assign_dofs();
      if (ndofs >= NDOF_STOP) done = true;
    }

    // time measurement
    cpu += end_time();
    //sview.wait_for_keypress();
  }
  while (done == false);
  verbose("Total running time: %g sec", cpu);

  // show the fine solution - this is the final result
  sview.set_title("Final solution");
  sview.show(&sln_fine);

  // wait for keyboard or mouse input
  View::wait();
  return 0;
}
DBListCtrl::DBListCtrl(
      wxWindow* frame,
      wxWindow* parent,
      wxWindowID id,
      const wxPoint& pos,
      const wxSize& size,
      long style) :
   wxListCtrl(parent, id, pos, size, style),
   m_frame(frame),
   m_editing_item(-1),
   m_dragging_to_item(-1)
{
   wxListItem itemCol;
   itemCol.SetText("Name");
    this->InsertColumn(0, itemCol);
    SetColumnWidth(0, 200);
	itemCol.SetText("Description");
    this->InsertColumn(1, itemCol);
	SetColumnWidth(1, 200);

	/*
	const std::string file_name = "test.txt";
	std::ifstream ifs(file_name.c_str());
	if (ifs.fail())
    {
        std::cerr << "list file open error" << std::endl;
        return;
    }
    std::string str((std::istreambuf_iterator<char>(ifs)),
        std::istreambuf_iterator<char>());
	*/

	extern CURL *_g_curl;
	CURLcode ret;
	string chunk;
	if (_g_curl == NULL) {
		cerr << "curl_easy_init() failed" << endl;
		return;
	}
	curl_easy_reset(_g_curl);
	curl_easy_setopt(_g_curl, CURLOPT_URL, "http://srpbsg04.unit.oist.jp/flydb/catalog.txt");
	curl_easy_setopt(_g_curl, CURLOPT_USERAGENT, "libcurl-agent/1.0");
	curl_easy_setopt(_g_curl, CURLOPT_WRITEFUNCTION, callbackWrite);
	curl_easy_setopt(_g_curl, CURLOPT_WRITEDATA, &chunk);
	//ピア証明書検証なし
	curl_easy_setopt(_g_curl, CURLOPT_SSL_VERIFYPEER, 0);
	ret = curl_easy_perform(_g_curl);
	if (ret != CURLE_OK) {
		cerr << "curl_easy_perform() failed." << curl_easy_strerror(ret) << endl;
		return;
	}
	
	std::stringstream ss(chunk);
	std::string name, description, url, temp;
	while (getline(ss, temp))
	{
		std::stringstream ls(temp);
		if(getline(ls, name, '\t') && getline(ls, url, '\t'))
		{
			description = "";
			getline(ls, description, '\t');
			Append(name, url, description);
		}
	}
/*
	while (getline(ss, temp))
	{
		std::stringstream ls(temp);
		if((ls >> name) && (ls >> url))
		{
			description = "";
			ls >> description;
			Append(name, url, description);
		}
	}
*/
}
Exemple #4
0
int MAC3DTest_StationaryBubble() {
    // Set initial level set
    const double Re = 0.0, We = 0.0, Fr = 0.0;
    const double L = 1.0, U = 1.0;
    const double rhoL = 1.226, muL = 1.78e-5;
    // const double rhoH = 1000, muH = 1.137e-3;
    const double rhoH = 1000, muH = 1.137e-3, sigma = 0.0728;
    // const double rhoL = 1000, muL = 1.137e-3, sigma = 0.0;
    const double ambientPressure = 1.0;
    const double gConstant = 0.0; 
    GAXISENUM3D GAxis = GAXISENUM3D::Y;
    // # of cells
    const int nx = 128, ny = 128, nz = 128;
    // related to initialize level set
    const double baseX = 0.0, baseY = 0.0, baseZ = 0.0, lenX = 0.04, lenY = 0.04, lenZ = 0.04, cfl = 0.5;
    double radius = 0.01, x = 0.0, y = 0.0, z = 0.0, d = 0.0;

    const int maxiter = 5, niterskip = 1, num_bc_grid = 3;
    const int64_t arrSize = (nx + 2 * num_bc_grid) * (ny + 2 * num_bc_grid) * (nz + 2 * num_bc_grid);
    const double maxtime = 0.06;
    const bool writeVTK = false;
    // length of each cell
    const double dx = lenX / nx, dy = lenY / ny, dz = lenZ / nz;
    std::ostringstream outfname_stream1;
    outfname_stream1 << "testMAC3D_StationaryBubbleBubbleRisingVel_Re_"
        << std::to_string(Re) << "_"
        << static_cast<std::ostringstream*>(&(std::ostringstream() << nx))->str()
        << "x"
        << static_cast<std::ostringstream*>(&(std::ostringstream() << ny))->str()
        << "x"
        << static_cast<std::ostringstream*>(&(std::ostringstream() << nz))->str();
    const std::string fname_vel = outfname_stream1.str();

    std::ostringstream outfname_stream2;
    outfname_stream2 << "testMAC3D_StationaryBubbleBubbleRisingDiv_Re_"
        << std::to_string(Re) << "_"
        << static_cast<std::ostringstream*>(&(std::ostringstream() << nx))->str()
        << "x"
        << static_cast<std::ostringstream*>(&(std::ostringstream() << ny))->str()
        << "x"
        << static_cast<std::ostringstream*>(&(std::ostringstream() << nz))->str();
    const std::string fname_div = outfname_stream2.str();
    const int iterskip = 1;
    int stat = 0;

    std::unique_ptr<MACSolver3D> MSolver;
    MSolver = std::make_unique<MACSolver3D>(rhoH, rhoL, muH, muL, gConstant, GAxis,
        L, U, sigma, nx, ny, nz, baseX, baseY, baseY, lenX, lenY, lenZ,
        cfl, maxtime, maxiter, niterskip, num_bc_grid, writeVTK);
    MSolver->SetBC_U_3D("wall", "wall", "wall", "wall", "wall", "wall");
    MSolver->SetBC_V_3D("wall", "wall", "wall", "wall", "wall", "wall");
    MSolver->SetBC_W_3D("wall", "wall", "wall", "wall", "wall", "wall");
    MSolver->SetBC_P_3D("wall", "wall", "wall", "wall", "wall", "wall");
    MSolver->SetBCConstantUW(0.0);
    MSolver->SetBCConstantUE(0.0);
    MSolver->SetBCConstantUS(0.0);
    MSolver->SetBCConstantUN(0.0);
    MSolver->SetBCConstantUB(0.0);
    MSolver->SetBCConstantUT(0.0);
    MSolver->SetBCConstantVW(0.0);
    MSolver->SetBCConstantVE(0.0);
    MSolver->SetBCConstantVS(0.0);
    MSolver->SetBCConstantVN(0.0);
    MSolver->SetBCConstantVB(0.0);
    MSolver->SetBCConstantVT(0.0);
    MSolver->SetBCConstantWW(0.0);
    MSolver->SetBCConstantWE(0.0);
    MSolver->SetBCConstantWS(0.0);
    MSolver->SetBCConstantWN(0.0);
    MSolver->SetBCConstantWB(0.0);
    MSolver->SetBCConstantWT(0.0);
    MSolver->UpdateAmbientPressure(MSolver->m_dt * ambientPressure);
    MSolver->SetPLTType(PLTTYPE::BINARY);

    MSolver->SetPoissonSolver(POISSONTYPE::CG);
    MSolver->SetImplicitSolver(POISSONTYPE::CG);
    const int poissonMaxIter = 2500;

    std::shared_ptr<LevelSetSolver3D> LSolver;
    LSolver = std::make_shared<LevelSetSolver3D>(nx, ny, nz, num_bc_grid, baseX, baseY, baseZ, dx, dy, dz);
    // \phi^n
    std::vector<double> lsB(arrSize, 0.0);
    // \phi^{n + 1}
    std::vector<double> ls(arrSize, 0.0);
    // inside value must be positive levelset, otherwise, negative
    
    std::vector<double> H(arrSize, 0.0), 
        HSmooth(arrSize, 0.0);
    // init velocity and pseudo-pressure
    MSolver->AllocateVariables();

    MSolver->ApplyBC_U_3D(MSolver->m_u);
    MSolver->ApplyBC_V_3D(MSolver->m_v);
    MSolver->ApplyBC_W_3D(MSolver->m_w);
    MSolver->ApplyBC_P_3D(MSolver->m_ps);
    MSolver->ApplyBC_P_3D(MSolver->m_p);
    LSolver->SetBC_P_3D("neumann", "neumann", "neumann", "neumann", "neumann", "neumann");
    LSolver->SetBCConstantPW(0.0);
    LSolver->SetBCConstantPE(0.0);
    LSolver->SetBCConstantPS(0.0);
    LSolver->SetBCConstantPN(0.0);
    LSolver->SetBCConstantPB(0.0);
    LSolver->SetBCConstantPT(0.0);
    
    for (int k = 0; k < nz + 2 * num_bc_grid; k++)
    for (int j = 0; j < ny + 2 * num_bc_grid; j++)
    for (int i = 0; i < nx + 2 * num_bc_grid; i++) {
        // positive : inside & gas, negative : outside & liquid 
        x = baseX + (i + 0.5 - num_bc_grid) * dx;
        y = baseY + (j + 0.5 - num_bc_grid) * dy;
        z = baseZ + (k + 0.5 - num_bc_grid) * dz;

        // d - inside : -, outside : +
        d = std::sqrt(std::pow(x - 0.02, 2.0) + std::pow(y - 0.02, 2.0) + std::pow(z - 0.02, 2.0)) - radius;

        // ls - inside : -(gas), outside : +(liquid)
        ls[idx3_3D(ny, nz, i, j, k)] = d;
    }
    LSolver->ApplyBC_P_3D(ls);
    LSolver->Reinit_MinRK2_3D(ls);
    
    LSolver->ApplyBC_P_3D(ls);

    // prevent dt == 0.0
    MSolver->m_dt = cfl * std::min(dx, dy) / U;
    std::cout << " dt : " << MSolver->m_dt << std::endl;

    std::vector<double> rhsU(arrSize), rhsV(arrSize), rhsW(arrSize);
    std::vector<double> uhat(arrSize), vhat(arrSize), what(arrSize);
    std::vector<double> div(arrSize);
    MSolver->OutRes(MSolver->m_iter, MSolver->m_curTime, fname_vel, fname_div,
        MSolver->m_u, MSolver->m_v, MSolver->m_w, MSolver->m_ps, ls);

    while (MSolver->m_curTime < MSolver->kMaxTime && MSolver->m_iter < MSolver->kMaxIter) {
        // Solver Level set part first
        // Have to use \phi^{n+1} for rho, mu, kappa
        MSolver->m_iter++;

        lsB = ls;
        LSolver->Solve_LevelSet_3D(ls, MSolver->m_u, MSolver->m_v, MSolver->m_w, MSolver->m_dt);
        LSolver->ApplyBC_P_3D(ls);
        LSolver->Reinit_MinRK2_3D(ls);
        
        LSolver->ApplyBC_P_3D(ls);
        
        // Solve Momentum Part
        MSolver->UpdateKappa(ls);
        H = MSolver->UpdateHeavisideFunc(ls);
        HSmooth = MSolver->UpdateSmoothHeavisideFunc(ls);

        rhsU = MSolver->GetRHSU(LSolver, ls, MSolver->m_u, MSolver->m_v, MSolver->m_w, H);
        rhsV = MSolver->GetRHSV(LSolver, ls, MSolver->m_u, MSolver->m_v, MSolver->m_w, H);
        rhsW = MSolver->GetRHSW(LSolver, ls, MSolver->m_u, MSolver->m_v, MSolver->m_w, H);

        uhat = MSolver->GetUHat(ls, rhsU, H, poissonMaxIter);
        vhat = MSolver->GetVHat(ls, rhsV, H, poissonMaxIter);
        what = MSolver->GetWHat(ls, rhsW, H, poissonMaxIter);

        MSolver->ApplyBC_U_3D(uhat);
        MSolver->ApplyBC_V_3D(vhat);
        MSolver->ApplyBC_W_3D(what);
        
        // From intermediate velocity, get divergence
        div = MSolver->GetDivergence(uhat, vhat, what);
        MSolver->ApplyBC_P_3D(MSolver->m_ps);
        LSolver->ApplyBC_P_3D(ls);

        // Solve Poisson equation
        // m_phi = pressure * dt
        stat = MSolver->SolvePoisson(MSolver->m_ps, div, ls, lsB, MSolver->m_u, MSolver->m_v, MSolver->m_w, H, poissonMaxIter);
        MSolver->ApplyBC_P_3D(MSolver->m_ps);

        stat = MSolver->UpdateVel(MSolver->m_u, MSolver->m_v, MSolver->m_w,
            uhat, vhat, what, MSolver->m_ps, ls, lsB, H);

        MSolver->ApplyBC_U_3D(MSolver->m_u);
        MSolver->ApplyBC_V_3D(MSolver->m_v);
        MSolver->ApplyBC_W_3D(MSolver->m_w);

        MSolver->m_dt = MSolver->UpdateDt(MSolver->m_u, MSolver->m_v, MSolver->m_w);
        MSolver->m_curTime += MSolver->m_dt;

        if ((MSolver->m_iter % MSolver->kNIterSkip) == 0) {
            std::chrono::high_resolution_clock::time_point p = std::chrono::high_resolution_clock::now();
            std::chrono::milliseconds ms = std::chrono::duration_cast<std::chrono::milliseconds>(p.time_since_epoch());

            std::chrono::seconds s = std::chrono::duration_cast<std::chrono::seconds>(ms);
            std::time_t t = s.count();
            std::size_t fractional_seconds = ms.count() % 1000;

            std::cout << "Stationary Bubble : " << std::ctime(&t) << " " << MSolver->m_iter << " " << MSolver->m_curTime << " " << MSolver->m_dt << " " << std::endl;

            MSolver->OutRes(MSolver->m_iter, MSolver->m_curTime, fname_vel, fname_div,
                MSolver->m_u, MSolver->m_v, MSolver->m_w, MSolver->m_ps, ls);
        }
        std::fill(uhat.begin(), uhat.end(), 0.0);
        std::fill(vhat.begin(), vhat.end(), 0.0);
    }
    // http://stackoverflow.com/a/12836048/743078
    std::chrono::high_resolution_clock::time_point p = std::chrono::high_resolution_clock::now();
    std::chrono::milliseconds ms = std::chrono::duration_cast<std::chrono::milliseconds>(p.time_since_epoch());

    std::chrono::seconds s = std::chrono::duration_cast<std::chrono::seconds>(ms);
    std::time_t t = s.count();
    std::size_t fractional_seconds = ms.count() % 1000;

    std::cout << "(Final) Stationary Bubble : " << std::ctime(&t) << " " << MSolver->m_iter << " " << MSolver->m_curTime << " " << MSolver->m_dt << " " << std::endl;
    MSolver->OutRes(MSolver->m_iter, MSolver->m_curTime, fname_vel, fname_div,
        MSolver->m_u, MSolver->m_v, MSolver->m_w, MSolver->m_ps, ls);
    MSolver->OutResClose();

    MSolver.reset();
    LSolver.reset();

    return 0;
}
/*
 * Returns true if request processed and no more requests are expected (QUIT)
 * and false if further requests are expected.
 */
bool FTPServer::processRequest (commands command, string args, Socket control)
{
    if (command == CWD)
    {
        if (chdir (args.c_str ()) < 0)
        {
            control.send (Response (FILE_NOT_FOUND,
                                    "Cannot Change Directory").getString ());
        }
        else
        {
            control.send (Response (FILE_FOUND,
                                    "Changed Directory").getString ());
        }
    }
    else if (command == PWD)
    {
        char curr_dir[1024];
        getcwd (curr_dir, 1024);
        if (!curr_dir)
        {
            control.send (Response (FILE_NOT_FOUND,
                                    "PWD Error").getString ());
        }
        else
        {
            control.send (Response (FILE_FOUND,
                                    string (curr_dir)).getString ());
        }
    }
    else if (command == LIST)
    {
        control.send (Response (OPENING_DATA,
                                "Sending Directory Information").getString ());
        string ls_data = ls (args);
        dataSocket.send (ls_data);
        dataSocket.close ();
        control.send (Response (DATA_CONN_CLOSE, "Success").getString ());
    }
    else if (command == RETR)
    {
        ifstream in_file;
        in_file.open (args.c_str (), ios::in | ios::ate);
        if (!in_file.is_open ())
        {
            dataSocket.close ();
            control.send (Response (FILE_NOT_FOUND,
                                    "File not found").getString ());
        }
        else {
            control.send (Response (TRANSFER_START,
                                    "Sending file").getString ());
            int file_len = (int)in_file.tellg ();
            in_file.seekg (0, ios::beg);
            char* file_data = new char[file_len] ();
            in_file.read (file_data, file_len);
            dataSocket.send (file_data, file_len);
            dataSocket.close ();
            control.send (Response (DATA_CONN_CLOSE,
                                    "File send success").getString ());
            in_file.close ();
            delete[] file_data;
        }
    }
    else if (command == STOR)
    {
        ofstream out_file;
        out_file.open (args.c_str (), ios::out);
        if (!out_file.is_open ())
        {
            dataSocket.close ();
            control.send (Response (FILE_NOT_FOUND,
                                    "File open error").getString ());
        }
        else {
            char file_data[RECV_SIZE];
            control.send (Response (TRANSFER_START,
                                    "Start file send").getString ());
            int recv_len;
            while ((recv_len = dataSocket.recv (file_data, RECV_SIZE)) > 0)
            {
                out_file.write (file_data, recv_len);
            }
            dataSocket.close ();
            out_file.close ();
            control.send (Response (DATA_CONN_CLOSE,
                                    "File receive success").getString ());
        }
    }
    else if (command == PORT)
    {
        stringstream s_ip, s_port1, s_port2;
        char argstring[RECV_SIZE];
        strcpy(argstring, args.c_str());
        s_ip << strtok(argstring, ",") << ".";
        s_ip << strtok(NULL, ",") << ".";
        s_ip << strtok(NULL, ",") << ".";
        s_ip << strtok(NULL, ",");
        s_port1 << strtok(NULL, ",");
        s_port2 << strtok(NULL, ",");
        int port = atoi(s_port1.str().c_str())*256 + atoi(s_port2.str().c_str());
        string ip = s_ip.str();
        if (dataSocket.connect (ip, port) < 0)
        {
            control.send (Response (GENERIC_ERROR,
                                    "Connection Error").getString ());
        }
        else
        {
            control.send (Response (GENERIC_SUCCESS,
                                    "Connection Success").getString ());
        }
    }
    else if (command == QUIT)
    {
        control.send (Response (SERVICE_CLOSE, "Terminating").getString ());
        return true;
    }
    else
    {
        control.send (Response (GENERIC_ERROR,
                                "Unknown Command").getString ());
    }
    return false;
}
Exemple #6
0
int main(int argc, char* argv[])
{
  // load the mesh
  Mesh mesh;
  H2DReader mloader;
  mloader.load("square_quad.mesh", &mesh);
  if(P_INIT == 1) P_INIT++;  // this is because there are no degrees of freedom
                             // on the coarse mesh lshape.mesh if P_INIT == 1

  // initialize the shapeset and the cache
  H1Shapeset shapeset;
  PrecalcShapeset pss(&shapeset);

  // create finite element space
  H1Space space(&mesh, &shapeset);
  space.set_bc_types(bc_types);
  space.set_bc_values(bc_values);
  space.set_uniform_order(P_INIT);

  // enumerate basis functions
  space.assign_dofs();

  // initialize the weak formulation
  WeakForm wf(1);
  wf.add_biform(0, 0, callback(bilinear_form), SYM);
  wf.add_liform(0, callback(linear_form));

  // visualize solution and mesh
  //ScalarView sview("Coarse solution", 0, 0, 500, 400);
  //OrderView  oview("Polynomial orders", 505, 0, 500, 400);

  // matrix solver
  UmfpackSolver solver;

  // prepare selector
  RefinementSelectors::H1NonUniformHP selector(ISO_ONLY, ADAPT_TYPE, 1.0, H2DRS_DEFAULT_ORDER, &shapeset);

  // DOF and CPU convergence graphs
  SimpleGraph graph_dof_est, graph_dof_exact, graph_cpu_est, graph_cpu_exact;

  // adaptivity loop
  int it = 1, ndofs;
  bool done = false;
  double cpu = 0.0;
  Solution sln_coarse, sln_fine;
  do
  {
    info("\n---- Adaptivity step %d ---------------------------------------------\n", it++);

    // time measurement
    begin_time();

    // solve the coarse mesh problem
    LinSystem ls(&wf, &solver);
    ls.set_spaces(1, &space);
    ls.set_pss(1, &pss);
    ls.assemble();
    ls.solve(1, &sln_coarse);

    // time measurement
    cpu += end_time();

    // calculate error wrt. exact solution
    ExactSolution exact(&mesh, fndd);
    double error = h1_error(&sln_coarse, &exact) * 100;
    info("\nExact solution error: %g%%", error);

    // view the solution
    //sview.show(&sln_coarse);
    //oview.show(&space);

    // time measurement
    begin_time();

    // solve the fine mesh problem
    RefSystem rs(&ls);
    rs.assemble();
    rs.solve(1, &sln_fine);

    // calculate error estimate wrt. fine mesh solution
    H1AdaptHP hp(1, &space);
    double err_est = hp.calc_error(&sln_coarse, &sln_fine) * 100;
    info("Estimate of error: %g%%", err_est);

    // add entries to DOF convergence graphs
    graph_dof_exact.add_values(space.get_num_dofs(), error);
    graph_dof_exact.save("conv_dof_exact.dat");
    graph_dof_est.add_values(space.get_num_dofs(), err_est);
    graph_dof_est.save("conv_dof_est.dat");

    // add entries to CPU convergence graphs
    graph_cpu_exact.add_values(cpu, error);
    graph_cpu_exact.save("conv_cpu_exact.dat");
    graph_cpu_est.add_values(cpu, err_est);
    graph_cpu_est.save("conv_cpu_est.dat");

    // if err_est too large, adapt the mesh
    if (err_est < ERR_STOP) done = true;
    else {
      done = hp.adapt(THRESHOLD, STRATEGY, &selector, MESH_REGULARITY);
      ndofs = space.assign_dofs();
      if (ndofs >= NDOF_STOP) done = true;
    }

    // time measurement
    cpu += end_time();

    // wait for keyboard or mouse input
    //sview.wait_for_keypress("Click into the mesh window and press any key to proceed.");
  }
  while (done == false);
  verbose("Total running time: %g sec", cpu);

#define ERROR_SUCCESS                               0
#define ERROR_FAILURE                               -1
  int n_dof_allowed = 49;
  printf("n_dof_actual = %d\n", ndofs);
  printf("n_dof_allowed = %d\n", n_dof_allowed); // ndofs was 49 at the time this test was created
  if (ndofs <= n_dof_allowed) {
    printf("Success!\n");
    return ERROR_SUCCESS;
  }
  else {
    printf("Failure!\n");
    return ERROR_FAILURE;
  }
}
Exemple #7
0
int main(int argc, char *argv[])
{
	//判断参数
	if (argc !=3)
	{
		printf(1, "please input the command as [mv src_file dest_file]\n");
		exit();
	}
	
	//打开源文件
	int fd_src = open(argv[1], O_RDONLY);
	if (fd_src == -1)
	{
		printf(1, "open source file failed\n");
		exit();
	}
	
	//判断源文件状态是否为文件夹
	struct stat st;
	fstat(fd_src, &st);
	if (st.type == T_DIR)
	{
		printf(1, "source file is a directory, the files in that directory is:\n");
		ls(argv[1]);
		printf(1, "the program can't open the file in that directory after list them.\n");
		printf(1, "So, I'm sorry that you have to move them one by one.\n");
		exit();
	}

	//判断第二个参数是不是以"/"结尾,如果是,则补全路径
	char com[128] = {};
	strcpy(com, argv[2]);
	int len1 = strlen(argv[1]);
	int len2 = strlen(argv[2]);
	if (argv[2][len2-1] == '/')
	{
		//找到argv[1]中的文件名
		int i = len1 - 1;
		for (; i >= 0; i--)
			if (argv[1][i] == '/')
				break;
		i++;
		strcpy(&com[len2], &argv[1][i]);
	}
	
	//打开目标文件
	int fd_dest = open(com, O_WRONLY|O_CREATE);
	if (fd_dest == -1)
	{
		printf(1, "create dest file failed\n");
		exit();
	}
	
	//复制文件
	char buf[BUF_SIZE] = {};
	int len = 0;
	while((len = read(fd_src, buf, BUF_SIZE)) > 0)
		write(fd_dest, buf, len);
	
	//关闭文件
	close(fd_src);
	close(fd_dest);
	
	//删除源文件
	if(unlink(argv[1]) < 0)
		printf(1, "delete source file failed\n");
	
	//关闭程序
	exit();
}
Exemple #8
0
void IGIIntegrator::Preprocess(const Scene &scene, const Camera *camera,
                               const Renderer *renderer) {
    if (scene.lights.size() == 0) return;
    MemoryArena arena;
    RNG rng;
    // Compute samples for emitted rays from lights
    vector<float> lightNum(nLightPaths * nLightSets);
    vector<float> lightSampPos(2 * nLightPaths * nLightSets, 0.f);
    vector<float> lightSampComp(nLightPaths * nLightSets, 0.f);
    vector<float> lightSampDir(2 * nLightPaths * nLightSets, 0.f);
    LDShuffleScrambled1D(nLightPaths, nLightSets, &lightNum[0], rng);
    LDShuffleScrambled2D(nLightPaths, nLightSets, &lightSampPos[0], rng);
    LDShuffleScrambled1D(nLightPaths, nLightSets, &lightSampComp[0], rng);
    LDShuffleScrambled2D(nLightPaths, nLightSets, &lightSampDir[0], rng);

    // Precompute information for light sampling densities
    Distribution1D *lightDistribution = ComputeLightSamplingCDF(scene);
    for (uint32_t s = 0; s < nLightSets; ++s) {
        for (uint32_t i = 0; i < nLightPaths; ++i) {
            // Follow path _i_ from light to create virtual lights
            int sampOffset = s*nLightPaths + i;

            // Choose light source to trace virtual light path from
            float lightPdf;
            int ln = lightDistribution->SampleDiscrete(lightNum[sampOffset],
                                                       &lightPdf);
            Light *light = scene.lights[ln];

            // Sample ray leaving light source for virtual light path
            LightSample ls(lightSampPos[2*sampOffset], lightSampPos[2*sampOffset+1],
                           lightSampComp[sampOffset]);
            LightInfo2 li = light->Sample_L(scene, ls, lightSampDir[2*sampOffset],
                                             lightSampDir[2*sampOffset+1],
                                             camera->shutterOpen);
            RayDifferential ray(li.ray);
            Spectrum alpha(li.L);

            if (li.pdf == 0.f || alpha.IsBlack()) continue;
            alpha /= li.pdf * lightPdf;
            Intersection isect;
            auto optIsect = scene.Intersect(ray);
            while (optIsect && !alpha.IsBlack()) {
                // Create virtual light and sample new ray for path
                alpha *= renderer->Transmittance(scene, RayDifferential(ray), NULL,
                                                 rng, arena);
                Vector wo = -ray.d;
                BSDF *bsdf = optIsect->GetBSDF(ray, arena);

                // Create virtual light at ray intersection point
                Spectrum contrib = alpha * bsdf->rho(wo, rng) / M_PI;
                virtualLights[s].push_back(VirtualLight(optIsect->dg.p, optIsect->dg.nn, contrib,
                                                        optIsect->rayEpsilon));

                // Sample new ray direction and update weight for virtual light path
                Vector wi;
                float pdf;
                BSDFSample bsdfSample(rng);
                Spectrum fr = bsdf->Sample_f(wo, &wi, bsdfSample, &pdf);
                if (fr.IsBlack() || pdf == 0.f)
                    break;
                Spectrum contribScale = fr * AbsDot(wi, bsdf->dgShading.nn) / pdf;

                // Possibly terminate virtual light path with Russian roulette
                float rrProb = min(1.f, contribScale.y());
                if (rng.RandomFloat() > rrProb)
                    break;
                alpha *= contribScale / rrProb;
                ray = RayDifferential(optIsect->dg.p, wi, ray, optIsect->rayEpsilon);
                optIsect = scene.Intersect(ray);
            }
            arena.FreeAll();
        }
    }
    delete lightDistribution;
}
Vector UnconstrainedLocalSearch::find_gcp(const Vector& gk, const Matrix& Bk, const Vector& zk,  const IntervalVector& region) {

	// ====================== STEP 2.0 : initialization ======================

	////  cout << " [find_gcp] initial region=" << region << endl;
	// The Cauchy point
	Vector z_gcp = zk;
	//  cout << " [find_gcp] initial zk=" << zk << endl;

	// The opposite of the gradient of z->z^T*Bk*z - gk^T z
	Vector g = gk - Bk*zk;

	// Compute a descent direction d
	// that must "point" inside the box
	Vector d(n);

	// If the function decreases wrt the ith dimension
	// and the point zk is very close (less than sigma) to the
	// ith "upper face" of the bounding box then we project
	// the gradient on this face (we nullify the ith component).
	// We apply the symmetric case with the "lower face".
	// The constraint x=ui or x=li is activated.
	for (int i = 0 ; i < n ; i++) {
		if(  fabs(gk[i]) > sigma &&
				((gk[i] < 0 && zk[i] < box[i].ub() - sigma) ||
				 (gk[i] > 0 && zk[i] > box[i].lb() + sigma)) )
			d[i] = -gk[i];
		// else d[i] remains equal to 0.
	}
	//  cout << " [find_gcp] initial d=" << d << endl;
	// compute f'
	double fp = gk*d;
	//  cout << " [find_gcp] initial fp=" << fp << endl;

	// compute f''
	double fs = d*(Bk*d);
	//  cout << " [find_gcp] initial fs=" << fs << endl;


	bool gcp_found = (fp >= -eps);

	try {

		while (!gcp_found) {
			// ====================== STEP 2.1 : Find the next breakpoint ======================

			LineSearch ls(region,z_gcp,d,data,sigma); // if d~0, an exception is raised

			double deltat = ls.alpha_max();
			//  cout << " [find_gcp] deltat=" << deltat << endl;

			// check if we are in a corner
			// deltat can be very large even if the norm of the gradient is > eps
			// because once the "large" dimensions are treated, it may only
			// remains directions with d[i] very small (but not less than sigma).
			// In any case, we have deltat <= 1/sigma*diam(region) <= 2*Delta/sigma.

			//		assert(deltat<10*(2*Delta/sigma));

			// ====================== STEP 2.2 : Test whether the GCP has been found ======================

			// The minimum is in the segment [0,deltat]
			if ((fs > 0.0) && (0<-(fp/fs)) && (-(fp/fs)<deltat)) {
				z_gcp -= (fp/fs)*d;

				// Security check: z_gcp may be outside the region because of rounding
				ls.proj(z_gcp);

				gcp_found = true;
			}
			else {

				// ====================== STEP 2.3 : Update line derivatives ======================

				// b = Bk*(\sum_{I[i]==2} di*ei)
				Vector b(n);
				for (int i=0; i<n; i++) {
					if (ls.next_activated(i)) {
						for (int j=0; j<n; j++) b[j]+=d[i]*Bk[j][i];
					}
				}

				// set gcp to the the point on the face
				z_gcp = ls.endpoint();

				// update f'
				fp += deltat*fs - b*z_gcp;

				for (int i=0; i<n; i++) {
					if (ls.next_activated(i)) fp -= d[i]*g[i];
				}

				// update f''
				for (int i=0; i<n; i++) {
					fs -= (ls.next_activated(i) ? b[i]*d[i] : 2.0*b[i]*d[i]);
				}

				// update d and I
				for (int i=0; i<n; i++) {
					if (ls.next_activated(i)) {
						//  cout << " [find_gcp] activate ctr n°" << i << endl;
						d[i] = 0.0;
					}
				}

				//  cout << " [find_gcp] current d=" << d << endl;
				//  cout << " [find_gcp] current z_gcp=" << z_gcp << endl;
				//  cout << " [find_gcp] current fp=" << fp << endl;
				//  cout << " [find_gcp] current fs=" << fs << endl;
				// update the termination condition
				gcp_found = (fp >= -eps); // the minimum is at a breakpoint
			}
		}
	}
	catch(LineSearch::NullDirectionException&) {
		// we are in a corner of the region: we stop with current z_gcp
	}

	// ====================== STEP 2.4 : termination with GCP ======================
	//  cout << " [find_gcp] z_gcp =" << z_gcp << endl;
	assert(region.contains(z_gcp));

	return z_gcp;
}
STKUNIT_UNIT_TEST(UnitTestLinsysFunctions, test1)
{
  static const size_t spatial_dimension = 3;

  MPI_Barrier( MPI_COMM_WORLD );
  MPI_Comm comm = MPI_COMM_WORLD;
  //First create and fill MetaData and BulkData objects:

  const unsigned bucket_size = 100; //for a real application mesh, bucket_size would be much bigger...

  stk_classic::mesh::fem::FEMMetaData fem_meta;
  stk_classic::mesh::fem::FEMMetaData fem_meta2;
  fem_meta.FEM_initialize(spatial_dimension);
  fem_meta2.FEM_initialize(spatial_dimension);

  stk_classic::mesh::MetaData & meta_data = stk_classic::mesh::fem::FEMMetaData::get_meta_data(fem_meta);
  stk_classic::mesh::MetaData & meta_data2 = stk_classic::mesh::fem::FEMMetaData::get_meta_data(fem_meta2);

  const stk_classic::mesh::EntityRank element_rank = fem_meta.element_rank();

  stk_classic::mesh::BulkData bulk_data( meta_data, comm, bucket_size );
  stk_classic::mesh::BulkData bulk_data2( meta_data2, comm, bucket_size );

  //create a boundary-condition part for testing later:
  stk_classic::mesh::Part& bcpart = fem_meta.declare_part("bcpart");

  fill_utest_mesh_meta_data( fem_meta );

  bool use_temperature=false;
  fill_utest_mesh_meta_data( fem_meta2, use_temperature );

  fill_utest_mesh_bulk_data( bulk_data );
  fill_utest_mesh_bulk_data( bulk_data2 );

  //set owner-processors to lowest-sharing (stk_classic::mesh defaults to
  //highest-sharing) If highest-sharing owns, then it isn't correct for the
  //way the fei library sets ownership of shared nodes for vectors etc.
  stk_classic::mesh::set_owners<stk_classic::mesh::LowestRankSharingProcOwns>( bulk_data );

  //put a node in our boundary-condition part. arbitrarily choose the
  //first locally-owned node:

  bulk_data.modification_begin();

  std::vector<stk_classic::mesh::Entity*> local_nodes;
  stk_classic::mesh::Selector select_owned(meta_data.locally_owned_part());
  stk_classic::mesh::get_selected_entities(select_owned,
                                   bulk_data.buckets(NODE_RANK),
                                   local_nodes);

  stk_classic::mesh::EntityId bc_node_id = 0;

  if (local_nodes.size() > 0) {
    stk_classic::mesh::PartVector partvector;
    partvector.push_back(&bcpart);
    bulk_data.change_entity_parts(*local_nodes[0], partvector);
    bc_node_id = stk_classic::linsys::impl::entityid_to_int(local_nodes[0]->identifier());
  }

  bulk_data.modification_end();

  stk_classic::mesh::Selector selector = ( meta_data.locally_owned_part() | meta_data.globally_shared_part() ) & *meta_data.get_part("block_1");
  std::vector<unsigned> count;
  stk_classic::mesh::count_entities(selector, bulk_data, count);

  STKUNIT_ASSERT_EQUAL( count[element_rank], (unsigned)4 );
  STKUNIT_ASSERT_EQUAL( count[NODE_RANK],     (unsigned)20 );

  ScalarField* temperature_field = meta_data.get_field<ScalarField>("temperature");

  //Create a fei Factory and stk_classic::linsys::LinearSystem object:

  fei::SharedPtr<fei::Factory> factory(new Factory_Trilinos(comm));

  stk_classic::linsys::LinearSystem ls(comm, factory);

  stk_classic::linsys::add_connectivities(ls, element_rank, NODE_RANK,
                                  *temperature_field, selector, bulk_data);

  fei::SharedPtr<fei::MatrixGraph> matgraph = ls.get_fei_MatrixGraph();
  int num_blocks = matgraph->getNumConnectivityBlocks();

  STKUNIT_ASSERT_EQUAL( num_blocks, (int)1 );

  ls.synchronize_mappings_and_structure();
  ls.create_fei_LinearSystem();

  //put 0 throughout the matrix and 3 throughout the rhs:
  fei::SharedPtr<fei::Matrix> mat = ls.get_fei_LinearSystem()->getMatrix();
  ls.get_fei_LinearSystem()->getMatrix()->putScalar(0);
  ls.get_fei_LinearSystem()->getRHS()->putScalar(3.0);

  //put 10 on the matrix diagonal to ensure it will be easy to solve later.
  fei::SharedPtr<fei::VectorSpace> vspace = ls.get_fei_LinearSystem()->getRHS()->getVectorSpace();
  int numLocalRows = vspace->getNumIndices_Owned();
  std::vector<int> local_rows(numLocalRows);
  vspace->getIndices_Owned(numLocalRows, &local_rows[0], numLocalRows);

  for(size_t i=0; i<local_rows.size(); ++i) {
    int col = local_rows[i];
    double coef = 10;
    double* coefPtr = &coef;
    mat->sumIn(1, &local_rows[i], 1, &col, &coefPtr);
  }

  //now we'll impose a dirichlet bc on our one-node bcpart:
  stk_classic::linsys::dirichlet_bc(ls, bulk_data, bcpart, NODE_RANK,
                            *temperature_field, 0, 9.0);

  ls.finalize_assembly();

  //now confirm that the rhs value for the equation corresponding to our
  //bc node is 9.0:

  fei::SharedPtr<fei::Vector> rhsvec = ls.get_fei_LinearSystem()->getRHS();
  double rhs_bc_val = 0;
  int bc_eqn_index = ls.get_DofMapper().get_global_index(NODE_RANK,
           bc_node_id, *temperature_field);
  rhsvec->copyOut(1, &bc_eqn_index, &rhs_bc_val);

  bool bc_val_is_correct = std::abs(rhs_bc_val - 9.0) < 1.e-13;
  STKUNIT_ASSERT( bc_val_is_correct );

  stk_classic::linsys::copy_vector_to_mesh( *rhsvec, ls.get_DofMapper(), bulk_data);

  stk_classic::mesh::Entity* bc_node = bulk_data.get_entity(NODE_RANK, local_nodes[0]->identifier());

  stk_classic::mesh::FieldTraits<ScalarField>::data_type* bc_node_data = stk_classic::mesh::field_data(*temperature_field, *bc_node);

  bool bc_node_data_is_correct = std::abs(bc_node_data[0] - 9.0) < 1.e-13;
  STKUNIT_ASSERT( bc_node_data_is_correct );

  //now make sure we get a throw if we use the wrong bulk-data (that doesn't have the
  //temperature field defined)
  STKUNIT_ASSERT_THROW(stk_classic::linsys::copy_vector_to_mesh( *rhsvec, ls.get_DofMapper(), bulk_data2), std::runtime_error);

  //obtain and zero the solution vector
  fei::SharedPtr<fei::Vector> solnvec = ls.get_fei_LinearSystem()->getSolutionVector();
  solnvec->putScalar(0);

  //copy the vector of zeros into the mesh:
  stk_classic::linsys::copy_vector_to_mesh( *solnvec, ls.get_DofMapper(), bulk_data);

  //assert that our bc node's data is now zero.
  bc_node_data_is_correct = std::abs(bc_node_data[0] - 0) < 1.e-13;
  STKUNIT_ASSERT( bc_node_data_is_correct );

  //call the linear-system solve function.
  //(note that when we add options to the solve method, we'll need to enhance this
  //testing to exercise various specific solves.)
  Teuchos::ParameterList params;

  int status = 0;
  ls.solve(status, params);

  //copy the solution-vector into the mesh:
  stk_classic::linsys::copy_vector_to_mesh( *solnvec, ls.get_DofMapper(), bulk_data);

  //now assert that the value 9 (bc value) produced by the solve is in this
  //node's data.
  //note that we use a loose tolerance, because the default solver tolerance
  //is (I think) only 1.e-6.
  bc_node_data_is_correct = std::abs(bc_node_data[0] - 9.0) < 1.e-6;
  STKUNIT_ASSERT( bc_node_data_is_correct );
  STKUNIT_ASSERT(bc_node_data_is_correct);
}
Exemple #11
0
//
// Functions
//
int looper( sampleInfo::ID sampleID, std::vector<analyzer*> analyzers, int nEvents, bool readFast ) {


  //
  // Intro
  //
  cout << "====================================================" << endl;
  cout << endl;
  cout << "  WELCOME TO STOP BABY ANALYZER! " << endl;
  cout << endl;
  cout << "====================================================" << endl;
  cout << endl;


  //
  // Benchmark
  //
  TBenchmark *bmark = new TBenchmark();
  bmark->Start("benchmark");
  

  //
  // Input SampleInfo
  //
  sampleInfo::sampleUtil sample( sampleID );

  bool sampleIsTTbar = false;
  if( sample.id == sampleInfo::k_ttbar_powheg_pythia8 ||
      sample.id == sampleInfo::k_ttbar_powheg_pythia8_ext4 ||
      sample.id == sampleInfo::k_ttbar_singleLeptFromT_madgraph_pythia8 ||
      sample.id == sampleInfo::k_ttbar_singleLeptFromT_madgraph_pythia8_ext1 ||
      sample.id == sampleInfo::k_ttbar_singleLeptFromTbar_madgraph_pythia8 ||
      sample.id == sampleInfo::k_ttbar_singleLeptFromTbar_madgraph_pythia8_ext1 ||
      sample.id == sampleInfo::k_ttbar_diLept_madgraph_pythia8 ||
      sample.id == sampleInfo::k_ttbar_diLept_madgraph_pythia8_ext1 ) {
    sampleIsTTbar = true;
  }
  
  //
  // Input chain
  //
  TChain *chain = new TChain("t");
  
  cout << "    Processing the following: " << endl;  
  for(int iFile=0; iFile<(int)sample.inputBabies.size(); iFile++) {
    
    // input directory
    string input = sample.baby_i_o.first;
      
    // input file
    input += sample.inputBabies[iFile];
      
    chain->Add( input.c_str() );
    cout << "      " << input << endl; 
  }
  cout << endl;
  
  
  //
  // Output File
  //

  // output dir
  string f_output_name = "";
  f_output_name += sample.baby_i_o.second;

  // output name
  f_output_name += sample.label;
  f_output_name += ".root";

  // output file
  TFile *f_output = new TFile( f_output_name.c_str(), "recreate" );

  // print output location
  cout << "    Output Written to: " << endl;
  cout << "      " << f_output_name << endl;
  cout << endl;


  //
  // JSON File Tools
  //
  const char* json_file = "../StopCORE/inputs/json_files/Cert_271036-284044_13TeV_23Sep2016ReReco_Collisions16_JSON.txt"; // 35.876fb final 2016 run
  if( sample.isData ) set_goodrun_file_json(json_file);
  

  //
  // Event Weight Utilities
  //
  cout << "    Loading eventWeight Utilities..." << endl << endl;
  wgtInfo.setUp( sample.id, useBTagSFs_fromFiles_, useLepSFs_fromFiles_, add2ndLepToMet_ );  
  wgtInfo.apply_cr2lTrigger_sf  = (apply_cr2lTrigger_sf_ && add2ndLepToMet_);
  wgtInfo.apply_bTag_sf         = apply_bTag_sf_;
  wgtInfo.apply_lep_sf          = apply_lep_sf_;
  wgtInfo.apply_vetoLep_sf      = apply_vetoLep_sf_;
  wgtInfo.apply_tau_sf          = apply_tau_sf_;
  wgtInfo.apply_lepFS_sf        = apply_lepFS_sf_;
  wgtInfo.apply_topPt_sf        = apply_topPt_sf_;
  wgtInfo.apply_metRes_sf       = apply_metRes_sf_;
  wgtInfo.apply_metTTbar_sf     = apply_metTTbar_sf_;
  wgtInfo.apply_ttbarSysPt_sf   = apply_ttbarSysPt_sf_;
  wgtInfo.apply_ISR_sf          = apply_ISR_sf_;
  wgtInfo.apply_pu_sf           = apply_pu_sf_;
  wgtInfo.apply_sample_sf       = apply_sample_sf_;


  //
  // Declare genClassification list
  //
  cout << "    Loading genClassyList: ";
  std::vector< genClassyInfo::Util > genClassyList;
  if( sample.isData ) {
    genClassyList.push_back(genClassyInfo::Util(genClassyInfo::k_incl));
  }
  else{
    for(int iGenClassy=0; iGenClassy<genClassyInfo::k_nGenClassy; iGenClassy++) {
      genClassyList.push_back( genClassyInfo::Util(genClassyInfo::ID(iGenClassy)) );
    }
  }
  const int nGenClassy=(int)genClassyList.size();
  cout << nGenClassy << " genClassifications" << endl << endl;

  
  //
  // Declare Systematics
  //
  cout << "    Loading systematicList: ";
  std::vector< sysInfo::Util > systematicList;
  if( sample.isData || analyzeFast_ ) {
    systematicList.push_back(sysInfo::Util(sysInfo::k_nominal));
  }
  else{
    for(int iSys=0; iSys<sysInfo::k_nSys; iSys++) {
      systematicList.push_back( sysInfo::Util(sysInfo::ID(iSys)) );
    }
  }  
  const int nSystematics = (int)systematicList.size();
  cout << nSystematics << " systematics" << endl << endl;


	// Count number of analyzers in the list
	const int nAnalyzers = analyzers.size();



  ////////////////////////
  //                    //
  // Declare Histograms //
  //                    //
  ////////////////////////
  //
  //
  //  For Using DownStream Scripts, please adhere to the conventions:
  //
  //
  //    histogram_name = "your_name_here"+"__"+regionList[i]+"__genClassy_"+genClassyObject.label+"__systematic_"+sysInfoObject.label;
  //
  //
  //  Where regionList is the list of "SR", "CR0b", "CR0b_tightBTagHighMlb" or "CR2l"
  //
  //    And systematicList[0] is the nominal selection
  //
  //    And if there is andditional selection involved in this histogram, please refer to it in "you name here"
  //

  cout << "    Preparing histograms" << endl << endl;


	//
	// Declare yield histograms
	//
  f_output->cd(); // All yield histos will belong to the output file
	for( analyzer* thisAnalyzer : analyzers ) {

		TH1D* h_template = thisAnalyzer->GetYieldTemplate();
		TH3D* h_template_signal = thisAnalyzer->GetYieldTemplateSignal();

		for( int iClassy=0; iClassy<nGenClassy; iClassy++ ) {
			for( int iSys=0; iSys<nSystematics; iSys++ ) {

				int histIndex = iClassy*nSystematics + iSys;

				// Gen and Systematic String
				TString reg_gen_sys_name = "__";
				reg_gen_sys_name += thisAnalyzer->GetLabel();
				reg_gen_sys_name += "__genClassy_";
				reg_gen_sys_name += genClassyList[iClassy].label;
				reg_gen_sys_name += "__systematic_";
				reg_gen_sys_name += systematicList[iSys].label;

				TH1* h_tmp = 0;

				TString yieldname = "h_yields";
				yieldname += reg_gen_sys_name;
				if( sample.isSignalScan ) h_tmp = (TH3D*)h_template_signal->Clone( yieldname );
				else                      h_tmp = (TH1D*)h_template->Clone( yieldname );
				thisAnalyzer->SetYieldHistogram( histIndex, h_tmp );

			} // End loop over systematics
		} // End loop over genClassys
	} // End loop over analyzers

  
  
  

  //
  // Declare non-yield histograms
  //

  int nMassPts = 1;
  if( sample.isSignalScan ) nMassPts = (int)sample.massPtList.size();

  const int nHistosVars = nAnalyzers*nGenClassy*nMassPts;

  // nJets
  TH1D *h_nJets[nHistosVars];
  
  // nBTags
  TH1D *h_nBTags[nHistosVars];
  
  // lep1 pT
  TH1D *h_lep1Pt_incl[nHistosVars];
  
  // lep2 pT
  TH1D *h_lep2Pt_incl[nHistosVars];
  
  // jet pT
  TH1D *h_jetPt_incl[nHistosVars];
  
  // jet1 pT
  TH1D *h_jet1Pt_incl[nHistosVars];
  
  // jet2 pT
  TH1D *h_jet2Pt_incl[nHistosVars];
  
  // DeepCSV jet1 pT
  TH1D *h_deepcsvJet1Pt_incl[nHistosVars];
  
  // DeepCSV jet2 pT
  TH1D *h_deepcsvJet2Pt_incl[nHistosVars];
  
  // met
  TH1D *h_met_incl[nHistosVars];
  TH1D *h_met_lt4j[nHistosVars];
  TH1D *h_met_ge4j[nHistosVars];

  // lep1lep2bbMetPt
  TH1D *h_lep1lep2bbMetPt_incl[nHistosVars];
  TH1D *h_lep1lep2bbMetPt_lt4j[nHistosVars];
  TH1D *h_lep1lep2bbMetPt_ge4j[nHistosVars];

  // mt
  TH1D *h_mt_incl[nHistosVars];
  
  // modTopness
  TH1D *h_modTopness_incl[nHistosVars];
  TH1D *h_modTopness_lt4j[nHistosVars];
  TH1D *h_modTopness_ge4j[nHistosVars];

  // mlb
  TH1D *h_mlb_incl[nHistosVars];
  TH1D *h_mlb_lt4j[nHistosVars];
  TH1D *h_mlb_ge4j[nHistosVars];

  // mlb
  TH1D *h_mlb_lt0modTopness[nHistosVars];
  TH1D *h_mlb_ge0modTopness[nHistosVars];
  TH1D *h_mlb_ge10modTopness[nHistosVars];
  
  // mlb, met sideband CR
  TH1D *h_mlb_150to250met_incl[nHistosVars];
  TH1D *h_mlb_150to250met_lt4j[nHistosVars];
  TH1D *h_mlb_150to250met_ge4j[nHistosVars];

  // ml2b
  TH1D *h_mlb_lep2_incl[nHistosVars];
  TH1D *h_mlb_lep2_lt4j[nHistosVars];
  TH1D *h_mlb_lep2_ge4j[nHistosVars];
  
  // ml2b
  TH1D *h_mlb_lep2_150to250met_incl[nHistosVars];
  TH1D *h_mlb_lep2_150to250met_lt4j[nHistosVars];
  TH1D *h_mlb_lep2_150to250met_ge4j[nHistosVars];

  // Gen ttbar system pT
  TH1D *h_gen_ttbarPt_incl[nHistosVars];
  TH1D *h_gen_ttbarPt_lt4j[nHistosVars];
  TH1D *h_gen_ttbarPt_ge4j[nHistosVars];

  // Gen 2nd lepton ID
  TH1D *h_gen_lep2_id_incl[nHistosVars];
  TH1D *h_gen_lep2_id_lt4j[nHistosVars];
  TH1D *h_gen_lep2_id_ge4j[nHistosVars];

  f_output->cd(); // All non-yield histos will belong to the output file
  
  for(int iReg=0; iReg<nAnalyzers; iReg++) {
    for(int iGen=0; iGen<nGenClassy; iGen++) {
      for(int iMassPt=0; iMassPt<nMassPts; iMassPt++) {

				// Histo Index
				int iHisto = iReg*nGenClassy*nMassPts + iGen*nMassPts + iMassPt;

				int mStop = 0;
				int mLSP  = 0;
				if(sample.isSignalScan) {
					mStop = sample.massPtList[iMassPt].first;
					mLSP  = sample.massPtList[iMassPt].second;
				}

				TString hName = "";
	
				TString reg_gen_sys_name = "__";
				reg_gen_sys_name += analyzers.at(iReg)->GetLabel();
				reg_gen_sys_name += "__genClassy_";
				reg_gen_sys_name += genClassyList[iGen].label;
				reg_gen_sys_name += "__systematic_";
				reg_gen_sys_name += systematicList[0].label;
				if( sample.isSignalScan ) {
					reg_gen_sys_name += "__mStop_";
					reg_gen_sys_name += mStop;
					reg_gen_sys_name += "__mLSP_";
					reg_gen_sys_name += mLSP;
				}

      
				//
				// Njets
				//
				hName = "h_nJets" + reg_gen_sys_name;
				h_nJets[iHisto] = new TH1D( hName, "Number of Selected Jets;nJets", 11, -0.5, 10.5);

				//
				// nBTags
				//
				hName = "h_nBTags" + reg_gen_sys_name;
				h_nBTags[iHisto] = new TH1D( hName, "Number of b-Tagged Jets;nBTags", 5, -0.5, 4.5);


				//
				// lep1Pt
				//

				// Incl Selection
				hName = "h_lep1Pt__inclSelection" + reg_gen_sys_name;
				h_lep1Pt_incl[iHisto] = new TH1D( hName, "Lepton p_{T};p_{T} [GeV]", 20.0, 0.0, 200.0 );
      
	

				//
				// lep2Pt
				//

				// Incl Selection
				hName = "h_lep2Pt__inclSelection" + reg_gen_sys_name;
				h_lep2Pt_incl[iHisto] = new TH1D( hName, "Trailing Lepton p_{T};p_{T} [GeV]", 20.0, 0.0, 200.0 );
      
				//
				// jetPt
				//

				// Incl Selection
				hName = "h_jetPt__inclSelection" + reg_gen_sys_name;
				h_jetPt_incl[iHisto] = new TH1D( hName, "Jet p_{T};p_{T} [GeV]", 24, 0.0, 600.0 );
	
				//
				// jet1Pt
				//

				// Incl Selection
				hName = "h_jet1Pt__inclSelection" + reg_gen_sys_name;
				h_jet1Pt_incl[iHisto] = new TH1D( hName, "Leading Jet p_{T};p_{T} [GeV]", 24, 0.0, 600.0 );
	
	

				//
				// jet2Pt
				//

				// Incl Selection
				hName = "h_jet2Pt__inclSelection" + reg_gen_sys_name;
				h_jet2Pt_incl[iHisto] = new TH1D( hName, "2nd Leading Jet p_{T};p_{T} [GeV]", 24, 0.0, 600.0 );
      
	
				//
				// DeepCSVJet1Pt
				//

				// Incl Selection
				hName = "h_deepcsvJet1Pt__inclSelection" + reg_gen_sys_name;
				h_deepcsvJet1Pt_incl[iHisto] = new TH1D( hName, "Leading DeepCSV Jet p_{T};p_{T} [GeV]", 24, 0.0, 600.0 );
      
	

				//
				// DeepCSVJet2Pt
				//

				// Incl Selection
				hName = "h_deepcsvJet2Pt__inclSelection" + reg_gen_sys_name;
				h_deepcsvJet2Pt_incl[iHisto] = new TH1D( hName, "2nd Leading DeepCSV Jet p_{T};p_{T} [GeV]", 24, 0.0, 600.0 );
      
	

				//
				// met
				//

				// Incl Selection
				hName = "h_met__inclSelection" + reg_gen_sys_name;
				h_met_incl[iHisto] = new TH1D( hName, "MET;MET [GeV]", 32, 0.0, 800.0 );
      
				// <4j Selection
				hName = "h_met__lt4jSelection" + reg_gen_sys_name;
				h_met_lt4j[iHisto] = new TH1D( hName, "MET;MET [GeV]", 32, 0.0, 800.0 );

				// >=4j Selection
				hName = "h_met__ge4jSelection" + reg_gen_sys_name;
				h_met_ge4j[iHisto] = new TH1D( hName, "MET;MET [GeV]", 32, 0.0, 800.0 );


	

				//
				// lep1lep2bbMetPt
				//

				// Incl Selection
				hName = "h_lep1lep2bbMetPt__inclSelection" + reg_gen_sys_name;
				h_lep1lep2bbMetPt_incl[iHisto] = new TH1D( hName, "lep1(lep2)bbMet system p_{T};p_{T} [GeV]", 24, 0.0, 600.0 );
	
				// <4j Selection
				hName = "h_lep1lep2bbMetPt__lt4jSelection" + reg_gen_sys_name;
				h_lep1lep2bbMetPt_lt4j[iHisto] = new TH1D( hName, "lep1(lep2)bbMet system p_{T};p_{T} [GeV]", 24, 0.0, 600.0 );

				// >=4j Selection
				hName = "h_lep1lep2bbMetPt__ge4jSelection" + reg_gen_sys_name;
				h_lep1lep2bbMetPt_ge4j[iHisto] = new TH1D( hName, "lep1(lep2)bbMet system p_{T};p_{T} [GeV]", 24, 0.0, 600.0 );


				//
				// mt
				//

				// Incl Selection
				hName = "h_mt__inclSelection" + reg_gen_sys_name;
				h_mt_incl[iHisto] = new TH1D( hName, "M_{T};M_{T} [GeV]", 24, 0.0, 600.0 );
      
	
				//
				// modTopness
				//

				// Incl Selection
				hName = "h_modTopness__inclSelection" + reg_gen_sys_name;
				h_modTopness_incl[iHisto] = new TH1D( hName, "Modified Topness;Modified Topness", 20, -20.0, 20.0 );
      
				// <4j Selection
				hName = "h_modTopness__lt4jSelection" + reg_gen_sys_name;
				h_modTopness_lt4j[iHisto] = new TH1D( hName, "Modified Topness;Modified Topness", 20, -20.0, 20.0 );

				// >=4j Selection
				hName = "h_modTopness__ge4jSelection" + reg_gen_sys_name;
				h_modTopness_ge4j[iHisto] = new TH1D( hName, "Modified Topness;Modified Topness", 20, -20.0, 20.0 );

      
				//
				// mlb
				//

				// Incl Selection
				hName = "h_mlb__inclSelection" + reg_gen_sys_name;
				h_mlb_incl[iHisto] = new TH1D( hName, "M_{lb};M_{lb} [GeV]", 24, 0.0, 600.0 );
      
				// <4j Selection
				hName = "h_mlb__lt4jSelection" + reg_gen_sys_name;
				h_mlb_lt4j[iHisto] = new TH1D( hName, "M_{lb};M_{lb} [GeV]", 24, 0.0, 600.0 );

				// >=4j Selection
				hName = "h_mlb__ge4jSelection" + reg_gen_sys_name;
				h_mlb_ge4j[iHisto] = new TH1D( hName, "M_{lb};M_{lb} [GeV]", 24, 0.0, 600.0 );

      

				//
				// mlb, inclusive nJets, modTopness bins
				//

				// <0 modTopness Selection
				hName = "h_mlb__lt0modTopnessSelection" + reg_gen_sys_name;
				h_mlb_lt0modTopness[iHisto] = new TH1D( hName, "M_{lb};M_{lb} [GeV]", 24, 0.0, 600.0 );

				// >=0 modTopness Selection
				hName = "h_mlb__ge0modTopnessSelection" + reg_gen_sys_name;
				h_mlb_ge0modTopness[iHisto] = new TH1D( hName, "M_{lb};M_{lb} [GeV]", 24, 0.0, 600.0 );
      
				// >=10 modTopness Selection
				hName = "h_mlb__ge10modTopnessSelection" + reg_gen_sys_name;
				h_mlb_ge10modTopness[iHisto] = new TH1D( hName, "M_{lb};M_{lb} [GeV]", 24, 0.0, 600.0 );


				//
				// mlb, met sideband CR
				//

				// Incl Selection
				hName = "h_mlb_150to250met__inclSelection" + reg_gen_sys_name;
				h_mlb_150to250met_incl[iHisto] = new TH1D( hName, "M_{lb};M_{lb} [GeV]", 24, 0.0, 600.0 );
      
				// <4j Selection
				hName = "h_mlb_150to250met__lt4jSelection" + reg_gen_sys_name;
				h_mlb_150to250met_lt4j[iHisto] = new TH1D( hName, "M_{lb};M_{lb} [GeV]", 24, 0.0, 600.0 );

				// >=4j Selection
				hName = "h_mlb_150to250met__ge4jSelection" + reg_gen_sys_name;
				h_mlb_150to250met_ge4j[iHisto] = new TH1D( hName, "M_{lb};M_{lb} [GeV]", 24, 0.0, 600.0 );


				//
				// mlb_lep2
				//

				// Incl Selection
				hName = "h_mlb_lep2__inclSelection" + reg_gen_sys_name;
				h_mlb_lep2_incl[iHisto] = new TH1D( hName, "M_{l2b};M_{l2b} [GeV]", 24, 0.0, 600.0 );
      
				// <4j Selection
				hName = "h_mlb_lep2__lt4jSelection" + reg_gen_sys_name;
				h_mlb_lep2_lt4j[iHisto] = new TH1D( hName, "M_{l2b};M_{l2b} [GeV]", 24, 0.0, 600.0 );

				// >=4j Selection
				hName = "h_mlb_lep2__ge4jSelection" + reg_gen_sys_name;
				h_mlb_lep2_ge4j[iHisto] = new TH1D( hName, "M_{l2b};M_{l2b} [GeV]", 24, 0.0, 600.0 );



				//
				// mlb_lep2, met CR sideband
				//

				// Incl Selection
				hName = "h_mlb_lep2_150to250met__inclSelection" + reg_gen_sys_name;
				h_mlb_lep2_150to250met_incl[iHisto] = new TH1D( hName, "M_{l2b};M_{l2b} [GeV]", 24, 0.0, 600.0 );
      
				// <4j Selection
				hName = "h_mlb_lep2_150to250met__lt4jSelection" + reg_gen_sys_name;
				h_mlb_lep2_150to250met_lt4j[iHisto] = new TH1D( hName, "M_{l2b};M_{l2b} [GeV]", 24, 0.0, 600.0 );

				// >=4j Selection
				hName = "h_mlb_lep2_150to250met__ge4jSelection" + reg_gen_sys_name;
				h_mlb_lep2_150to250met_ge4j[iHisto] = new TH1D( hName, "M_{l2b};M_{l2b} [GeV]", 24, 0.0, 600.0 );



	

				//
				// Gen ttbar pT
				//
				if( !sample.isData ) {
    
					// Incl Selection
					hName = "h_gen_ttbarPt__inclSelection" + reg_gen_sys_name;
					h_gen_ttbarPt_incl[iHisto] = new TH1D( hName, "Gen t#bar{t} system p_{T};p_{T} [GeV]", 24, 0.0, 600.0 );
	
					// <4j Selection
					hName = "h_gen_ttbarPt__lt4jSelection" + reg_gen_sys_name;
					h_gen_ttbarPt_lt4j[iHisto] = new TH1D( hName, "Gen t#bar{t} system p_{T};p_{T} [GeV]", 24, 0.0, 600.0 );

					// >=4j Selection
					hName = "h_gen_ttbarPt__ge4jSelection" + reg_gen_sys_name;
					h_gen_ttbarPt_ge4j[iHisto] = new TH1D( hName, "Gen t#bar{t} system p_{T};p_{T} [GeV]", 24, 0.0, 600.0 );



					//
					// Gen Lep2 ID
					//
      
					// Incl Selection
					hName = "h_gen_lep2_id__inclSelection" + reg_gen_sys_name;
					h_gen_lep2_id_incl[iHisto] = new TH1D( hName, "Gen 2nd Lepton ID;ID", 7, 1.0, 8.0 );
					h_gen_lep2_id_incl[iHisto]->GetXaxis()->SetBinLabel(1, "ele");
					h_gen_lep2_id_incl[iHisto]->GetXaxis()->SetBinLabel(2, "mu");
					h_gen_lep2_id_incl[iHisto]->GetXaxis()->SetBinLabel(3, "lep tau, ele");
					h_gen_lep2_id_incl[iHisto]->GetXaxis()->SetBinLabel(4, "lep tau, mu");
					h_gen_lep2_id_incl[iHisto]->GetXaxis()->SetBinLabel(5, "had tau, 1 prong");
					h_gen_lep2_id_incl[iHisto]->GetXaxis()->SetBinLabel(6, "had tau, 3 prong");
					h_gen_lep2_id_incl[iHisto]->GetXaxis()->SetBinLabel(7, "\"other\" tau");
	
					// <4j Selection
					hName = "h_gen_lep2_id__lt4jSelection" + reg_gen_sys_name;
					h_gen_lep2_id_lt4j[iHisto] = new TH1D( hName, "Gen 2nd Lepton ID;ID", 7, 1.0, 8.0 );
					h_gen_lep2_id_lt4j[iHisto]->GetXaxis()->SetBinLabel(1, "ele");
					h_gen_lep2_id_lt4j[iHisto]->GetXaxis()->SetBinLabel(2, "mu");
					h_gen_lep2_id_lt4j[iHisto]->GetXaxis()->SetBinLabel(3, "lep tau, ele");
					h_gen_lep2_id_lt4j[iHisto]->GetXaxis()->SetBinLabel(4, "lep tau, mu");
					h_gen_lep2_id_lt4j[iHisto]->GetXaxis()->SetBinLabel(5, "had tau, 1 prong");
					h_gen_lep2_id_lt4j[iHisto]->GetXaxis()->SetBinLabel(6, "had tau, 3 prong");
					h_gen_lep2_id_lt4j[iHisto]->GetXaxis()->SetBinLabel(7, "\"other\" tau");

					// >=4j Selection
					hName = "h_gen_lep2_id__ge4jSelection" + reg_gen_sys_name;
					h_gen_lep2_id_ge4j[iHisto] = new TH1D( hName, "Gen 2nd Lepton ID;ID", 7, 1.0, 8.0 );
					h_gen_lep2_id_ge4j[iHisto]->GetXaxis()->SetBinLabel(1, "ele");
					h_gen_lep2_id_ge4j[iHisto]->GetXaxis()->SetBinLabel(2, "mu");
					h_gen_lep2_id_ge4j[iHisto]->GetXaxis()->SetBinLabel(3, "lep tau, ele");
					h_gen_lep2_id_ge4j[iHisto]->GetXaxis()->SetBinLabel(4, "lep tau, mu");
					h_gen_lep2_id_ge4j[iHisto]->GetXaxis()->SetBinLabel(5, "had tau, 1 prong");
					h_gen_lep2_id_ge4j[iHisto]->GetXaxis()->SetBinLabel(6, "had tau, 3 prong");
					h_gen_lep2_id_ge4j[iHisto]->GetXaxis()->SetBinLabel(7, "\"other\" tau");

	
				} // end if sample is ttbar
      

      } // end loop over mass pts (1 pt only if not signal scan)
    } // end loop over genClassifications for histogram arrays
  } // end loop over analyzers/regions for histogram arrays


	// Set up cutflow histograms
	TH1D* h_cutflow[nAnalyzers];
	for( int iAna=0; iAna<nAnalyzers; iAna++ ) {

		analyzer* thisAnalyzer = analyzers.at(iAna);
		std::string histName  = "h_cutflow_";
		std::string histTitle = "Cutflow histogram ";
		histName  += thisAnalyzer->GetLabel();
		histTitle += thisAnalyzer->GetLabel();

		h_cutflow[iAna] = selectionInfo::get_cutflowHistoTemplate( thisAnalyzer->GetSelections(), histName, histTitle );
	}


  //////////////////////
  //                  //
  // Loop Over Events //
  //                  //
  //////////////////////
    
  // Event Counters
  cout << "    Loading files to loop over" << endl << endl;
  unsigned int nEventsTotal = 0;
  unsigned int nEventsChain = chain->GetEntries();
  if( nEvents >= 0 ) nEventsChain = nEvents;
  
  // Grab list of files
  TObjArray *listOfFiles = chain->GetListOfFiles();
  TIter fileIter(listOfFiles);
  TFile *currentFile = 0;
  while ( (currentFile = (TFile*)fileIter.Next()) ) {
    
    
    //////////////////////
    //                  //
    // Get File Content //
    //                  //
    //////////////////////
    
    // Open File and Get Tree
    TFile *file = new TFile( currentFile->GetTitle(), "read" );
    TTree *tree = (TTree*)file->Get("t");
    if(readFast) TTreeCache::SetLearnEntries(10);
    if(readFast) tree->SetCacheSize(128*1024*1024);
    babyAnalyzer.Init(tree);
    
    // Get weight histogram from baby
    wgtInfo.getWeightHistogramFromBaby( file );
    
    // Loop over Events in current file
    if( nEventsTotal >= nEventsChain ) continue;
    unsigned int nEventsTree = tree->GetEntriesFast();
    for( unsigned int event = 0; event < nEventsTree; ++event) {

      
      ///////////////////////
      //                   //
      // Get Event Content //
      //                   //
      ///////////////////////
   
      // Read Tree
      if( nEventsTotal >= nEventsChain ) continue;
      if(readFast) tree->LoadTree(event);
      babyAnalyzer.GetEntry(event);
      ++nEventsTotal;

      // Progress
      stop_1l_babyAnalyzer::progress( nEventsTotal, nEventsChain );

      
      /////////////////////
      //                 //
      // Check Selection //
      //                 //
      /////////////////////


      // Check JSON
      if( sample.isData && applyjson ) {
	if( !goodrun(run(),ls()) ) continue;
      }
	
      // Check duplicate event
      if( sample.isData ) {
	duplicate_removal::DorkyEventIdentifier id(run(), evt(), ls());
	if( is_duplicate(id) ) continue;
      }

      // Check WNJets genPt
      if( sample.id == sampleInfo::k_W1JetsToLNu_madgraph_pythia8 ||
					sample.id == sampleInfo::k_W2JetsToLNu_madgraph_pythia8 ||
					sample.id == sampleInfo::k_W3JetsToLNu_madgraph_pythia8 ||
					sample.id == sampleInfo::k_W4JetsToLNu_madgraph_pythia8    ) {
				if( nupt()>200.0 ) continue;
      }

			// Pre-calculate all the event weights
      wgtInfo.getEventWeights();



      /////////////////////////////
      //                         //
      // Compute Event Variables //
      //                         //
      /////////////////////////////

      // Find the gen pT of the ttbar system
      double ttbarPt = -99.9;
      LorentzVector genTTbar_LV;
      int nFoundGenTop=0;
      if( sampleIsTTbar ) {
	
				for(int iGen=0; iGen<(int)genqs_p4().size(); iGen++) {
					if( abs(genqs_id().at(iGen))==6 && genqs_isLastCopy().at(iGen) ) {
						genTTbar_LV += genqs_p4().at(iGen);
						nFoundGenTop++;
					} // end if last copy of top
				} // end loop over gen quarks

				if( nFoundGenTop == 2 ) ttbarPt = genTTbar_LV.Pt();

      } // end if sample is ttbar

      
      // Find the gen ID of the 2nd lepton
      double matched_lep_dr = 0.1;

      int gen2ndLep__idx = -1;
      int gen2ndLep__id = -99;
      int gen2ndLep__tauDecay = -1;
      int fill_bin_genLep2ID = -1;
      if( !sample.isData && is2lep() ) {
	
				// match leading lepton first
				int genLep_matchedTo_selLep__idx = -1;
				for(int iGen=0; iGen<(int)genleps_p4().size(); iGen++) {
					if( abs(genleps_id().at(iGen)) != abs(lep1_pdgid()) ) continue;
					if( !genleps_isLastCopy().at(iGen) ) continue;
					if( !genleps_fromHardProcessFinalState().at(iGen) &&
							!genleps_fromHardProcessDecayed().at(iGen)       ) continue;
					if( ROOT::Math::VectorUtil::DeltaR(genleps_p4().at(iGen), lep1_p4()) < matched_lep_dr ) {
						genLep_matchedTo_selLep__idx = iGen;
						break;
					}
				}

				// If matched selected lepton, find lost gen lepton
				if( genLep_matchedTo_selLep__idx>0 ) {

					for(int iGen=0; iGen<(int)genleps_p4().size(); iGen++) {
						if( iGen == genLep_matchedTo_selLep__idx ) continue;
						if( !genleps_isLastCopy().at(iGen) ) continue;
						if( !genleps_fromHardProcessFinalState().at(iGen) &&
								!genleps_fromHardProcessDecayed().at(iGen)       ) continue;
						gen2ndLep__idx = iGen;
						gen2ndLep__id = genleps_id().at(iGen);
						gen2ndLep__tauDecay = genleps_gentaudecay().at(iGen);
					}

					// If found second lep
					if( gen2ndLep__idx>=0 ) {
	      
						if( abs(gen2ndLep__id)==11 ) fill_bin_genLep2ID = 1;  // "ele";
						if( abs(gen2ndLep__id)==13 ) fill_bin_genLep2ID = 2;  // "mu";
						if( abs(gen2ndLep__id)==15 ) {
							if( gen2ndLep__tauDecay==1 ) fill_bin_genLep2ID = 3;  // "lep tau, ele";
							if( gen2ndLep__tauDecay==2 ) fill_bin_genLep2ID = 4;  // "lep tau, mu";
							if( gen2ndLep__tauDecay==3 ) fill_bin_genLep2ID = 5;  // "had tau, 1 prong";
							if( gen2ndLep__tauDecay==4 ) fill_bin_genLep2ID = 6;  // "had tau, 3 prong";
							if( gen2ndLep__tauDecay==5 ) fill_bin_genLep2ID = 7;  // "\"other\" tau";
						} // end if 2nd lep is tau


					} // end if found 2nd gen lep
				} // end if found first gen lep, matched to selected lepton
      } // end if 2lep event and not data

      // Calculate p4 of (lep1 lep2 b b) system
      LorentzVector lep1lep2bb_TLV(0.0,0.0,0.0,0.0);

      LorentzVector lep1lep2bbMet_TLV(0.0,0.0,0.0,0.0);
      double lep1lep2bbMet_pt = -99.9;

      lep1lep2bb_TLV += lep1_p4();
      if(nvetoleps()>1) lep1lep2bb_TLV += lep2_p4();
      
      int jet1_idx = -1;
      double max_deepcsv = -99.9;
      for(int iJet=0; iJet<(int)ak4pfjets_p4().size(); iJet++) {
				if( ak4pfjets_deepCSV().at(iJet) > max_deepcsv ) {
					jet1_idx = iJet;
					max_deepcsv  = ak4pfjets_deepCSV().at(iJet);
				}
      }
      if(jet1_idx>=0) lep1lep2bb_TLV += ak4pfjets_p4().at(jet1_idx);
      
      int jet2_idx = -1;
      max_deepcsv = -99.9;
      for(int iJet=0; iJet<(int)ak4pfjets_p4().size(); iJet++) {
				if( iJet==jet1_idx ) continue;
				if( ak4pfjets_deepCSV().at(iJet) > max_deepcsv ) {
					jet2_idx = iJet;
					max_deepcsv = ak4pfjets_deepCSV().at(iJet);
				}
      }
      if(jet2_idx>=0) lep1lep2bb_TLV += ak4pfjets_p4().at(jet2_idx);
      
      // Calculate p4 of (lep1 lep2 b b MET) system
      lep1lep2bbMet_TLV = lep1lep2bb_TLV;
      LorentzVector met_TLV( pfmet()*cos(pfmet_phi()), pfmet()*sin(pfmet_phi()), 0.0, pfmet() );
      lep1lep2bbMet_TLV += met_TLV;
    
      lep1lep2bbMet_pt = lep1lep2bbMet_TLV.Pt();

      // Calculate mlb using lep2 instead of lep1
      LorentzVector lep2b_TLV(0.0,0.0,0.0,0.0);
      double minDr = 99.9;
      int minBJetIdx = -99;
      if(nvetoleps()>1) {
				lep2b_TLV += lep2_p4();
				for(int iJet=0; iJet<(int)ak4pfjets_p4().size(); iJet++) {
					if(!ak4pfjets_passMEDbtag().at(iJet)) continue;
					if(ROOT::Math::VectorUtil::DeltaR(ak4pfjets_p4().at(iJet),lep2_p4())<minDr) {
						minDr = ROOT::Math::VectorUtil::DeltaR(ak4pfjets_p4().at(iJet),lep2_p4());
						minBJetIdx = iJet;
					}
				} // end loop over jets
				if(minBJetIdx>=0) lep2b_TLV += ak4pfjets_p4().at(minBJetIdx);
      } // end if nvetoleps>1

      int mStop = mass_stop();
      int mLSP  = mass_lsp();



			/////////////////////////////////////////////////////////////
			//                                                         //
			// Loop over all analyzers, genClassy's, systematics, etc. //
			//                                                         //
			/////////////////////////////////////////////////////////////

			// Loop over all analyzers
			for( int iAna=0; iAna<nAnalyzers; iAna++ ) {
				analyzer* thisAnalyzer = analyzers.at(iAna);


				// Make an array of which genClassy's this event passes
				bool passedGenClassies[genClassyInfo::k_nGenClassy];
				for( genClassyInfo::Util thisGenClassy : thisAnalyzer->GetGenClassifications() ) {
					passedGenClassies[thisGenClassy.id] = thisGenClassy.eval_GenClassy();

					// Manually correct the ZZto2L2Nu sample
					if( sample.id==sampleInfo::k_ZZTo2L2Nu_powheg_pythia8 ) {
						if( thisGenClassy.id == genClassyInfo::k_ge2lep ||
								thisGenClassy.id == genClassyInfo::k_incl ) passedGenClassies[thisGenClassy.id] = true;
						else passedGenClassies[thisGenClassy.id] = false;
					}
				}

				// Check if this event passes selections with JES set to nominal
				//  (saves us having to evaluate this for every systematic)
				thisAnalyzer->SetJesType( 0 );
				bool pass_JESnominal = thisAnalyzer->PassSelections();

				// Fill cutflow histogram
				std::vector<bool> cutflow_results = selectionInfo::get_selectionResults( thisAnalyzer->GetSelections() );
				for( uint i=0; i<cutflow_results.size(); i++ ) {
					if( !cutflow_results.at(i) ) break;
					h_cutflow[iAna]->Fill( i+1 );
				}


				// Loop over all systematics in the analyzer
				for( sysInfo::Util thisSystematic : thisAnalyzer->GetSystematics() ) {

					// Check if this event passes selections, and also set the appropriate JES type for future use
					if( thisSystematic.id == sysInfo::k_JESUp ) {
						thisAnalyzer->SetJesType( 1 );
						if( !thisAnalyzer->PassSelections() ) continue;
					}
					else if( thisSystematic.id == sysInfo::k_JESDown ) {
						thisAnalyzer->SetJesType( -1 );
						if( !thisAnalyzer->PassSelections() ) continue;
					}
					else {
						thisAnalyzer->SetJesType( 0 );
						if( !pass_JESnominal ) continue;
					}

					// If we've passed selections, then get the event weight and the categories passed
					double weight = thisAnalyzer->GetEventWeight( thisSystematic.id );
					std::vector<int> categories_passed = thisAnalyzer->GetCategoriesPassed();

					// Loop over all the gen classifications that we passed
					for( genClassyInfo::Util thisGenClassy : thisAnalyzer->GetGenClassifications() ) {
						int iGen = thisGenClassy.id;
						if( !passedGenClassies[iGen] ) continue;

						// Get the index for the histogram corresponding to this genClassy and systematic
						int histIndex = iGen*nSystematics + thisSystematic.id;

						// Fill yield histograms
						for( int category : categories_passed ) {
							if( sample.isSignalScan ) {
								TH3D* yieldHisto = (TH3D*)thisAnalyzer->GetYieldHistogram( histIndex );
								yieldHisto->Fill( mStop, mLSP, category, weight );
							}
							else thisAnalyzer->GetYieldHistogram( histIndex )->Fill( category, weight );
						}

						/////////////////////////////////////
						//                                 //
						// Fill other non-yield histograms //
						//                                 //
						/////////////////////////////////////

						if( thisSystematic.id == sysInfo::k_nominal ) {

							for(int iMassPt=0; iMassPt<nMassPts; iMassPt++) {

								if( sample.isSignalScan && mStop!=sample.massPtList[iMassPt].first && mLSP!=sample.massPtList[iMassPt].second ) continue;
								//if(!isnormal(wgt_nominal)) cout << "NaN/inf weight: nEntries=" << wgtInfo.nEvents << ", lepSF=" << wgtInfo.sf_lep << ", vetoLep="<< wgtInfo.sf_vetoLep << ", btagSF=" << wgtInfo.sf_bTag << endl;
								// Histo Index
								int iHisto = iAna*nGenClassy*nMassPts + iGen*nMassPts + iMassPt;

								// Vars
								double nGoodJets = ngoodjets();

								bool add2ndLepToMet = thisAnalyzer->GetAdd2ndLep();

								double mt =         add2ndLepToMet ? mt_met_lep_rl() : mt_met_lep();
								double modTopness = add2ndLepToMet ? topnessMod_rl() : topnessMod();
								double met =        add2ndLepToMet ? pfmet_rl() : pfmet();

								double mlb = Mlb_closestb();
								if( TString(thisAnalyzer->GetLabel()).Contains("CR0b") ) mlb = ( lep1_p4() + ak4pfjets_leadbtag_p4() ).M();

								// Met Sideband CR area, met>=150

								if( met>=150 && met<250 ) {
									// mlb, met sideband CR
									h_mlb_150to250met_incl[iHisto]->Fill( mlb, weight );
									if( nGoodJets<4 )  h_mlb_150to250met_lt4j[iHisto]->Fill( mlb, weight );
									if( nGoodJets>=4 ) h_mlb_150to250met_ge4j[iHisto]->Fill( mlb, weight );
	      
									// mlb_lep2, met sideband CR
									if(nvetoleps()>1 && minBJetIdx>=0) {
										h_mlb_lep2_150to250met_incl[iHisto]->Fill( lep2b_TLV.M(), weight );
										if( nGoodJets<4 )  h_mlb_lep2_150to250met_lt4j[iHisto]->Fill( lep2b_TLV.M(), weight );
										if( nGoodJets>=4 ) h_mlb_lep2_150to250met_ge4j[iHisto]->Fill( lep2b_TLV.M(), weight );
									}

								} // end if 150<met<250

								// Signal Region Area, met>=250
								if( met<250.0 ) continue;
	    
								// nJets
								h_nJets[iHisto]->Fill( nGoodJets, weight );

								// nBTags
								h_nBTags[iHisto]->Fill( ngoodbtags(), weight );
	    
								// lep1 pT
								h_lep1Pt_incl[iHisto]->Fill( lep1_p4().Pt(), weight );

								// lep2 pT
								if( nvetoleps()>1 ) h_lep2Pt_incl[iHisto]->Fill( lep2_p4().Pt(), weight );

								// jet pT
								for(int iJet=0; iJet<(int)ak4pfjets_p4().size(); iJet++) h_jetPt_incl[iHisto]->Fill( ak4pfjets_p4().at(iJet).Pt(), weight );

								// jet1 pT
								h_jet1Pt_incl[iHisto]->Fill( ak4pfjets_p4().at(0).Pt(), weight );

								// jet2 pT
								h_jet2Pt_incl[iHisto]->Fill( ak4pfjets_p4().at(1).Pt(), weight );

								// DeepCSV jet1 pT
								if(jet1_idx>=0) h_deepcsvJet1Pt_incl[iHisto]->Fill( ak4pfjets_p4().at(jet1_idx).Pt(), weight );

								// DeepCSV jet2 pT
								if(jet2_idx>=0) h_deepcsvJet2Pt_incl[iHisto]->Fill( ak4pfjets_p4().at(jet2_idx).Pt(), weight );

								// met
								h_met_incl[iHisto]->Fill( met, weight );
								if( nGoodJets<4  ) h_met_lt4j[iHisto]->Fill( met, weight );
								if( nGoodJets>=4 ) h_met_ge4j[iHisto]->Fill( met, weight );

								// lep1lep2bbMetPt
								h_lep1lep2bbMetPt_incl[iHisto]->Fill( lep1lep2bbMet_pt, weight );
								if( nGoodJets<4  ) h_lep1lep2bbMetPt_lt4j[iHisto]->Fill( lep1lep2bbMet_pt, weight );
								if( nGoodJets>=4 ) h_lep1lep2bbMetPt_ge4j[iHisto]->Fill( lep1lep2bbMet_pt, weight );

								// mt
								h_mt_incl[iHisto]->Fill( mt, weight );

								// modTopness
								h_modTopness_incl[iHisto]->Fill( modTopness, weight );
								if( nGoodJets<4  ) h_modTopness_lt4j[iHisto]->Fill( modTopness, weight );
								if( nGoodJets>=4 ) h_modTopness_ge4j[iHisto]->Fill( modTopness, weight );

								// mlb
								h_mlb_incl[iHisto]->Fill( mlb, weight );
								if( nGoodJets<4 )  h_mlb_lt4j[iHisto]->Fill( mlb, weight );
								if( nGoodJets>=4 ) h_mlb_ge4j[iHisto]->Fill( mlb, weight );

								// mlb, modTopness bins
								if(modTopness<0.0)   h_mlb_lt0modTopness[iHisto]->Fill( mlb, weight );
								if(modTopness>=0.0)  h_mlb_ge0modTopness[iHisto]->Fill( mlb, weight );
								if(modTopness>=10.0) h_mlb_ge10modTopness[iHisto]->Fill( mlb, weight );

								// mlb_lep2
								if(nvetoleps()>1 && minBJetIdx>=0) {
									h_mlb_lep2_incl[iHisto]->Fill( lep2b_TLV.M(), weight );
									if( nGoodJets<4 )  h_mlb_lep2_lt4j[iHisto]->Fill( lep2b_TLV.M(), weight );
									if( nGoodJets>=4 ) h_mlb_lep2_ge4j[iHisto]->Fill( lep2b_TLV.M(), weight );
								}

								// Gen TTBar System
								if( sampleIsTTbar ) {
									h_gen_ttbarPt_incl[iHisto]->Fill( ttbarPt, weight );
									if( nGoodJets<4 )  h_gen_ttbarPt_lt4j[iHisto]->Fill( ttbarPt, weight );
									if( nGoodJets>=4 ) h_gen_ttbarPt_ge4j[iHisto]->Fill( ttbarPt, weight );
								}

								// Gen 2nd Lep ID
								if( !sample.isData && is2lep() && gen2ndLep__idx>=0 ) {
									h_gen_lep2_id_incl[iHisto]->Fill( fill_bin_genLep2ID, weight );
									if( ngoodjets()<4 )  h_gen_lep2_id_lt4j[iHisto]->Fill( fill_bin_genLep2ID, weight );
									if( ngoodjets()>=4 ) h_gen_lep2_id_ge4j[iHisto]->Fill( fill_bin_genLep2ID, weight );
								}

							} // end loop over mass points (1 if not signal scan)

						} // End filling of non-yield histograms

					} // End loop over genClassy's

				} // End loop over systematics

			} // End loop over analyzers

		} // End loop over events in tree


    //
    // Clean Up
    //
    delete tree;
    file->Close();
    delete file;

  } // end loop over file list


  //
  // Output Sanitation
  //
  if ( nEventsChain != nEventsTotal ) {
	  cout << Form( "ERROR: number of events from files (%d) is not equal to total number of events (%d)", nEventsChain, nEventsTotal ) << endl;
  }


  //
  // Print Selection Cutflow
  //
  cout << "====================================================" << endl;
  cout << endl;
  for(int iAna=0; iAna<nAnalyzers; iAna++) {
	  cout << "    " << analyzers.at(iAna)->GetLabel() << " Cutflow: " << endl;
	  for(int iCut=1; iCut<=(int)h_cutflow[iAna]->GetNbinsX(); iCut++) {
		  cout << "      nEvents pass " << h_cutflow[iAna]->GetXaxis()->GetBinLabel(iCut) << " = " << h_cutflow[iAna]->GetBinContent(iCut) << endl;
	  }
	  cout << endl;
	  cout << endl;
  }
  cout << "====================================================" << endl;


  //
  // Clean stopCORE objects
  //
  wgtInfo.cleanUp(); 


  //
  // Close Output File
  //
  f_output->Write();
  f_output->Close();


  //
  // Clean input chain
  // 
  chain->~TChain();
  if( sample.isData ) duplicate_removal::clear_list();

  //
  // Benchmark Reporting
  //
  bmark->Stop("benchmark");
  cout << endl;
  cout << nEventsTotal << " Events Processed" << endl;
  cout << "------------------------------" << endl;
  cout << "CPU  Time:	" << Form( "%.01f", bmark->GetCpuTime("benchmark")  ) << endl;
  cout << "Real Time:	" << Form( "%.01f", bmark->GetRealTime("benchmark") ) << endl;
  cout << endl;
  delete bmark;

  cout << "====================================================" << endl;
    
  //fclose(f_evtList);

  //
  // Return!
  //
  return 0;

} // End of function "looper"
STKUNIT_UNIT_TEST(UnitTestLinsysFunctions, test3)
{
  static const size_t spatial_dimension = 3;

  MPI_Barrier( MPI_COMM_WORLD );
  MPI_Comm comm = MPI_COMM_WORLD;
  //First create and fill MetaData and BulkData objects:

  const unsigned bucket_size = 100; //for a real application mesh, bucket_size would be much bigger...

  stk_classic::mesh::fem::FEMMetaData fem_meta;
  fem_meta.FEM_initialize(spatial_dimension);
  stk_classic::mesh::MetaData & meta_data = stk_classic::mesh::fem::FEMMetaData::get_meta_data(fem_meta);
  stk_classic::mesh::BulkData bulk_data( meta_data, comm, bucket_size );

  fill_utest_mesh_meta_data( fem_meta );

  fill_utest_mesh_bulk_data( bulk_data );

  //set owner-processors to lowest-sharing (stk_classic::mesh defaults to
  //highest-sharing) If highest-sharing owns, then it isn't correct for the
  //way the fei library sets ownership of shared nodes for vectors etc.
  stk_classic::mesh::set_owners<stk_classic::mesh::LowestRankSharingProcOwns>( bulk_data );

  stk_classic::mesh::Selector selector = ( meta_data.locally_owned_part() | meta_data.globally_shared_part() ) & *meta_data.get_part("block_1");
  std::vector<unsigned> count;
  stk_classic::mesh::count_entities(selector, bulk_data, count);
  const stk_classic::mesh::EntityRank element_rank = fem_meta.element_rank();

  STKUNIT_ASSERT_EQUAL( count[element_rank], (unsigned)4 );
  STKUNIT_ASSERT_EQUAL( count[NODE_RANK],     (unsigned)20 );

  ScalarField* temperature_field = meta_data.get_field<ScalarField>("temperature");

  //Create a fei Factory and stk_classic::linsys::LinearSystem object:

  fei::SharedPtr<fei::Factory> factory(new Factory_Trilinos(comm));

  stk_classic::linsys::LinearSystem ls(comm, factory);

  stk_classic::linsys::add_connectivities(ls, element_rank, NODE_RANK,
                                  *temperature_field, selector, bulk_data);

  fei::SharedPtr<fei::MatrixGraph> matgraph = ls.get_fei_MatrixGraph();
  int num_blocks = matgraph->getNumConnectivityBlocks();

  STKUNIT_ASSERT_EQUAL( num_blocks, (int)1 );

  ls.synchronize_mappings_and_structure();
  ls.create_fei_LinearSystem();

  //put 3 throughout the matrix and 3 throughout the rhs:
  fei::SharedPtr<fei::Matrix> mat = ls.get_fei_LinearSystem()->getMatrix();
  mat->putScalar(3.0);
  ls.get_fei_LinearSystem()->getRHS()->putScalar(3.0);

  fei::SharedPtr<fei::Vector> rhsvec = ls.get_fei_LinearSystem()->getRHS();

  stk_classic::linsys::scale_vector(2, *rhsvec);
  stk_classic::linsys::scale_matrix(2, *mat);

  //now the rhs and matrix contain 6.

  //create another matrix and vector:
  fei::SharedPtr<fei::Matrix> mat2 = factory->createMatrix(matgraph);
  fei::SharedPtr<fei::Vector> vec2 = factory->createVector(matgraph);
  mat2->putScalar(3.0);
  vec2->putScalar(3.0);

  //add 3*mat to mat2
  stk_classic::linsys::add_matrix_to_matrix(3.0, *mat, *mat2);

  //confirm that mat2 contains 21:
  bool result = confirm_matrix_values(*mat2, 21);
  STKUNIT_ASSERT(result);

  //add 3*rhsvec to vec2:
  stk_classic::linsys::add_vector_to_vector(3.0, *rhsvec, *vec2);

  //confirm that vec2 contains 21:
  result = confirm_vector_values(*vec2, 21);
  STKUNIT_ASSERT(result);
}
Exemple #13
0
bool load(std::istream & in, std::vector<Vertex> & vertices, std::vector<Face> & faces)
{
    std::string line;
    //read header
	while(getline(in, line))
	{
		std::string a, b;
		unsigned count;
		std::istringstream ls(line);
		ls >> a >> b >> count;
		if(a == "element")
		{
			if(b == "vertex")
			{
				vertices.resize(count);
			}
			else if(b == "face")
			{
				faces.resize(count);
			}
		}
		else if(a == "end_header")
			break;
	}
	if((vertices.size() == 0) || (faces.size() == 0))
    {
        std::cerr << "Can't parse header\n";
		return false;
    }
	//read vertices
	for(unsigned i = 0; i < vertices.size(); ++i)
	{
		if(!getline(in, line))
        {
            std::cerr << "Can't read vertex\n";
			return false;
        }
		std::istringstream ls(line);
        float x, y, z, nx, ny, nz;
		if(!(ls >> x >> y >> z >> nx >> ny >> nz))
        {
            std::cerr << "Can't parse vertex\n";
			return false;
        }
        //store vertex
        vertices[i].position = glm::vec3(x, y, z);
        vertices[i].normal = glm::vec3(nx, ny, nz);
        vertices[i].face_count = 0;
	}
	//read faces
	for(unsigned i = 0; i < faces.size(); ++i)
	{
		if(!getline(in, line))
        {
            std::cerr << "Can't read face\n";
			return false;
        }
		std::istringstream ls(line);
		unsigned cnt, a, b, c;
		if(!(ls >> cnt >> a >> b >> c))
        {
            std::cerr << "Can't parse face\n";
			return false;
        }
        if(cnt != 3)
        {
            std::cerr << "Faces must be triangles\n";
			return false;
        }
        //store face
        faces[i].vertices[0] = a;
        faces[i].vertices[1] = b;
        faces[i].vertices[2] = c;
        //mark vertices
        ++vertices[a].face_count;
        ++vertices[b].face_count;
        ++vertices[c].face_count;
        //edge vectors
/*        glm::vec3 ab = vertices[b].position-vertices[a].position;
        glm::vec3 ac = vertices[c].position-vertices[a].position;
        //face normal, scaled by area(*2)
        glm::vec3 n = glm::cross(ab, ac);*/
        //add face normal to vertex normal
        for(unsigned j = 0; j < 3; ++j)
        {
//            vertices[faces[i].vertices[j]].normal += n;
            //check for out-of-bounds indices
            if(faces[i].vertices[j] >= vertices.size())
            {
                std::cerr << "Face out of bounds\n";
                return false;
            }
        }
	}
    unsigned unused_vertices = 0;
    //normalize vertex normals
    for(unsigned i = 0; i < vertices.size(); ++i)
    {
/*        vertices[i].normal = glm::normalize(vertices[i].normal);
        for(unsigned j = 0; j < 3; ++j)
            if(isnan(vertices[i].normal[j]))
                vertices[i].normal[j] = 0.0f;*/
        if(vertices[i].face_count == 0)
            ++unused_vertices;
    }
    //std::cerr << "Unused vertices : " << unused_vertices << std::endl;
    //if(unused_vertices > 0) TODO : remove unused vertices
    return true;
}
/**
 * @brief 运行命令
 * @param[in] argc 命令行参数的个数
 * @param[in] argv 命令行参数的数组
 * @return 成功返回true,失败返回false
 */
bool run_command(int argc, char * const * argv)
{
	int i;
	char directory[MAX_COMMAND_LENGTH];
	assert(argv != NULL);

	if ( argc == 0 || argv[0][0] == '#' )
		return true;

	if ( !strcmp(argv[0], "exit") )
	{
		if ( argc == 2 )
			exit(atoi(argv[1]));
		else
			exit(EXIT_SUCCESS);
	}

	if ( !strcmp(argv[0], "ls") || !strcmp(argv[0], "dir") )
	{
		int c;
		int option_index = 0;
		char filename[MAX_PATH];
		memset(filename, 0, sizeof(filename));
		bool all = false, almost_all = false, long_list = false;
		const struct option long_options[] = {
			{ "all",	0, NULL, 'a' },
			{ "almost-all",	0, NULL, 'A' },
			{ NULL,		0, NULL, 0 }
		};

		optarg = NULL;
		optind = 0;

		while ( true )
		{
			c = getopt_long(argc, argv, "aAl", long_options, &option_index);
      			if (c == -1)
				break;

			switch(c)
			{
				case 'a':
					all = true;
					break;
				case 'A':
					almost_all = true;
					break;
				case 'l':
					long_list = true;
					break;
				default:
					return true;
					break;
			}
		}
		if ( optind == argc )
			return ls(all, almost_all, long_list, NULL);
		else
			return ls(all, almost_all, long_list, (const char * const* const)&argv[optind]);
	}

	else if ( !strcmp(argv[0], "cat" ) )
	{
		for ( i = 1; i < argc; ++ i )
			cat( argv[i] );
		puts("");
		return true;
	}

	if ( !strcmp(argv[0], "cd" ) )
	{
		memset(directory, 0, sizeof(directory));
		if ( argc == 1 )
			strcpy(directory, "~");
		else
			strncpy(directory, argv[1], MAX_COMMAND_LENGTH - 1);
		if ( !strcmp( directory, "~" ) || !strcmp(directory, "#") )
		{
			const char * temp = getenv("HOME");
			if ( temp == NULL )
			{
				strcpy(lastError, "No HOME environment varible set");
				return false;
			}
			else
				strncpy(directory, temp, MAX_COMMAND_LENGTH - 1);
		}
		return cd(directory);
	}

	else if ( !strcmp(argv[0], "rm") )
	{
		int c;
		bool recursive = false, force = false;
		int option_index = 0;
		const struct option long_options[] = {
			{ "recursive",	0, NULL, 'r' },
			{ "force",	0, NULL, 'f' },
			{ NULL,		0, NULL, 0 }
		};

		optarg = NULL;
		optind = 0;

		while ( true )
		{
			c = getopt_long(argc, argv, "rRf", long_options, &option_index);
      			if (c == -1)
				break;

			switch(c)
			{
				case 'r':
				case 'R':
					recursive = true;
					break;
				case 'f':
					force = true;
					break;
				case '?':
					return true;
					break;
				default:
					break;
			}
		}
		return rm( (const char * const* const)&(argv[optind]), recursive, force );
	}

	else
	{
		fprintf(stderr, "%s: command not found\n", argv[0]);
		return true;
	}

	return true;
}
Exemple #15
0
void main(int argc, char *argv[])
{
	int i = 0, cmd = -1, fd = 0; 
	char line[128], cname[64], temp_pathname[124], pathname[124] = "NULL", basename[124] = "NULL",
	     dirname[124] = "NULL", parameter[124] = "NULL", *device;

	//GETS DISK NAME TO MOUNT
	/*
	printf("Enter the name of your disk image\n");
	fgets(device, 128, stdin);
	device[strlen(device)-1] = 0;  // kill the \n char at end	
	*/
	device = "mydisk";
	
	mount_root(device, &fd);

	while(1)
	{
		//printf("P%d running: ", running.uid);
		printf("nick's@linux:");
		pwd(P0.cwd);
		printf("$ ");
		fgets(line, 128, stdin);
		line[strlen(line)-1] = 0;  // kill the \n char at end
		if (line[0]==0) continue;

		sscanf(line, "%s %s %s", cname, pathname, parameter);

		if(strcmp(pathname,"NULL") != 0)		
			strcpy(PATHNAME, pathname);
		
		if(strcmp(parameter,"NULL") != 0)		
			strcpy(PARAMETER, parameter);

		cmd = findCmd(cname); // map cname to an index
		switch(cmd)
		{
			case 0 : menu();		break;
			case 1 : pwd(P0.cwd);printf("\n");			break;
			case 2 : ls();			break;
			case 3 : cd();			break;
			case 4 : make_dir();		break;
			case 5 : rmdir();               break;
			case 6 : creat_file();          break;
			case 7 : link();                break;
			case 8 : unlink();              break;
			case 9 : symlink();             break;
			case 10: rm_file();             break;
			case 11: chmod_file();          break;
			case 12: chown_file();          break;
			case 13: stat_file();           break;
			case 14: touch_file();          break;
			case 20: open_file();           break;		//LEVEL 2
			case 21: close_file((int)PATHNAME);          break;
			case 22: pfd();                 break;
			case 23: lseek_file();          break;
			case 24: //access_file();         break;
				break;
			case 25: //read_file();           
				break;
			case 26: write_file();          break;
			case 27: cat_file();            break;
			case 28: cp_file();             break;
			case 29: mv_file();             break;
			case 30: mount();               break;		//LEVLEL 3
			case 31: //umount();              break;
			case 32: //cs();                  break;
			case 33: //do_fork();             break;
			case 34: //do_ps();               break;
			case 40: //sync();                break; 
			case 41: quit();              	 break;
			case 42 : system("clear");	break; 
			default: printf("invalid command\n");
			break;
			
		}

		//RESET NAMES
		strcpy(parameter, "NULL");
		strcpy(pathname, "NULL");
		strcpy(PATHNAME, "NULL");
	}
	
  }
Vector UnconstrainedLocalSearch::conj_grad(const Vector& gk, const Matrix& Bk, const Vector& xk, const Vector& x_gcp, const IntervalVector& region, const BoolMask& I) {
	int hn = I.nb_unset(); // the restricted dimension

	//  cout << " [conj_grad] init x_gcp= " << x_gcp << endl;
	if (hn==0) return x_gcp;  // we are in a corner: nothing to do

	// ====================== STEP 3.0 : Initialization ======================
	Vector x=x_gcp; // next point, initialized to gcp

	// gradient of the quadratic model on zk1
	Vector r = -gk-Bk*(x-xk);

	double eta = get_eta(gk,xk,region,I);

	// Initialization of the conjuguate gradient restricted to the direction not(I[i])
	Vector hp(hn); // the restricted conjugate direction
	Vector hx(hn); // the restricted iterate
	Vector hr(hn); // the restricted gradient
	Vector hy(hn); // temporary vector
	Matrix hB(hn,hn); // the restricted hessian matrix
	IntervalVector hregion(hn); // the restricted region

	// initialization of \hat{B}:
	int p=0, q=0;
	for (int i=0; i<n; i++) {
		if (!I[i]) {
			for (int j=0; j<n; j++) {
				if (!I[j]) {
					hB[p][q] = Bk[i][j];
					q++;
				}
			}
			p++;
			q=0;
		}
	}

	// initialization of \hat{r} and \hat{region}
	p=0;
	for (int i=0; i<n; i++) {
		if (!I[i]) {
			hregion[p] = region[i];
			hr[p] = r[i];
			hx[p] = x[i];
			p++;
		}
	}

	double rho1 = 1.0; 					// norm of the restricted gradient at the previous iterate
	double rho2 = ::pow(hr.norm(),2); 	// norm of the restricted gradient

	// ====================== STEP 3.1 : Test for the required accuracy in c.g. iteration ======================
	bool cond = (rho2>::pow(eta,2));

	try {
		while (cond) {

			// ====================== STEP 3.2 : Conjugate gradient recurrences ======================

			// Update the restricted conjugate direction
			// \hat{p} = \hat{r} +beta* \hat{p}
			hp = hr + (rho2/rho1)*hp;

			// Update the temporary vector
			// \hat{y} = \hat{Bk}*\hat{p}
			hy = hB*hp;

			//  cout << " [conj_grad] current hr=" << hr << endl;
			//  cout << " [conj_grad] current hp=" << hp << endl;
			LineSearch ls(hregion,hx,hp,data,sigma);

			double alpha1=ls.alpha_max();
			//  cout << " [conj_grad] alpha1=" << alpha1 << endl;

			// first termination condition
			// we check if the hessian is "positive definite for \hat{p}"
			// otherwise the quadratic approximation is concave
			// and the solution if on the border of the region
			double aux = hp*hy;
			if ( aux <= 0) {
				cond = false;
				hx = ls.endpoint();
			}
			else {
				// second termination condition alpha2>alpha1
				double alpha2 = rho2/aux;

				if (alpha2>alpha1) {
					cond = false;
					hx = ls.endpoint();
				}
				else {
					// otherwise update x, r=\hat{r}, hy=y, rho1 and rho2= \hat{r}*\hat{r}=r*r
					hx += alpha2*hp;
					ls.proj(hx);
					hr -= alpha2*hy;
					rho1 = rho2;
					rho2 = hr*hr;
					cond = (rho2>(::pow(eta,2)));
				}
			}
		}
	} catch(LineSearch::NullDirectionException&) {

	}

	// update of x
	p=0;
	for (int i=0; i<n; i++) {
		if (!I[i]) {
			x[i] = hx[p];
			p++;
		}
	}
	//  cout << " [conj_grad] new x= " << x << endl;
	return x;
}
Exemple #17
0
void RunProgram(void)
{
	int running = 1;
	//USER_INPUT[0] = USER_INPUT_0;
	//USER_INPUT[1] = USER_INPUT_1;
	//USER_INPUT[2] = USER_INPUT_2;
	//USER_INPUT[3] = USER_INPUT_3;
	//USER_INPUT[4] = NULL;

	while (running)
	{
		PrintPrompt();
		GetUserInput();
		if (strcmp(USER_INPUT[0], "exit") == 0)
		{
			running = 0;
		}
		else if (strcmp(USER_INPUT[0], "ls") == 0)
		{
			if (strcmp(USER_INPUT[1], ". . . . .") == 0)
			{
				//printf("Requires an argument for path name\n");
				list(GetCurrentDirectoryClusterNum());
			}
			else
			{
				ls(USER_INPUT[1]);
			}
		}
		else if (strcmp(USER_INPUT[0], "cd") == 0)
		{
			if (strcmp(USER_INPUT[1], ". . . . .") == 0)
			{
				printf("Requires an argument for path name\n");
			}
			else if (strcmp(USER_INPUT[1], ".") == 0)
			{
				// do nothing
			}
			else
			{
				//char parsed_dir[USER_INPUT_BUFFER_LENGTH];
				//strcpy(parsed_dir, USER_INPUT[1]);
				//ToFAT32(parsed_dir);
				//printf("!%s!\n", parsed_dir);
				cd(USER_INPUT[1]);
			}
		}
		else if (strcmp(USER_INPUT[0], "size") == 0)
		{
			if (strcmp(USER_INPUT[1], ". . . . .") == 0)
			{
				printf("Requires a file name argument\n");
			}
			else
			{
				size(USER_INPUT[1]);
			}
		}
		else if (strcmp(USER_INPUT[0], "open") == 0)
		{
			if (strcmp(USER_INPUT[1], ". . . . .") == 0 ||
			    strcmp(USER_INPUT[2], ". . . . .") == 0)
			{
				printf("Requires a file name argument followed by a mode argument\n");
			}
			else
			{
				char parsed_dir[USER_INPUT_BUFFER_LENGTH];
				strcpy(parsed_dir, USER_INPUT[1]);
				ToFAT32(parsed_dir);
				open(parsed_dir, USER_INPUT[2]);
			}
		}
		else if (strcmp(USER_INPUT[0], "close") == 0)
		{
			if (strcmp(USER_INPUT[1], ". . . . .") == 0)
			{
				printf("Requires a file name argument\n");
			}
			else
			{
				char parsed_dir[USER_INPUT_BUFFER_LENGTH];
				strcpy(parsed_dir, USER_INPUT[1]);
				ToFAT32(parsed_dir);
				close(parsed_dir);
			}
		}
		else if (strcmp(USER_INPUT[0], "read") == 0)
		{
			if (strcmp(USER_INPUT[1],". . . . .") == 0 ||
			    strcmp(USER_INPUT[2],". . . . .") == 0 ||
			    strcmp(USER_INPUT[3],". . . . .") == 0)
			{
				printf("Requires arguments for filename, position, and size\n");
			}
			else
			{
				char parsed_dir[USER_INPUT_BUFFER_LENGTH];
				strcpy(parsed_dir, USER_INPUT[1]);
				ToFAT32(parsed_dir);
				read(parsed_dir, atoi(USER_INPUT[2]), atoi(USER_INPUT[3]));
			}
		}
		else if (strcmp(USER_INPUT[0], "create") == 0)
		{
			if (strcmp(USER_INPUT[1],". . . . .") == 0)
			{
				printf("Requires an argument for the file name\n");
			}
			else if (strcmp(USER_INPUT[1],".") == 0)
			{
				printf("Invalid file name\n");
			}
			else if (strcmp(USER_INPUT[1],"..") == 0)
			{
				printf("Invalid file name\n");
			}
			else
			{
				char parsed_dir[USER_INPUT_BUFFER_LENGTH];
				strcpy(parsed_dir, USER_INPUT[1]);
				ToFAT32(parsed_dir);
				create(parsed_dir);
			}
		}
		else if (strcmp(USER_INPUT[0], "mkdir") == 0)
		{
			if (strcmp(USER_INPUT[1],". . . . .") == 0)
			{
				printf("Requires an argument for the directory name\n");
			}
			else if (strcmp(USER_INPUT[1],".") == 0)
			{
				printf("Invalid directory name\n");
			}
			else if (strcmp(USER_INPUT[1],"..") == 0)
			{
				printf("Invalid directory name\n");
			}	
			else
			{
				char parsed_dir[USER_INPUT_BUFFER_LENGTH];
				strcpy(parsed_dir, USER_INPUT[1]);
				ToFAT32(parsed_dir);
				mkdir(parsed_dir);
			}
		}
		else if (strcmp(USER_INPUT[0], "rm") == 0)
		{
			if (strcmp(USER_INPUT[1],". . . . .") == 0)
			{
				printf("Requires an argument for the file name\n");
			}
			else if (strcmp(USER_INPUT[1],".") == 0)
			{
				printf("Invalid file name\n");
			}
			else if (strcmp(USER_INPUT[1],"..") == 0)
			{
				printf("Invalid file name\n");
			}	
			else
			{
				char parsed_dir[USER_INPUT_BUFFER_LENGTH];
				strcpy(parsed_dir, USER_INPUT[1]);
				ToFAT32(parsed_dir);
				rm(parsed_dir);
			}
		}
		else if (strcmp(USER_INPUT[0], "rmdir") == 0)
		{
			if (strcmp(USER_INPUT[1],". . . . .") == 0)
			{
				printf("Requires an argument for the directory name\n");
			}
			else if (strcmp(USER_INPUT[1],".") == 0)
			{
				printf("Invalid directory name\n");
			}
			else if (strcmp(USER_INPUT[1],"..") == 0)
			{
				printf("Invalid directory name\n");
			}
			else
			{
				char parsed_dir[USER_INPUT_BUFFER_LENGTH];
				strcpy(parsed_dir, USER_INPUT[1]);
				ToFAT32(parsed_dir);
				rmdir(parsed_dir);
			}
		}
		else if (strcmp(USER_INPUT[0], "write") == 0)
		{
			if (strcmp(USER_INPUT[1],". . . . .") == 0 ||
			    strcmp(USER_INPUT[2],". . . . .") == 0 ||
			    strcmp(USER_INPUT[3],". . . . .") == 0 ||
			    strcmp(USER_INPUT[4],". . . . .") == 0)
			{
				printf("Requires arguments for file name, position, number of bytes, and string to write\n"); 
			}
			else
			{
				char parsed_dir[USER_INPUT_BUFFER_LENGTH];
				strcpy(parsed_dir, USER_INPUT[1]);
				ToFAT32(parsed_dir);
				write(parsed_dir, atoi(USER_INPUT[2]), atoi(USER_INPUT[3]), USER_INPUT[4]);
			}
		}
		else if (strcmp(USER_INPUT[0], "debug") == 0)
		{
			printf("CURRENT_CLUSTER: %d\n", GetCurrentDirectoryClusterNum());
			printf("CURRENT_CLUSTER BYTE_ADDRESS: 0x%x\n", FindFirstSectorOfCluster(GetCurrentDirectoryClusterNum()));
			FTPrint();
			PrintDirectoryVector(GetDirectoryContents(GetCurrentDirectoryClusterNum()));
		}
	}
	int k;
	for (k = 0; k < 5; k++)
	{
		free(USER_INPUT[k]);
	}
}
Exemple #18
0
int
main(int argc,char *argv[])
{
	int	err, opt, removefiles, list;
	char *file1, *file2;

	verbose = 0;
	list = 0;
	removefiles = 1;
	getoptinit();
	while((opt=getopt(argc,argv,"lrv")) != -1) {
		switch(opt) {
		case 'l':
			list = 1;
			break;
		case 'r':
			removefiles = 0;
			break;
		case 'v':
			verbose++;
			break;
		default:
			usage(0);
		}
	}

	if (argc != optind+2)
		usage("Bad arg count");

	/* Test all aspects of TFS API calls: */
	file1 = argv[optind];
	file2 = argv[optind+1];
	if ((!strcmp(file1,TMPFILE)) || (!strcmp(file2,TMPFILE)))
		usage(TMPFILE);


	if (verbose)
		mon_printf("tfstest %s %s...\n",file1,file2);
	

	/* 
	 *	Start by removing files to be created later...
	 */
	if (mon_tfsstat(TMPFILE)) {
		if (verbose)
			mon_printf("Removing %s...\n",TMPFILE);
		err = mon_tfsunlink(TMPFILE);
		if (err != TFS_OKAY)
			tfsdie(err);
	}
	if (mon_tfsstat(file1)) {
		if (verbose)
			mon_printf("Removing %s...\n",file1);
		err = mon_tfsunlink(file1);
		if (err != TFS_OKAY)
			tfsdie(err);
	}
	if (mon_tfsstat(file2)) {
		if (verbose)
			mon_printf("Removing %s...\n",file2);
		err = mon_tfsunlink(file2);
		if (err != TFS_OKAY)
			tfsdie(err);
	}

	/*
	 *	Create a file...
	 */
	if (verbose)
		mon_printf("Creating %s...\n",file1);
	err = mon_tfsadd(file1,"data1","2",data1,strlen(data1));
	if (err != TFS_OKAY)
		tfsdie(err);

	/*
	 *	Basic getline test...
	 */
	if (verbose)
		mon_printf("Checking 'getline'...\n");
	getlinetest(file1,data1);

	/*
	 *	Now copy the file...
	 */
	if (verbose)
		mon_printf("Copying %s to %s...\n",file1,file2);
	cp(file2,file1);

	/*
	 *	Now compare the two...
	 *	(they should be identical)
	 */
	if (verbose)
		mon_printf("Comparing %s to %s...\n",file1,file2);
	if (cmp(file1,file2) != 0)
		die();

	/*
	 *	Seek test...
	 *  Verify that data at a specified offset is as expected based on the
	 *	file (file1) initially created from the data1 array...
	 */
	if (verbose)
		mon_printf("Running seek test on %s...\n",file1);
	seektest(file1,38,data1[38]);

	/* 
	 *	Truncateion test...
	 *	Truncate a file and verify.
	 */
	if (verbose)
		mon_printf("Running truncation test on %s...\n",file1);
	trunctest(file1,data1);

	/*
	 *	Tfsctrl() function test...
	 */
	if (verbose)
		mon_printf("Running tfsctrl test...\n");
	ctrltest(file1,data1);

	/* 
	 *	Write test...
	 *	Modify a file in a few different ways and verify the modification...
	 *	Note that after this point, file1 and data1 are not the same.
	 *	The content of file1 will be the same as the new_data1 array.
	 */
	if (verbose)
		mon_printf("Running write test on %s...\n",file1);
	writetest(file1,new_data1);
	
	/*
	 *	File in-use test...
	 *	Verify that if a file is in-use, it cannot be removed.
	 */
	if (verbose)
		mon_printf("Running in-use test on %s...\n",file1);
	inusetest(file1);

	/*
	 *	Append test...
	 *	Verify that a file can be properly appended to.
	 */
	if (verbose)
		mon_printf("Running append test on %s...\n",file1);
	appendtest(file1,"this_is_some_data","this_is_the_appended_data");

	/*
	 * If the -r option is not set, then remove the files...
	 */
	if (removefiles) {
		if (mon_tfsstat(file1)) {
			err = mon_tfsunlink(file1);
			if (err != TFS_OKAY)
				tfsdie(err);
		}
		if (mon_tfsstat(file2)) {
			err = mon_tfsunlink(file2);
			if (err != TFS_OKAY)
				tfsdie(err);
		}
		if (mon_tfsstat(TMPFILE)) {
			err = mon_tfsunlink(TMPFILE);
			if (err != TFS_OKAY)
				tfsdie(err);
		}
	}

	if (list)
		ls();

	/* All error cases checked above would have resulted in an exit
	 * of this application, so if we got here, the testing must
	 * have succeeded...
	 */
	mon_printf("TFS test on %s & %s PASSED\n",file1,file2);
	mon_appexit(0);
	return(0);
}
Exemple #19
0
void ls(node *subdir){
	if(!subdir)
		return;
	printf("%s ",  subdir -> name);
	ls(subdir -> nextSibling);
}
Exemple #20
0
static void
lsdir(const char *path)
{
	DIR *dp;
	Rune r;
	struct entry ent, *ents = NULL;
	struct dirent *d;
	size_t i, n = 0, len;
	char cwd[PATH_MAX], *p, *q, *name;

	if (!getcwd(cwd, sizeof(cwd)))
		eprintf("getcwd:");
	if (!(dp = opendir(path)))
		eprintf("opendir %s:", path);
	if (chdir(path) < 0)
		eprintf("chdir %s:", path);

	if (many || Rflag) {
		if (!first)
			putchar('\n');
		printf("%s:\n", path);
	}
	first = 0;

	while ((d = readdir(dp))) {
		if (d->d_name[0] == '.' && !aflag && !Aflag)
			continue;
		else if (Aflag)
			if (strcmp(d->d_name, ".") == 0 || strcmp(d->d_name, "..") == 0)
				continue;
		if (Uflag){
			mkent(&ent, d->d_name, Fflag || lflag || pflag || iflag || Rflag, Lflag);
			ls(&ent, Rflag);
		} else {
			ents = ereallocarray(ents, ++n, sizeof(*ents));
			name = p = estrdup(d->d_name);
			if (qflag) {
				q = d->d_name;
				while (*q) {
					len = chartorune(&r, q);
					if (isprintrune(r)) {
						memcpy(p, q, len);
						p += len, q += len;
					} else {
						*p++ = '?';
						q += len;
					}
				}
				*p = '\0';
			}
			mkent(&ents[n - 1], name, tflag || Sflag || Fflag || iflag || lflag || pflag || Rflag, Lflag);
		}
	}
	closedir(dp);
	if (!Uflag){
		qsort(ents, n, sizeof(*ents), entcmp);
		for (i = 0; i < n; i++) {
			ls(&ents[rflag ? (n - i - 1) : i], Rflag);
			free(ents[rflag ? (n - i - 1) : i].name);
		}
	}
	if (chdir(cwd) < 0)
		eprintf("chdir %s:", cwd);
	free(ents);
}
void PhotonShootingTask::Run() {
    // Declare local variables for _PhotonShootingTask_
    MemoryArena arena;
    RNG rng(31 * taskNum);
    vector<Photon> localDirectPhotons, localIndirectPhotons, localCausticPhotons;
    vector<RadiancePhoton> localRadiancePhotons;
    uint32_t totalPaths = 0;
    bool causticDone = (integrator->nCausticPhotonsWanted == 0);
    bool indirectDone = (integrator->nIndirectPhotonsWanted == 0);
    PermutedHalton halton(6, rng);
    vector<Spectrum> localRpReflectances, localRpTransmittances;
    while (true) {
        // Follow photon paths for a block of samples
        const uint32_t blockSize = 4096;
        for (uint32_t i = 0; i < blockSize; ++i) {
            float u[6];
            halton.Sample(++totalPaths, u);
            // Choose light to shoot photon from
            float lightPdf;
            int lightNum = lightDistribution->SampleDiscrete(u[0], &lightPdf);
            const Light *light = scene->lights[lightNum];

            // Generate _photonRay_ from light source and initialize _alpha_
            RayDifferential photonRay;
            float pdf;
            LightSample ls(u[1], u[2], u[3]);
            Normal Nl;
            Spectrum Le = light->Sample_L(scene, ls, u[4], u[5],
                                          time, &photonRay, &Nl, &pdf);
            if (pdf == 0.f || Le.IsBlack()) continue;
            Spectrum alpha = (AbsDot(Nl, photonRay.d) * Le) / (pdf * lightPdf);
            if (!alpha.IsBlack()) {
                // Follow photon path through scene and record intersections
                PBRT_PHOTON_MAP_STARTED_RAY_PATH(&photonRay, &alpha);
                bool specularPath = true;
                Intersection photonIsect;
                int nIntersections = 0;
                while (scene->Intersect(photonRay, &photonIsect)) {
                    ++nIntersections;
                    // Handle photon/surface intersection
                    alpha *= renderer->Transmittance(scene, photonRay, NULL, rng, arena);
                    BSDF *photonBSDF = photonIsect.GetBSDF(photonRay, arena);
                    BxDFType specularType = BxDFType(BSDF_REFLECTION |
                                            BSDF_TRANSMISSION | BSDF_SPECULAR);
                    bool hasNonSpecular = (photonBSDF->NumComponents() >
                                           photonBSDF->NumComponents(specularType));
                    Vector wo = -photonRay.d;
                    if (hasNonSpecular) {
                        // Deposit photon at surface
                        Photon photon(photonIsect.dg.p, alpha, wo);
                        bool depositedPhoton = false;
                        if (specularPath && nIntersections > 1) {
                            if (!causticDone) {
                                PBRT_PHOTON_MAP_DEPOSITED_CAUSTIC_PHOTON(&photonIsect.dg, &alpha, &wo);
                                depositedPhoton = true;
                                localCausticPhotons.push_back(photon);
                            }
                        }
                        else {
                            // Deposit either direct or indirect photon
                            // stop depositing direct photons once indirectDone is true; don't
                            // want to waste memory storing too many if we're going a long time
                            // trying to get enough caustic photons desposited.
                            if (nIntersections == 1 && !indirectDone && integrator->finalGather) {
                                PBRT_PHOTON_MAP_DEPOSITED_DIRECT_PHOTON(&photonIsect.dg, &alpha, &wo);
                                depositedPhoton = true;
                                localDirectPhotons.push_back(photon);
                            }
                            else if (nIntersections > 1 && !indirectDone) {
                                PBRT_PHOTON_MAP_DEPOSITED_INDIRECT_PHOTON(&photonIsect.dg, &alpha, &wo);
                                depositedPhoton = true;
                                localIndirectPhotons.push_back(photon);
                            }
                        }

                        // Possibly create radiance photon at photon intersection point
                        if (depositedPhoton && integrator->finalGather &&
                                rng.RandomFloat() < .125f) {
                            Normal n = photonIsect.dg.nn;
                            n = Faceforward(n, -photonRay.d);
                            localRadiancePhotons.push_back(RadiancePhoton(photonIsect.dg.p, n));
                            Spectrum rho_r = photonBSDF->rho(rng, BSDF_ALL_REFLECTION);
                            localRpReflectances.push_back(rho_r);
                            Spectrum rho_t = photonBSDF->rho(rng, BSDF_ALL_TRANSMISSION);
                            localRpTransmittances.push_back(rho_t);
                        }
                    }
                    if (nIntersections >= integrator->maxPhotonDepth) break;

                    // Sample new photon ray direction
                    Vector wi;
                    float pdf;
                    BxDFType flags;
                    Spectrum fr = photonBSDF->Sample_f(wo, &wi, BSDFSample(rng),
                                                       &pdf, BSDF_ALL, &flags);
                    if (fr.IsBlack() || pdf == 0.f) break;
                    Spectrum anew = alpha * fr *
                        AbsDot(wi, photonBSDF->dgShading.nn) / pdf;

                    // Possibly terminate photon path with Russian roulette
                    float continueProb = min(1.f, anew.y() / alpha.y());
                    if (rng.RandomFloat() > continueProb)
                        break;
                    alpha = anew / continueProb;
                    specularPath &= ((flags & BSDF_SPECULAR) != 0);

                    if (indirectDone && !specularPath) break;
                    photonRay = RayDifferential(photonIsect.dg.p, wi, photonRay,
                                                photonIsect.rayEpsilon);
                }
                PBRT_PHOTON_MAP_FINISHED_RAY_PATH(&photonRay, &alpha);
            }
            arena.FreeAll();
        }

        // Merge local photon data with data in _PhotonIntegrator_
        { MutexLock lock(mutex);

        // Give up if we're not storing enough photons
        if (abortTasks)
            return;
        if (nshot > 500000 &&
            (unsuccessful(integrator->nCausticPhotonsWanted,
                                      causticPhotons.size(), blockSize) ||
             unsuccessful(integrator->nIndirectPhotonsWanted,
                                      indirectPhotons.size(), blockSize))) {
            Error("Unable to store enough photons.  Giving up.\n");
            causticPhotons.erase(causticPhotons.begin(), causticPhotons.end());
            indirectPhotons.erase(indirectPhotons.begin(), indirectPhotons.end());
            radiancePhotons.erase(radiancePhotons.begin(), radiancePhotons.end());
            abortTasks = true;
            return;
        }
        progress.Update(localIndirectPhotons.size() + localCausticPhotons.size());
        nshot += blockSize;

        // Merge indirect photons into shared array
        if (!indirectDone) {
            integrator->nIndirectPaths += blockSize;
            for (uint32_t i = 0; i < localIndirectPhotons.size(); ++i)
                indirectPhotons.push_back(localIndirectPhotons[i]);
            localIndirectPhotons.erase(localIndirectPhotons.begin(),
                                       localIndirectPhotons.end());
            if (indirectPhotons.size() >= integrator->nIndirectPhotonsWanted)
                indirectDone = true;
            nDirectPaths += blockSize;
            for (uint32_t i = 0; i < localDirectPhotons.size(); ++i)
                directPhotons.push_back(localDirectPhotons[i]);
            localDirectPhotons.erase(localDirectPhotons.begin(),
                                     localDirectPhotons.end());
        }

        // Merge direct, caustic, and radiance photons into shared array
        if (!causticDone) {
            integrator->nCausticPaths += blockSize;
            for (uint32_t i = 0; i < localCausticPhotons.size(); ++i)
                causticPhotons.push_back(localCausticPhotons[i]);
            localCausticPhotons.erase(localCausticPhotons.begin(), localCausticPhotons.end());
            if (causticPhotons.size() >= integrator->nCausticPhotonsWanted)
                causticDone = true;
        }

        for (uint32_t i = 0; i < localRadiancePhotons.size(); ++i)
            radiancePhotons.push_back(localRadiancePhotons[i]);
        localRadiancePhotons.erase(localRadiancePhotons.begin(), localRadiancePhotons.end());
        for (uint32_t i = 0; i < localRpReflectances.size(); ++i)
            rpReflectances.push_back(localRpReflectances[i]);
        localRpReflectances.erase(localRpReflectances.begin(), localRpReflectances.end());
        for (uint32_t i = 0; i < localRpTransmittances.size(); ++i)
            rpTransmittances.push_back(localRpTransmittances[i]);
        localRpTransmittances.erase(localRpTransmittances.begin(), localRpTransmittances.end());
        }

        // Exit task if enough photons have been found
        if (indirectDone && causticDone)
            break;
    }
}
Exemple #22
0
int
main(int argc, char *argv[])
{
	struct entry *ents;
	size_t i;

	ARGBEGIN {
	case '1':
		/* ignore */
		break;
	case 'A':
		Aflag = 1;
		break;
	case 'a':
		aflag = 1;
		break;
	case 'c':
		cflag = 1;
		uflag = 0;
		break;
	case 'd':
		dflag = 1;
		break;
	case 'f':
		aflag = 1;
		fflag = 1;
		Uflag = 1;
		break;
	case 'F':
		Fflag = 1;
		break;
	case 'H':
		Hflag = 1;
		break;
	case 'h':
		hflag = 1;
		break;
	case 'i':
		iflag = 1;
		break;
	case 'L':
		Lflag = 1;
		break;
	case 'l':
		lflag = 1;
		break;
	case 'n':
		lflag = 1;
		nflag = 1;
		break;
	case 'p':
		pflag = 1;
		break;
	case 'q':
		qflag = 1;
		break;
	case 'R':
		Rflag = 1;
		break;
	case 'r':
		if (!fflag)
			rflag = 1;
		break;
	case 'S':
		Sflag = 1;
		tflag = 0;
		break;
	case 't':
		Sflag = 0;
		tflag = 1;
		break;
	case 'U':
		Uflag = 1;
		break;
	case 'u':
		uflag = 1;
		cflag = 0;
		break;
	default:
		usage();
	} ARGEND;

	many = (argc > 1);
	if (argc == 0)
		*--argv = ".", argc++;

	ents = ereallocarray(NULL, argc, sizeof(*ents));

	for (i = 0; i < argc; i++)
		mkent(&ents[i], argv[i], 1, Hflag || Lflag);
	qsort(ents, argc, sizeof(*ents), entcmp);
	for (i = 0; i < argc; i++)
		ls(&ents[rflag ? argc-i-1 : i], 1);

	return fshut(stdout, "<stdout>");
}
char *cmd = "-1l";

reset_sandbox();
sandbox_cmd("touch file && xattr -w theAnswerIs42 whatever_you_want file");
UT_ASSERT(strcmp(ls(cmd), ft_ls(cmd)) == 0);

/*
printf("\n===================\n");
printf("%s", ls(cmd));
printf("\n===================\n");
printf("%s", ft_ls(cmd));
printf("\n===================\n");

*/
Exemple #24
0
int main(int argc, char* argv[])
{
  // load the mesh
  Mesh mesh;
  H2DReader mloader;
  mloader.load("motor.mesh", &mesh);

  // initialize the shapeset and the cache
  H1Shapeset shapeset;
  PrecalcShapeset pss(&shapeset);

  // create finite element space
  H1Space space(&mesh, &shapeset);
  space.set_bc_types(bc_types);
  space.set_bc_values(bc_values);
  space.set_uniform_order(P_INIT);

  // enumerate basis functions
  space.assign_dofs();

  // initialize the weak formulation
  WeakForm wf(1);
  wf.add_biform(0, 0, callback(biform1), SYM, 1);
  wf.add_biform(0, 0, callback(biform2), SYM, 2);

  // visualize solution, gradient, and mesh
  ScalarView sview("Coarse solution", 0, 0, 600, 1000);
  VectorView gview("Gradient", 610, 0, 600, 1000);
  OrderView  oview("Polynomial orders", 1220, 0, 600, 1000);
  //gview.set_min_max_range(0.0, 400.0);

  // matrix solver
  UmfpackSolver solver;

  // DOF and CPU convergence graphs
  SimpleGraph graph_dof, graph_cpu;

  // adaptivity loop
  int it = 1, ndofs;
  bool done = false;
  double cpu = 0.0;
  Solution sln_coarse, sln_fine;
  do
  {
    info("\n---- Adaptivity step %d ---------------------------------------------\n", it++);

    // time measurement
    begin_time();

    // solve the coarse mesh problem
    LinSystem ls(&wf, &solver);
    ls.set_spaces(1, &space);
    ls.set_pss(1, &pss);
    ls.assemble();
    ls.solve(1, &sln_coarse);

    // time measurement
    cpu += end_time();

    // view the solution -- this can be slow; for illustration only
    sview.show(&sln_coarse);
    gview.show(&sln_coarse, &sln_coarse, EPS_NORMAL, FN_DX_0, FN_DY_0);
    oview.show(&space);

    // time measurement
    begin_time();

    // solve the fine mesh problem
    RefSystem rs(&ls);
    rs.assemble();
    rs.solve(1, &sln_fine);

    // calculate element errors and total error estimate
    H1OrthoHP hp(1, &space);
    double err_est = hp.calc_error(&sln_coarse, &sln_fine) * 100;
    info("Error estimate: %g%%", err_est);

    // time measurement
    cpu += end_time();

    // add entry to DOF convergence graph
    graph_dof.add_values(space.get_num_dofs(), err_est);
    graph_dof.save("conv_dof.dat");

    // add entry to CPU convergence graph
    graph_cpu.add_values(cpu, err_est);
    graph_cpu.save("conv_cpu.dat");

    // if err_est too large, adapt the mesh
    if (err_est < ERR_STOP) done = true;
    else {
      hp.adapt(THRESHOLD, STRATEGY, ADAPT_TYPE, ISO_ONLY, MESH_REGULARITY);
      ndofs = space.assign_dofs();
      if (ndofs >= NDOF_STOP) done = true;
    }
  }
  while (done == false);
  verbose("Total running time: %g sec", cpu);

  // show the fine solution - this is the final result
  sview.set_title("Final solution");
  sview.show(&sln_fine);
  gview.show(&sln_fine, &sln_fine, EPS_HIGH, FN_DX_0, FN_DY_0);

  // wait for all views to be closed
  View::wait();
  return 0;
}
Exemple #25
0
Spectrum VolumePatIntegrator::Li_Single(const Scene *scene, const Renderer *renderer,
        const RayDifferential &ray, const Sample *sample, RNG &rng,
        Spectrum *T, MemoryArena &arena) const {
    VolumeRegion *vr = scene->volumeRegion;
    float t0, t1;
    if (!vr || !vr->IntersectP(ray, &t0, &t1) || (t1-t0) == 0.f) {
        *T = 1.f;
        return 0.f;
    }
    // Do single scattering volume integration in _vr_
    Spectrum Lv(0.);

    // Prepare for volume integration stepping
    int nSamples = Ceil2Int((t1-t0) / stepSize);
    float step = (t1 - t0) / nSamples;
    Spectrum Tr(1.f);
    Point p = ray(t0), pPrev;
    Vector w = -ray.d;
    t0 += sample->oneD[scatterSampleOffset][0] * step;

    // Compute sample patterns for single scattering samples
    float *lightNum = arena.Alloc<float>(nSamples);
    LDShuffleScrambled1D(1, nSamples, lightNum, rng);
    float *lightComp = arena.Alloc<float>(nSamples);
    LDShuffleScrambled1D(1, nSamples, lightComp, rng);
    float *lightPos = arena.Alloc<float>(2*nSamples);
    LDShuffleScrambled2D(1, nSamples, lightPos, rng);
    uint32_t sampOffset = 0;
    for (int i = 0; i < nSamples; ++i, t0 += step) {
        // Advance to sample at _t0_ and update _T_
        pPrev = p;
        p = ray(t0);
        Ray tauRay(pPrev, p - pPrev, 0.f, 1.f, ray.time, ray.depth);
        Spectrum stepTau = vr->tau(tauRay,
                                   .5f * stepSize, rng.RandomFloat());
        Tr *= Exp(-stepTau);

        // Possibly terminate ray marching if transmittance is small
        if (Tr.y() < 1e-3) {
            const float continueProb = .5f;
            if (rng.RandomFloat() > continueProb) {
                Tr = 0.f;
                break;
            }
            Tr /= continueProb;
        }

        // Compute single-scattering source term at _p_
        Lv += Tr * vr->Lve(p, w, ray.time);
        Spectrum ss = vr->Sigma_s(p, w, ray.time);
        if (!ss.IsBlack() && scene->lights.size() > 0) {
            int nLights = scene->lights.size();
            int ln = min(Floor2Int(lightNum[sampOffset] * nLights),
                         nLights-1);
            Light *light = scene->lights[ln];
            // Add contribution of _light_ due to scattering at _p_
            float pdf;
            VisibilityTester vis;
            Vector wo;
            LightSample ls(lightComp[sampOffset], lightPos[2*sampOffset],
                           lightPos[2*sampOffset+1]);
            Spectrum L = light->Sample_L(p, 0.f, ls, ray.time, &wo, &pdf, &vis);
            if (!L.IsBlack() && pdf > 0.f && vis.Unoccluded(scene)) {
                Spectrum Ld = L * vis.Transmittance(scene, renderer, NULL, rng, arena);
                Lv += Tr * ss * vr->p(p, w, -wo, ray.time) * Ld * float(nLights) /
                        pdf;
            }
        }
        ++sampOffset;
    }
    *T = Tr;
    return Lv * step;
}
Exemple #26
0
int main() {
  Filesystem filesystem;

  printf("Creating filesystem\n");
  mkfs(&filesystem);
  printf("pwd: ");
  pwd(&filesystem);


  printf("Creating directory animals ad gods\n");
  mkdir(&filesystem, "animals");
  mkdir(&filesystem, "god");
  printf("Printing current\n");
  ls(&filesystem,".");
  printf("Printing root\n");
  ls(&filesystem,"/");
  printf("changing directory to animals: ");
  
  

  printf("%d\n",cd(&filesystem,"animals"));
  pwd(&filesystem);
  mkdir(&filesystem, "rabbit");
  printf("printing cuurrent\n");
  ls(&filesystem,".");
  printf("printing root\n");
  ls(&filesystem,"/");
  printf("Changing directory to root: ");
  printf("%d\n",cd(&filesystem,"/"));
  cd(&filesystem, "god");
  mkdir(&filesystem, "lord");
  ls(&filesystem, ".");
  ls(&filesystem, "/");
  printf("---/nBACK TO ROOT/n");
  cd(&filesystem,"/");

  
  touch(&filesystem, "hippo");
  touch(&filesystem, "rabbit");
  printf("\n FIRST ls \n");
  ls(&filesystem,"");
  printf("\n END 1 ls \n\n");
  printf("Making directory wild in root\n");

  mkdir(&filesystem, "wild");
  cd(&filesystem, "wild");
  printf("PATH OF WILD NOW IS ");
  pwd(&filesystem);
  mkdir(&filesystem, "bear");
  mkdir(&filesystem, "lion");
  mkdir(&filesystem, "tiger");
  cd(&filesystem, "tiger");
  printf("PATH OF TIGER INSIDE WILD IS ");
  pwd(&filesystem);
  cd(&filesystem, "..");
  printf("\nSECOND ls \n");
  ls(&filesystem, ".");
  printf("\nEND SECOND ls \n");

  ls(&filesystem,"/");
  
  printf("going up to the root\n");
  cd(&filesystem,"..");
  ls(&filesystem,".");
  
  cd(&filesystem,"..");

  mkdir(&filesystem, "plants");
  cd(&filesystem,"plants");
  touch(&filesystem, "flowers");
  touch(&filesystem, "roses");
  printf("\nTHIRD ls \n");
  ls(&filesystem,".");
  printf("\nEND THIRD ls \n");

  cd(&filesystem,"/");
  printf("\nPRINTING ANIMALS \n");
  ls(&filesystem,"animals");
  printf("\nEND ANIMALS \n");
  printf("\nPRINTING PLANTS \n");
  ls(&filesystem,"plants");  
  printf("\nEND PLANTS \n");

  
  return 0;
}
void SearchManager::checkLinksSimultaneously(vector<LinkStatus*> const& links)
{
    Q_ASSERT(finished_connections_ <= max_simultaneous_connections_);
    finished_connections_ = 0;
    links_being_checked_ = 0;
    maximum_current_connections_ = -1;

    if(links.size() < (uint)max_simultaneous_connections_)
        maximum_current_connections_ = links.size();
    else
        maximum_current_connections_ = max_simultaneous_connections_;

    for(uint i = 0; i != links.size(); ++i)
    {
        LinkStatus* ls(links[i]);
        Q_ASSERT(ls);

        QString protocol = ls->absoluteUrl().protocol();

        ++links_being_checked_;
        Q_ASSERT(links_being_checked_ <= max_simultaneous_connections_);

        if(ls->malformed())
        {
            Q_ASSERT(ls->errorOccurred());
            Q_ASSERT(ls->status() == LinkStatus::MALFORMED);

            ls->setChecked(true);
            slotLinkChecked(ls, 0);
        }

        else if(ls->absoluteUrl().prettyURL().contains("javascript:", false))
        {
            ++ignored_links_;
            ls->setIgnored(true);
            ls->setErrorOccurred(true);
            ls->setError(i18n( "Javascript not supported" ));
            ls->setStatus(LinkStatus::NOT_SUPPORTED);
            ls->setChecked(true);
            slotLinkChecked(ls, 0);
        }
        /*
                else if(!(protocol == "http" || protocol == "https"))
                {
                    ++ignored_links_;
                    ls->setIgnored(true);
                    ls->setErrorOccurred(true);
                    ls->setError(i18n("Protocol %1 not supported").arg(protocol));
                    ls->setStatus(LinkStatus::MALFORMED);
                    ls->setChecked(true);
                    slotLinkChecked(ls, 0);
                }
        */
        else
        {
            LinkChecker* checker = new LinkChecker(ls, time_out_, this, "link_checker");
            checker->setSearchManager(this);

            connect(checker, SIGNAL(transactionFinished(const LinkStatus *, LinkChecker *)),
                    this, SLOT(slotLinkChecked(const LinkStatus *, LinkChecker *)));
            /*
                        connect(checker, SIGNAL(jobFinnished(LinkChecker *)),
                                this, SLOT(slotLinkCheckerFinnished(LinkChecker *)));
            */
            checker->check();
        }
    }
}
TEST(AssemblerLibSerialLinearSolver, Steady2DdiffusionQuadElem)
{
    // example
    using Example = SteadyDiffusion2DExample1<GlobalIndexType>;
    Example ex1;

    //--------------------------------------------------------------------------
    // Choose implementation type
    //--------------------------------------------------------------------------
    using GlobalSetup = GlobalSetupType;    // defined in numerics config

    //--------------------------------------------------------------------------
    // Prepare mesh items where data are assigned
    //--------------------------------------------------------------------------
    const MeshLib::MeshSubset mesh_items_all_nodes(*ex1.msh,
                                                          &ex1.msh->getNodes());

    //--------------------------------------------------------------------------
    // Allocate a coefficient matrix, RHS and solution vectors
    //--------------------------------------------------------------------------
    // define a mesh item composition in a vector
    std::vector<std::unique_ptr<MeshLib::MeshSubsets>> vec_comp_dis;
    vec_comp_dis.emplace_back(new MeshLib::MeshSubsets{&mesh_items_all_nodes});
    AssemblerLib::LocalToGlobalIndexMap local_to_global_index_map(
        std::move(vec_comp_dis), AssemblerLib::ComponentOrder::BY_COMPONENT);

    //--------------------------------------------------------------------------
    // Construct a linear system
    //--------------------------------------------------------------------------
    // allocate a vector and matrix
    typedef GlobalSetup::VectorType GlobalVector;
    typedef GlobalSetup::MatrixType GlobalMatrix;
    auto A = std::unique_ptr<GlobalMatrix>{
             GlobalSetup::createMatrix(local_to_global_index_map.dofSizeWithGhosts())};
    A->setZero();
    auto rhs = std::unique_ptr<GlobalVector>{
               GlobalSetup::createVector(local_to_global_index_map.dofSizeWithGhosts())};
    auto x   = std::unique_ptr<GlobalVector>{
               GlobalSetup::createVector(local_to_global_index_map.dofSizeWithGhosts())};
    // TODO no setZero() for rhs, x?

    using LocalAssembler = Example::LocalAssemblerData<GlobalMatrix, GlobalVector>;
    // Initializer of the local assembler data.
    std::vector<LocalAssembler*> local_assembler_data;
    local_assembler_data.resize(ex1.msh->getNElements());

    auto local_asm_builder =
        [&](std::size_t const id,
            MeshLib::Element const& item,
            LocalAssembler*& item_data)
    {
        assert(local_to_global_index_map.size() > id);

        auto const num_local_dof = local_to_global_index_map.getNumElementDOF(id);

        Example::initializeLocalData<GlobalMatrix, GlobalVector>(
                    item, item_data, num_local_dof, ex1);
    };

    // Call global initializer for each mesh element.
    GlobalSetup::transformDereferenced(
            local_asm_builder,
            ex1.msh->getElements(),
            local_assembler_data);

    // TODO in the future use simpler NumLib::ODESystemTag
    // Local and global assemblers.
    typedef AssemblerLib::VectorMatrixAssembler<
            GlobalMatrix, GlobalVector, LocalAssembler,
            NumLib::ODESystemTag::FirstOrderImplicitQuasilinear> GlobalAssembler;

    GlobalAssembler assembler(local_to_global_index_map);

    // Call global assembler for each mesh element.
    auto M_dummy = std::unique_ptr<GlobalMatrix>{
        GlobalSetup::createMatrix(local_to_global_index_map.dofSizeWithGhosts())};
    A->setZero();
    auto const t = 0.0;
    GlobalSetup::executeMemberDereferenced(
                assembler, &GlobalAssembler::assemble,
                local_assembler_data, t, *x, *M_dummy, *A, *rhs);

    //std::cout << "A=\n";
    //A->write(std::cout);
    //std::cout << "rhs=\n";
    //rhs->write(std::cout);

    // apply Dirichlet BC
    MathLib::applyKnownSolution(*A, *rhs, *x, ex1.vec_DirichletBC_id,
                                ex1.vec_DirichletBC_value);
    //std::cout << "A=\n";
    //A->write(std::cout);
    //std::cout << "rhs=\n";
    //rhs->write(std::cout);

    MathLib::finalizeMatrixAssembly(*A);
    //--------------------------------------------------------------------------
    // solve x=A^-1 rhs
    //--------------------------------------------------------------------------
    boost::property_tree::ptree t_root;
    {
        boost::property_tree::ptree t_solver;
        t_solver.put("solver_type", "CG");
        t_solver.put("precon_type", "NONE");
        t_solver.put("error_tolerance", 1e-16);
        t_solver.put("max_iteration_step", 1000);
        t_root.put_child("eigen", t_solver);
    }
    t_root.put("lis", "-i cg -p none -tol 1e-16 -maxiter 1000");
    BaseLib::ConfigTree conf(t_root, "",
                             BaseLib::ConfigTree::onerror,
                             BaseLib::ConfigTree::onwarning);

    GlobalSetup::LinearSolver ls("solver_name", &conf);
    ls.solve(*A, *rhs, *x);

    // copy solution to double vector
    std::vector<double> solution(x->size());
    for (std::size_t i = 0; i < x->size(); ++i)
        solution[i] = (*x)[i];

    ASSERT_ARRAY_NEAR(&ex1.exact_solutions[0], &solution[0], ex1.dim_eqs, 1.e-5);

    for (auto p : local_assembler_data)
        delete p;
}
Exemple #29
0
int main(int argc, char **argv) {
  const std::string storage_path = "exampledb";
  // comment that, for open exists storage.
  if (dariadb::utils::fs::path_exists(storage_path)) {
    dariadb::utils::fs::rm(storage_path);
  }

  // Replace standart logger.
  dariadb::utils::ILogger_ptr log_ptr{new QuietLogger()};
  dariadb::utils::LogManager::start(log_ptr);

  auto storage = dariadb::open_storage(storage_path);
  auto settings = storage->settings();

  auto scheme = dariadb::scheme::Scheme::create(settings);

  auto p1 = scheme->addParam("group.param1");
  auto p2 = scheme->addParam("group.subgroup.param2");
  scheme->save();

  auto m = dariadb::Meas();
  auto start_time = dariadb::timeutil::current_time();

  // write values in interval [currentTime:currentTime+10]
  m.time = start_time;
  for (size_t i = 0; i < 10; ++i) {
    if (i % 2) {
      m.id = p1;
    } else {
      m.id = p2;
    }

    m.time++;
    m.value++;
    m.flag = 100 + i % 2;
    auto status = storage->append(m);
    if (status.writed != 1) {
      std::cerr << "Error: " << dariadb::to_string(status.error) << std::endl;
    }
  }
  // we can get param id`s from scheme
  auto all_params = scheme->ls();
  dariadb::IdArray all_id;
  all_id.reserve(all_params.size());
  all_id.push_back(all_params.idByParam("group.param1"));
  all_id.push_back(all_params.idByParam("group.subgroup.param2"));

  // query writed interval;
  dariadb::QueryInterval qi(all_id, dariadb::Flag(), start_time, m.time);
  dariadb::MeasArray readed_values = storage->readInterval(qi);
  std::cout << "Readed: " << readed_values.size() << std::endl;
  for (auto measurement : readed_values) {
    std::cout << " param: " << all_params[measurement.id]
              << " timepoint: " << dariadb::timeutil::to_string(measurement.time)
              << " value:" << measurement.value << std::endl;
  }

  // query in timepoint;
  dariadb::QueryTimePoint qp(all_id, dariadb::Flag(), m.time);
  dariadb::Id2Meas timepoint = storage->readTimePoint(qp);
  std::cout << "Timepoint: " << std::endl;
  for (auto kv : timepoint) {
    auto measurement = kv.second;
    std::cout << " param: " << all_params[kv.first]
              << " timepoint: " << dariadb::timeutil::to_string(measurement.time)
              << " value:" << measurement.value << std::endl;
  }

  // current values
  dariadb::Id2Meas cur_values = storage->currentValue(all_id, dariadb::Flag());
  std::cout << "Current: " << std::endl;
  for (auto kv : timepoint) {
    auto measurement = kv.second;
    std::cout << " id: " << all_params[kv.first]
              << " timepoint: " << dariadb::timeutil::to_string(measurement.time)
              << " value:" << measurement.value << std::endl;
  }

  // callback
  std::cout << "Callback in interval: " << std::endl;
  Callback callback;
  storage->foreach (qi, &callback);
  callback.wait();

  // callback
  std::cout << "Callback in timepoint: " << std::endl;
  storage->foreach (qp, &callback);
  callback.wait();

  { // stat
    auto stat = storage->stat(dariadb::Id(0), start_time, m.time);
    std::cout << "count: " << stat.count << std::endl;
    std::cout << "time: [" << dariadb::timeutil::to_string(stat.minTime) << " "
              << dariadb::timeutil::to_string(stat.maxTime) << "]" << std::endl;
    std::cout << "val: [" << stat.minValue << " " << stat.maxValue << "]" << std::endl;
    std::cout << "sum: " << stat.sum << std::endl;
  }

  { // statistical functions
    dariadb::statistic::Calculator calc(storage);
    auto all_functions = dariadb::statistic::FunctionFactory::functions();
    std::cout << "available functions: " << std::endl;
    for (auto fname : all_functions) {
      std::cout << " " << fname << std::endl;
    }
    auto result =
        calc.apply(dariadb::Id(0), start_time, m.time, dariadb::Flag(), all_functions);
    for (size_t i = 0; i < result.size(); ++i) {
      auto measurement = result[i];
      std::cout << all_functions[i] << " id: " << all_params[m.id].name
                << " timepoint: " << dariadb::timeutil::to_string(measurement.time)
                << " value:" << measurement.value << std::endl;
    }
  }
}
Exemple #30
0
void process_command (void)
{
    uint8_t num_tokens = tokenize_command();
    
    if (num_tokens == 0)  // no commands
        return;
    
    /*
    for (uint8_t i = 0; i < num_tokens; i++)
    {
        m_usb_tx_char ('\t');
        
        for (char *ptr = command_tokens[i]; *ptr != '\0'; ptr++)
            m_usb_tx_char (*ptr);
        
        printf ("\n");
    }
    */
    
    if (strcmp (command_tokens[0], "help") == 0)
        printf ("Commands: ls, cd, print, mkdir, rmdir, write, append, edit, keycode\r\n");
    else if (strcmp (command_tokens[0], "ls") == 0)
    {
        if (num_tokens > 1)
            printf ("ls does not take any arguments\r\n");
        else
            ls();
    }
    else if (strcmp (command_tokens[0], "cd") == 0)
    {
        if (num_tokens != 2)
        {
            printf ("cd requires one argument (the destination directory)\r\n");
            return;
        }
        
        if (!m_sd_push (command_tokens[1]))
            printf ("error entering ");
        else
            printf ("now in ");
        
        for (char *c = command_tokens[1]; *c != '\0'; c++)
            putchar (*c);
        printf ("\r\n");
    }
    else if (strcmp (command_tokens[0], "print") == 0)
    {
        if (num_tokens != 2)
        {
            printf ("print requires one argument (the file to print)\r\n");
            return;
        }
        
        printFile (command_tokens[1]);
    }
    else if (strcmp (command_tokens[0], "mkdir") == 0)
    {
        if (num_tokens != 2)
        {
            printf ("mkdir requires one argument (the directory to create)\r\n");
            return;
        }
        
        if (!m_sd_mkdir (command_tokens[1]))
        {
            printf ("error creating directory ");
        }
        else
        {
            printf ("successfully created directory ");
            m_sd_commit();
        }
        
        for (char *c = command_tokens[1]; *c != '\0'; c++)
            putchar (*c);
        printf ("\r\n");
    }
    else if (strcmp (command_tokens[0], "rmdir") == 0)
    {
        if (num_tokens != 2)
        {
            printf ("rmdir requires one argument (the directory to delete)\n");
            return;
        }
        
        if (!m_sd_rmdir (command_tokens[1]))
        {
            printf ("error deleting directory ");
        }
        else
        {
            printf ("successfully deleted directory ");
            m_sd_commit();
        }
        
        for (char *c = command_tokens[1]; *c != '\0'; c++)
            putchar (*c);
        printf ("\r\n");
    }
    else if (strcmp (command_tokens[0], "write") == 0)
    {
        if (num_tokens < 3)
        {
            printf ("write requires a filename, followed by the data to write\r\n");
            return;
        }
        
        writeToFile (command_tokens[1],
                     CREATE_FILE,
                     command_ptr - command_tokens[2],
                     (uint8_t*)command_tokens[2]);
    }
    else if (strcmp (command_tokens[0], "append") == 0)
    {
        if (num_tokens < 3)
        {
            printf ("append requires a filename, followed by the data to write\r\n");
            return;
        }
        
        writeToFile (command_tokens[1],
                     APPEND_FILE,
                     command_ptr - command_tokens[2],
                     (uint8_t*)command_tokens[2]);
    }
    else if (strcmp (command_tokens[0], "edit") == 0)
    {
        if (num_tokens < 2)
        {
            printf ("edit requires a filename\r\n");
            return;
        }
        
        uint8_t fid = 255;
        if (!m_sd_open_file (command_tokens[1], APPEND_FILE, &fid))
        {  // if opening the file in r/w mode failed
            if (m_sd_error_code == ERROR_FAT32_NOT_FOUND)
            {  // if the reason was because the file doesn't exist, try creating it
                m_sd_open_file (command_tokens[1], CREATE_FILE, &fid);
            }
        }
        
        if (fid == 255)
        {  // the file is still not open
            printf ("Couldn't open/create file ");
            for (char *c = command_tokens[1]; *c != '\0'; c++)
                putchar (*c);
            printf ("\r\n");
            return;
        }
        
        edit (fid, command_tokens[1]);
        
        if (!m_sd_close_file (fid))
        {
            printf ("Error closing file!  Error code %d\r\n", m_sd_error_code);
        }
    }
    else if (strcmp (command_tokens[0], "keycode") == 0)
    {  // print the ASCII number of the pressed keys, CTRL-C exits
        keycodes();
    }
    else
    {
        printf ("unknown command\r\n");
    }
}