static int bch_dec(int c[255], int n, int t)
{
	int i, j, tmp;
	int s[4], a[6], b[6], temp[6], deg_a, deg_b;
	int sig[5], deg_sig;
	int errloc[4], errcnt;

	memset(s, 0, 4*sizeof(int));
	for (j=0; j<n; j++)
		for (i=0; i<t*2; i++)
			s[i] = cm(i+1, s[i]) ^ (c[j]&1);

	memset(a, 0, 6*sizeof(int));
	memset(b, 0, 6*sizeof(int));
	a[0] = 1;
	deg_a = t*2;
	for (i=0; i<t*2; i++) b[i] = s[t*2-1-i];
		deg_b = t*2-1;

	a[t*2+1] = 1;
	b[t*2+1] = 0;
	while (deg_b >= t) {
		if (b[0] == 0) {
			memmove(b, b+1, 5*sizeof(int));
			b[5] = 0;
			deg_b--;
        }
        else {
			for (i=t*2+1; i>deg_a; i--)
				b[i] = gm(b[i], b[0]) ^ gm(a[i], a[0]);
			for (i=deg_a; i>deg_b; i--) {
				b[i] = gm(b[i], b[0]);
				a[i] = gm(a[i], b[0]);
			}
			for (; i>0; i--)
				a[i] = gm(a[i], b[0]) ^ gm(b[i], a[0]);
				memmove(a, a+1, 5*sizeof(int));
				a[5] = 0;
				deg_a--;

			if (deg_a < deg_b) {
				memcpy(temp, a, 6*sizeof(int));
				memcpy(a, b, 6*sizeof(int));
				memcpy(b, temp, 6*sizeof(int));

				tmp = deg_a;
				deg_a = deg_b;
				deg_b = tmp;
			}
		}
	}

	deg_sig = t*2 - deg_a;
	memcpy(sig, a+deg_a+1, (deg_sig+1)*sizeof(int));

	errcnt = 0;
	for (j=0; j<255; j++) {
		tmp = 0;
		for (i=0; i<=deg_sig; i++) {
			sig[i] = cm(i, sig[i]);
			tmp ^= sig[i];
		}

		if (tmp == 0) {
			errloc[errcnt] = j - (255-n);
			if (errloc[errcnt] >= 0)
			errcnt++;
		}
	}

	if (errcnt<deg_sig) {
		return -1;
	}

	for (i=0; i<errcnt; i++) {
		c[errloc[i]] ^= 1;
		__D("fix error at %4d\n", errloc[i]);
	}

	return errcnt;
}
示例#2
0
 //! Default facet implementation uses month_type defaults
 virtual void do_put_month_short(iter_type& oitr, month_enum moy) const
 {
   month_type gm(moy);
   charT c = '\0';
   put_string(oitr, gm.as_short_string(c));
 }
示例#3
0
MaxCutHyperheuristic::MaxCutHyperheuristic(const MaxCutInstance&mi,
                                           double runtime_limit,
                                           bool validation,
                                           MaxCutCallback *mc, int seed,
                                           std::string* selected) :
  MaxCutHeuristic(mi, runtime_limit, validation, mc) {
  // Step 1: Calculate graph metrics for this instance.
  GraphMetrics gm(mi);
  std::vector<double> metrics;
  gm.AllMetrics(&metrics, NULL);

  // Step 2: Obtain predicted probabilities from each random forest model.
  // Best-performing model information (using streaming alg to select best)
  double bestProbability = -1.0;
  Prob bestProblem = MaxCut;
  std::string bestCode = "";
  int numBest = 1;  // Number tied for best

  // Check the Max-Cut heuristics
  HeuristicFactory factory;
  std::vector<std::string> codes;
  factory.MaxCutHeuristicCodes(&codes);
  for (int i=0; i < codes.size(); ++i) {
    UpdateBestModel(codes[i], MaxCut, metrics, &bestProbability, &bestProblem,
                    &bestCode, &numBest);
  }

  // Check the QUBO heuristics
  factory.QUBOHeuristicCodes(&codes);
  for (int i=0; i < codes.size(); ++i) {
    UpdateBestModel(codes[i], QUBO, metrics, &bestProbability, &bestProblem,
                    &bestCode, &numBest);
  }
  if (selected) {
    *selected = bestCode;
  }

  // Step 3: Run the selected heuristic "H", using callbacks to capture all the
  // reported solutions from "H" and report them for the hyper-heuristic.
  // Because several previous steps may have used random draws or set the
  // random seed, re-set the seed to the original here.
  srand(seed);
  if (bestProblem == MaxCut) {
    // Using a Max-Cut heuristic
    HyperheuristicMaxCutCallback callback(this);
    // Run with our callback and no validation (solutions will be validated
    // with the hyperheuristic, so no need to double validate)
    Heuristic *h = factory.RunMaxCutHeuristic(bestCode, mi, runtime_limit,
                                              false, &callback);
    delete h;  // We don't need to keep around the pointer
  } else if (bestProblem == QUBO) {
    // Using a QUBO heuristic
    HyperheuristicQUBOCallback callback(this, mi);
    QUBOInstance qi(mi);  // Need to construct a QUBOInstance for heuristic
    // Run with our callback and no validation (solutions will be validated
    // with the hyperheuristic, so no need to double validate)
    Heuristic *h = factory.RunQUBOHeuristic(bestCode, qi, runtime_limit,
                                            false, &callback);
    delete h;  // We don't need to keep around the pointer
  }
}
示例#4
0
void MT(void)
{
    char buf[10];
    while(1)
    {
        sen.pro = 2;
        system("clear");
        printf("-----欢迎进入MT-----\n\n");
        printf("--------------------\n");
        printf("1--------私聊-------\n");
        printf("2--------群聊-------\n");
        printf("3---------FTP-------\n");
        printf("4---------VIP-------\n");
        printf("5------修改状态-----\n");
        printf("6------修改密码-----\n");
        printf("7--------注销-------\n");
        printf("8--------退出-------\n");
        printf("--------------------\n\n");

        printf("请输入你的选择:");
        memset(buf,0,10);
        fgets(buf,10,stdin);
        if(strlen(buf) > 2)
        {
            continue;
        }
        if(buf[0] == '1')
        {
            sl();
        }
        else if(buf[0] == '2')
        {
            ql();
        }
        else if(buf[0] == '3')
        {
            ftp();
        }
        else if(buf[0] == '4')
        {
            vip();
        }
        else if(buf[0] == '5')
        {
            zt();
        }
        else if(buf[0] == '6')
        {
            gm();   
        }
        else if(buf[0] == '7')
        {
            sen.pro = 6;
            strcpy(sen.message,"ZX");
            send(fd,&sen,len_data,0);
            MAIN(); 
        }
        else if(buf[0] == '8')
        {
            sen.pro = 6;
            strcpy(sen.message,"MT");
            send(fd,&sen,len_data,0);
            exit(0);
        }
    }
}
void dynamics_mul::compute_intensity_force(){
    HMesh::HalfEdgeAttributeVector<int> touched(s_dsc->get_no_halfedges(), 0);
    
    for (auto eit = s_dsc->halfedges_begin(); eit != s_dsc->halfedges_end(); eit++) {
        if(s_dsc->is_interface(*eit) and !touched[*eit]){
            auto hew = s_dsc->walker(*eit);
            
            double c0 = mean_inten_[s_dsc->get_label(hew.face())];
            double c1 = mean_inten_[s_dsc->get_label(hew.opp().face())];
            
            // Loop on the edge
            auto p0 = s_dsc->get_pos(hew.opp().vertex());
            auto p1 = s_dsc->get_pos(hew.vertex());
            
            Vec2 L01 = p1 - p0;
            L01.normalize();
            Vec2 N01(L01[1], -L01[0]); // Outward pointing normal
            
            int length = (int)(p1 - p0).length();
            double f0 = 0.0, f1 = 0.0;
            Vec2 fg0(0.0), fg1(0.0);
            for (int i = 0; i <= length; i++) {
                auto p = p0 + (p1 - p0)*(double(i)/(double)length);
                double I = s_img->get_intensity(p[0], p[1]);
                
                // Normalize force
                int normalizedF = 1;
                double f ;
                switch (normalizedF) {
                    case 1:
                        f = ( (c0-c1)*(2*I - c0 - c1)) / ((c0-c1)*(c0-c1));
                        break;
                    case 2:
                        f = ( (c0-c1)*(2*I - c0 - c1)) / std::abs((c0 - c1));
                        break;
                    case 3:
                        f = (c0-c1)*(2*I - c0 - c1);
                        break;
                    default:
                        f = 0.0;
                        break;
                }
                
                Vec2 fu = N01*(c0-c1)*(2*I - c0 - c1);
                
                // Image gradient force
                int lengthM = 10;
                Vec2 gm(0.0); double max_grad = 0;
                for (int l = 0; l < lengthM; l++) {
                    Vec2 curPt = p + fu*(l/(double)(lengthM));
                    Vec2 gg = s_img->grad((int)curPt[0], (int)curPt[1]);
                    if (max_grad < gg.length()) {
                        max_grad = gg.length();
                        gm = gg*(lengthM - l)/(double)lengthM;
                    }
                }
                

                Vec2 fg = gm*(2*I - c0 - c1);
                
                Vec2 fv = (fu + fg)/((c0-c1)*(c0-c1));
                
                fg0 += fv*(p-p1).length() / (double)length;
                fg1 += fv*(p-p0).length() / (double)length;
                
                // Barry Centric coordinate
                f0 += f*(p-p1).length() / (double)length;
                f1 += f*(p-p0).length() / (double)length;
                
                // Image gradient force
//                Vec2 fg = s_img->grad((int)p[0], (int)p[1]) * (2*I - c0 - c1) / ((c0-c1)*(c0-c1));
//                fg0 += fg*(p-p1).length() / (double)length;
//                fg1 += fg*(p-p0).length() / (double)length;
            }
            
            // Set force
            
            Vec2 f_x0 = fg0; // N01*f0;
            Vec2 f_x1 = fg1; // N01*f1;
            
            s_dsc->add_node_external_force(hew.opp().vertex(), f_x0*g_param.beta);
            s_dsc->add_node_external_force(hew.vertex(), f_x1*g_param.beta);
            
            // Avoid retouch the edge
            touched[*eit] = 1;
            touched[hew.opp().halfedge()] = 1;
        }
    }
}
示例#6
0
    void
    modifVec(std::list<ElementRange> const& __r, eltType const& u,vectorType & UnVec,ExprType const& expr,
             size_type rowstart, int ComponentShiftFactor,
             mpl::int_<MESH_EDGES> /**/ )
    {
        const size_type context = ExprType::context|vm::POINT;

        auto mesh = u.functionSpace()->mesh().get();
        auto const* dof = u.functionSpace()->dof().get();
        auto const* fe = u.functionSpace()->fe().get();


        if ( __r.size() == 0 ) return;
        auto edge_it =  __r.begin()->template get<1>();
        auto edge_en =  __r.begin()->template get<2>();

        bool findAEdge = false;
        for( auto lit = __r.begin(), len = __r.end(); lit != len; ++lit )
        {
            edge_it = lit->template get<1>();
            edge_en = lit->template get<2>();
            if ( edge_it != edge_en )
            {
                findAEdge=true;
                break;
            }
        }
        if ( !findAEdge ) return;

        auto const& edgeForInit = boost::unwrap_ref( *edge_it );

        auto gm = mesh->gm();
        //auto const& firstEntity = *entity_it;
        size_type eid = edgeForInit.elements().begin()->first;
        size_type ptid_in_element = edgeForInit.elements().begin()->second;
        auto const& elt = mesh->element( eid );
        auto geopc = gm->preCompute( fe->edgePoints(ptid_in_element) );
        auto ctx = gm->template context<context>( elt, geopc );
        auto expr_evaluator = expr.evaluator( mapgmc(ctx) );
        auto IhLoc = fe->edgeLocalInterpolant();

        std::vector<bool> dofdone( dof->nLocalDofWithGhost(), false );

        for( auto const& lit : __r )
        {
            edge_it = lit.template get<1>();
            edge_en = lit.template get<2>();
            for ( ; edge_it != edge_en;++edge_it )
            {
                auto const& theedge = boost::unwrap_ref( *edge_it );

                if ( theedge.isGhostCell() )
                {
                    LOG(WARNING) << "edge id : " << theedge.id() << " is a ghost edge";
                    continue;
                }

                size_type eid = theedge.elements().begin()->first;
                size_type edgeid_in_element = theedge.elements().begin()->second;
                auto const& elt = mesh->element( eid );
                geopc = gm->preCompute( fe->edgePoints(edgeid_in_element) );
                ctx->update( elt, geopc );
                expr_evaluator.update( mapgmc( ctx ) );
                fe->edgeInterpolate( expr_evaluator, IhLoc );

                for( auto const& ldof : u.functionSpace()->dof()->edgeLocalDof( eid, edgeid_in_element ) )
                {
                    size_type index = ldof.index();
                    if ( dofdone[index] ) continue;
                    //size_type thedof = u.start()+ (is_comp_space?Elem1::nComponents:1)*ldof.index();
                    size_type thedof = u.start() + ComponentShiftFactor*index;
                    double value = ldof.sign()*IhLoc( ldof.localDofInFace() );
                    UnVec->set(rowstart+thedof,value);
                    dofdone[index] = true;
                }
            } // edge_it
        } // lit
    }
示例#7
0
    void
    modifVec(std::list<ElementRange> const& __r, eltType const& u,vectorType & UnVec,ExprType const& expr,
             size_type rowstart, int ComponentShiftFactor,
             mpl::int_<MESH_POINTS> /**/ )
    {
        const size_type context = ExprType::context|vm::POINT;

        auto mesh = u.functionSpace()->mesh().get();
        auto const* dof = u.functionSpace()->dof().get();
        auto const* fe = u.functionSpace()->fe().get();

        if ( __r.size() == 0 ) return;
        auto point_it =  __r.begin()->template get<1>();
        auto point_en =  __r.begin()->template get<2>();

        bool findAPoint = false;
        for( auto lit = __r.begin(), len = __r.end(); lit != len; ++lit )
        {
            point_it = lit->template get<1>();
            point_en = lit->template get<2>();
            if ( point_it != point_en )
            {
                findAPoint=true;
                break;
            }
        }
        if ( !findAPoint ) return;

        auto const& pointForInit = boost::unwrap_ref( *point_it );

        size_type eid = pointForInit.elements().begin()->first;
        size_type ptid_in_element = pointForInit.elements().begin()->second;

        auto const& elt = mesh->element( eid );
        auto gm = mesh->gm();
        auto geopc = gm->preCompute( fe->vertexPoints(ptid_in_element) );
        auto ctx = gm->template context<context>( elt, geopc );
        auto expr_evaluator = expr.evaluator( mapgmc(ctx) );
        auto IhLoc = fe->vertexLocalInterpolant();

        std::vector<bool> dofdone( dof->nLocalDofWithGhost(), false );

        for( auto const& lit : __r )
        {
            point_it = lit.template get<1>();
            point_en = lit.template get<2>();
            DVLOG(2) << "point " << point_it->id() << " with marker " << point_it->marker() << " nb: " << std::distance(point_it,point_en);

            if ( point_it == point_en )
                continue;

            for ( ; point_it != point_en;++point_it )
            {
                auto const& thept = boost::unwrap_ref( *point_it );

                size_type eid = thept.elements().begin()->first;
                size_type ptid_in_element = thept.elements().begin()->second;
                auto const& elt = mesh->element( eid );
                geopc = gm->preCompute( fe->vertexPoints(ptid_in_element) );
                ctx->update( elt, ptid_in_element, geopc, mpl::int_<0>() );
                expr_evaluator.update( mapgmc( ctx ) );
                fe->vertexInterpolate( expr_evaluator, IhLoc );

                for (int c1=0;c1<eltType::nComponents1;c1++)
                    //for( int c = 0; c < (is_product?nComponents:1); ++c )
                {
                    size_type index = dof->localToGlobal( eid, ptid_in_element, c1 ).index();
                    //size_type thedof = u.start()+ (is_comp_space?Elem1::nComponents:1)*index; // global dof
                    size_type thedof = u.start() + ComponentShiftFactor*index;
                    if ( dofdone[index] ) continue;
                    double value = IhLoc( c1 );
                    UnVec->set(rowstart+thedof,value);
                    dofdone[index] = true;
                }
            }
        }

    }
示例#8
0
void TankLogic::MakeMove(Consoden::TankGame::GameStatePtr gameState)
{
    GameMap gm(m_ownTankId, gameState);
    auto currentPosition=gm.OwnPosition();
    auto enemyPosition=gm.EnemyPosition();
    BfsHelper bfs(gameState, currentPosition);
    Consoden::TankGame::Direction::Enumeration moveDirection;

    // Look for powerups and enemy
    int enemySteps = 20000;
    if (bfs.CanReachSquare(enemyPosition)) {
        enemySteps = bfs.StepsToSquare(enemyPosition);
    }

    int powerUpSteps = 20000;
    std::pair<int,int> powerUpPos;
    for (int x = 0; x < gm.SizeX(); x++) {
        for (int y = 0; y < gm.SizeY(); y++) {
            std::pair<int,int> pos = std::make_pair(x, y);
            if (!bfs.CanReachSquare(pos)) {
                continue;
            }

            if ((gm.IsLaserAmmo(pos) || gm.IsRedeemerAmmo(pos) || gm.IsSmokeGrenade(pos)) && powerUpSteps > bfs.StepsToSquare(pos)) {
                powerUpSteps = bfs.StepsToSquare(pos);
                powerUpPos = pos;
            }
        }
    }

    if (powerUpSteps < enemySteps) {
        // It is possible to get a power up, do it
        moveDirection=bfs.FindDirection(currentPosition, bfs.BacktrackFromSquare(powerUpPos));

    } else if (enemySteps < 20000) {
        // It is possible to move all the way to the enemy, do it
        moveDirection=bfs.FindDirection(currentPosition, bfs.BacktrackFromSquare(enemyPosition));

    } else {
        //Find an empty sqaure we can move to, otherwise stand still
        moveDirection=Consoden::TankGame::Direction::Neutral;
        if (!gm.IsWall(gm.Move(currentPosition, Consoden::TankGame::Direction::Left)) &&
            !gm.IsMine(gm.Move(currentPosition, Consoden::TankGame::Direction::Left)))
        {
            moveDirection=Consoden::TankGame::Direction::Left;
        }
        else if (!gm.IsWall(gm.Move(currentPosition, Consoden::TankGame::Direction::Right)) &&
                 !gm.IsMine(gm.Move(currentPosition, Consoden::TankGame::Direction::Right)))
        {
            moveDirection=Consoden::TankGame::Direction::Right;
        }
        else if (!gm.IsWall(gm.Move(currentPosition, Consoden::TankGame::Direction::Up)) &&
                 !gm.IsMine(gm.Move(currentPosition, Consoden::TankGame::Direction::Up)))
        {
            moveDirection=Consoden::TankGame::Direction::Up;
        }
        else if (!gm.IsWall(gm.Move(currentPosition, Consoden::TankGame::Direction::Down)) &&
                 !gm.IsMine(gm.Move(currentPosition, Consoden::TankGame::Direction::Down)))
        {
            moveDirection=Consoden::TankGame::Direction::Down;
        }
    }

    // Evaluate firing direction
    int opponent_x = gm.EnemyPosition().first;
    int opponent_y = gm.EnemyPosition().second;
    int player_x = gm.OwnPosition().first;
    int player_y = gm.OwnPosition().second;
    int x_distance;
    int x_wrap_distance;
    Consoden::TankGame::Direction::Enumeration x_direction;
    int y_distance;
    int y_wrap_distance;
    Consoden::TankGame::Direction::Enumeration y_direction;
    Consoden::TankGame::Direction::Enumeration tower_direction;

    if (opponent_x > player_x) {
        // opponent to the right
        x_distance = opponent_x - player_x;
        x_wrap_distance = player_x - opponent_x + gm.SizeX();
        if (x_distance < x_wrap_distance || !bfs.CanWrapX()) {
            x_direction = Consoden::TankGame::Direction::Right; //Shortest linear path to enemy is right
        } else {
            x_direction = Consoden::TankGame::Direction::Left; //Shortest linear path to enemy is left
            x_distance = x_wrap_distance;
        }
    } else {
        // opponent to the left
        x_distance = player_x - opponent_x;
        x_wrap_distance = opponent_x - player_x + gm.SizeX();
        if (x_distance < x_wrap_distance || !bfs.CanWrapX()) {
            x_direction = Consoden::TankGame::Direction::Left; //Shortest linear path to enemy is left
        } else {
            x_direction = Consoden::TankGame::Direction::Right; //Shortest linear path to enemy is right
            x_distance = x_wrap_distance;
        }            
    }

    if (opponent_y > player_y) {
        // opponent is down
        y_distance = opponent_y - player_y;
        y_wrap_distance = player_y - opponent_y + gm.SizeY();
        if (y_distance < y_wrap_distance || !bfs.CanWrapY()) {
            y_direction = Consoden::TankGame::Direction::Down; //Shortest linear path to enemy is down
        } else {
            y_direction = Consoden::TankGame::Direction::Up; //Shortest linear path to enemy is up
            y_distance = y_wrap_distance;
        }
    } else {
        // opponent is up
        y_distance = player_y - opponent_y;
        y_wrap_distance = opponent_y - player_y + gm.SizeY();
        if (y_distance < y_wrap_distance || !bfs.CanWrapY()) {
            y_direction = Consoden::TankGame::Direction::Up; //Shortest linear path to enemy is up
        } else {
            y_direction = Consoden::TankGame::Direction::Down; //Shortest linear path to enemy is down
            y_distance = y_wrap_distance;
        }            
    }

    if (x_distance > y_distance) {
        tower_direction = x_direction;
    } else {
        tower_direction = y_direction;
    }

    // Firing logic
    bool fire = false;
    bool fire_redeemer = false;
    int redemer_timer = 3;
    bool fire_laser = false;
    bool deploy_smoke = false;
    bool drop_mine = false;

    if (gm.HasSmoke()) {
        deploy_smoke = true;
    }

    if (gm.HasRedeemer()) {
        fire_redeemer = true;
        fire = true;
        redemer_timer = 4;
    } else if (gm.LaserAmmoCount() > 0) {
        fire_laser = true;
        fire = true;
        // Stand still to fire laser
        moveDirection = Consoden::TankGame::Direction::Neutral;
    } else {
        // Go for regular missile
        fire = true;
    }

    //Sometimes we also drop a mine
    drop_mine=(static_cast<int>(gameState->ElapsedTime().GetVal()) % 3)==0;

    //Move our joystick.
    SetJoystick(moveDirection, tower_direction, fire, drop_mine, fire_laser,deploy_smoke,fire_redeemer, redemer_timer);
}
void UnifyingConflator::apply(shared_ptr<OsmMap>& map)
{
  Timer timer;
  _reset();

  NamedOp(ConfigOptions().getUnifyPreOps().split(";", QString::SkipEmptyParts)).apply(map);

  _stats.append(SingleStat("Apply Pre Ops Time (sec)", timer.getElapsedAndRestart()));

  // will reproject if necessary.
  MapReprojector::reprojectToPlanar(map);

  _stats.append(SingleStat("Project to Planar Time (sec)", timer.getElapsedAndRestart()));

  if (Log::getInstance().isDebugEnabled())
  {
    LOG_DEBUG("Writing debug map.");
    OsmMapPtr debug(new OsmMap(map));
    MapReprojector::reprojectToWgs84(debug);
    OsmMapWriterFactory::write(debug, "tmp/debug.osm");

    _stats.append(SingleStat("Write Debug Map Time (sec)", timer.getElapsedAndRestart()));
  }

  LOG_DEBUG("Creating matches...");
  // find all the matches in this map
  if (_matchThreshold.get())
  {
    //ScoreMatches logic seems to be the only one that needs to pass in the match threshold now when
    //the optimize param is activated.  Otherwise, we get the match threshold information from the
    //config.
    _matchFactory.createMatches(map, _matches, _bounds, _matchThreshold);
  }
  else
  {
    _matchFactory.createMatches(map, _matches, _bounds);
  }
  LOG_DEBUG("Match count: " << _matches.size());
  LOG_DEBUG(SystemInfo::getMemoryUsageString());

  double findMatchesTime = timer.getElapsedAndRestart();
  _stats.append(SingleStat("Find Matches Time (sec)", findMatchesTime));
  _stats.append(SingleStat("Number of Matches Found", _matches.size()));
  _stats.append(SingleStat("Number of Matches Found per Second",
    (double)_matches.size() / findMatchesTime));

  vector<const Match*> allMatches = _matches;

  // add review tags to all matches that have some review component
  _addReviewTags(map, allMatches);
  LOG_INFO("Pre-constraining match count: " << allMatches.size());

  _stats.append(SingleStat("Number of Matches Before Whole Groups", _matches.size()));

  // If there are groups of matches that should not be optimized, remove them before optimization.
  MatchSetVector matchSets;
  _removeWholeGroups(_matches, matchSets, map);
  _stats.append(SingleStat("Number of Whole Groups", matchSets.size()));

  // Globally optimize the set of matches to maximize the conflation score.
  {
    OptimalConstrainedMatches cm(map);
    cm.addMatches(_matches.begin(), _matches.end());

    cm.setTimeLimit(ConfigOptions(_settings).getUnifyOptimizerTimeLimit());

    double cmStart = Time::getTime();
    vector<const Match*> cmMatches = cm.calculateSubset();
    LOG_INFO("CM took: " << Time::getTime() - cmStart << "s.");
    LOG_INFO("CM Score: " << cm.getScore());
    LOG_DEBUG(SystemInfo::getMemoryUsageString());

    GreedyConstrainedMatches gm(map);
    gm.addMatches(_matches.begin(), _matches.end());
    double gmStart = Time::getTime();
    vector<const Match*> gmMatches = gm.calculateSubset();
    LOG_INFO("GM took: " << Time::getTime() - gmStart << "s.");
    LOG_INFO("GM Score: " << gm.getScore());

    if (gm.getScore() > cm.getScore())
    {
      _matches = gmMatches;
    }
    else
    {
      _matches = cmMatches;
    }
  }

  double optimizeMatchesTime = timer.getElapsedAndRestart();
  _stats.append(SingleStat("Optimize Matches Time (sec)", optimizeMatchesTime));
  _stats.append(SingleStat("Number of Optimized Matches", _matches.size()));
  _stats.append(SingleStat("Number of Matches Optimized per Second",
    (double)allMatches.size() / optimizeMatchesTime));

  LOG_DEBUG(SystemInfo::getMemoryUsageString());

//  #warning validateConflictSubset is on, this is slow.
//  _validateConflictSubset(map, _matches);

  LOG_INFO("Post constraining match count: " << _matches.size());

  {
    // search the matches for groups (subgraphs) of matches. In other words, groups where all the
    // matches are interrelated by element id
    MatchGraph mg;
    mg.addMatches(_matches.begin(), _matches.end());
    vector< set<const Match*, MatchPtrComparator> > tmpMatchSets =
      mg.findSubgraphs(map);
    matchSets.insert(matchSets.end(), tmpMatchSets.begin(), tmpMatchSets.end());
    LOG_DEBUG(SystemInfo::getMemoryUsageString());
  }

  LOG_DEBUG("Match sets count: " << matchSets.size());
  LOG_DEBUG(SystemInfo::getMemoryUsageString());
  /// @todo would it help to sort the matches so the biggest or best ones get merged first?

  // convert all the match sets into mergers.
  for (size_t i = 0; i < matchSets.size(); ++i)
  {
    _mergerFactory->createMergers(map, matchSets[i], _mergers);
  }

  LOG_DEBUG(SystemInfo::getMemoryUsageString());
  // don't need the matches any more
  _deleteAll(allMatches);
  _matches.clear();

  LOG_DEBUG(SystemInfo::getMemoryUsageString());
  _mapElementIdsToMergers();
  LOG_DEBUG(SystemInfo::getMemoryUsageString());

  _stats.append(SingleStat("Create Mergers Time (sec)", timer.getElapsedAndRestart()));

  vector< pair<ElementId, ElementId> > replaced;
  for (size_t i = 0; i < _mergers.size(); ++i)
  {
    _mergers[i]->apply(map, replaced);

    // update any mergers that reference the replaced values
    _replaceElementIds(replaced);
    replaced.clear();
    if (Log::getInstance().getLevel() == Log::Debug)
    {
      cout << "Applying mergers: " << i + 1 << " / " << _mergers.size() << "       \r" << flush;
    }
  }
  if (Log::getInstance().getLevel() == Log::Debug)
  {
    cout << endl;
  }
  LOG_DEBUG(SystemInfo::getMemoryUsageString());
  size_t mergerCount = _mergers.size();
  // free up any used resources.
  _reset();
  LOG_DEBUG(SystemInfo::getMemoryUsageString());

  double mergersTime = timer.getElapsedAndRestart();
  _stats.append(SingleStat("Apply Mergers Time (sec)", mergersTime));
  _stats.append(SingleStat("Mergers Applied per Second", (double)mergerCount / mergersTime));

  NamedOp(ConfigOptions().getUnifyPostOps().split(";", QString::SkipEmptyParts)).apply(map);

  _stats.append(SingleStat("Apply Post Ops Time (sec)", timer.getElapsedAndRestart()));
}
示例#10
0
文件: temp.cpp 项目: 199911/acm
int joseph(int n, int k){   // O(klogn)
	if(n<=1)return 0;
	if(k==1)return n-1;  // this line of code can be handled by caller
	int x=(n+k-1)/k;
	return (x*k+(joseph(n-x,k)*k+gm(x-n,k-1))/(k-1)+(x*k==n+k-1))%n;
}
/* Backward propagation of a reduction on (p + q), where p is a garbled mix,
   and q a precise pointer or an integer. */
void main3 () {
  int a = 0, b = 1, c = 2;
  int *p = gm (&a);
  int *q = rand ? &b : (int*)rand;
  int v; char w;
  if (rand) {
    /* According to the C semantics, computes (p + sizeof(*p) q),
       so the b address from q is lost in the operation. */
    v = *((p + (uintptr_t)q));
    Frama_C_show_each_GM_only_a(p, q);
  }

  if (rand) {
    /* Here, size = 0, so &b+[0..3] is valid, and p is reduced accordingly. */
    w = *(((char*)p + (uintptr_t)q));
    Frama_C_show_each_GM_reduce_p_offset(p, q);
  }

  p = gm (&a);
  q = &b;

  if (rand) {
    /* The same but q is only a pointer, so &a is impossible too. */
    v = *((p + (uintptr_t)q));
    Frama_C_show_each_GM_BOTTOM(p, q);
  }

  p = gm (rand ? &a : &b);
  q = rand ? &b : (int*)rand;

  if (rand) {
    /* Here, &b appear in the garbled mix of p, and may interfere with the
       (4 * &b) from q: no reduction is feasible. */
    v = *((p + (uintptr_t)q));
    Frama_C_show_each_GM_no_reduction(p, q);
  }

  p = gm (rand ? &a : &b);
  q = rand ? &c : (int*)rand;

  if (rand) {
    /* &c is the only valid location after the condition, so q = &c and p = 0. */
    if ( *(((char*)p + (uintptr_t)q)) == 2)
      Frama_C_show_each_GM_only_c(p, q);
  }
  if (rand) {
    /* &b is the only valid location after the condition, so p = &b+[..] and
       q is an integer. */
    if ( *((p + (uintptr_t)q)) == 1)
      Frama_C_show_each_GM_only_b(p, q);
  }

  p = gm (rand ? &a : &b);
  q = rand ? &b : (int*)rand;

  if (rand) {
    /* No pointer on c, so bottom after the condition. */
    if ( *(((char*)p + (uintptr_t)q)) == 2)
      Frama_C_show_each_GM_BOTTOM(p, q);
  }
  if (rand) {
    /* &b is the only valid location after the condition, but it may be builds
       by any combination of a garbled mix of &b for p. */
    if ( *(((char*)p + (uintptr_t)q)) == 1)
      Frama_C_show_each_GM_only_b_and_gm(p, q);
  }
}
示例#12
0
void CMomentumPlayer::Spawn()
{
    SetModel(ENTITY_MODEL);
    SetBodygroup(1, 11);//BODY_PROLATE_ELLIPSE
    // BASECLASS SPAWN MUST BE AFTER SETTING THE MODEL, OTHERWISE A NULL HAPPENS!
    BaseClass::Spawn();
    AddFlag(FL_GODMODE);
    RemoveSolidFlags(FSOLID_NOT_SOLID); // this removes the flag that was added while switching to spectator mode which
                                        // prevented the player from activating triggers
    // do this here because we can't get a local player in the timer class
    ConVarRef gm("mom_gamemode");
    switch (gm.GetInt())
    {
    case MOMGM_BHOP:
    case MOMGM_SURF:
    case MOMGM_UNKNOWN:
    default:
        EnableAutoBhop();
        break;
    case MOMGM_SCROLL:
        DisableAutoBhop();
        break;
    }
    // Reset all bool gameevents
    IGameEvent *runSaveEvent = gameeventmanager->CreateEvent("run_save");
    IGameEvent *runUploadEvent = gameeventmanager->CreateEvent("run_upload");
    IGameEvent *timerStartEvent = gameeventmanager->CreateEvent("timer_state");
    m_RunData.m_bIsInZone = false;
    m_RunData.m_bMapFinished = false;
    m_RunData.m_iCurrentZone = 0;
    m_bHasPracticeMode = false;
    ResetRunStats();
    if (runSaveEvent)
    {
        runSaveEvent->SetBool("run_saved", false);
        gameeventmanager->FireEvent(runSaveEvent);
    }
    if (runUploadEvent)
    {
        runUploadEvent->SetBool("run_posted", false);
        runUploadEvent->SetString("web_msg", "");
        gameeventmanager->FireEvent(runUploadEvent);
    }
    if (timerStartEvent)
    {
        timerStartEvent->SetInt("ent", entindex());
        timerStartEvent->SetBool("is_running", false);
        gameeventmanager->FireEvent(timerStartEvent);
    }
    // Linear/etc map
    g_Timer->DispatchMapInfo();

    RegisterThinkContext("THINK_EVERY_TICK");
    RegisterThinkContext("CURTIME");
    RegisterThinkContext("THINK_AVERAGE_STATS");
    RegisterThinkContext("CURTIME_FOR_START");
    RegisterThinkContext("TWEEN");
    SetContextThink(&CMomentumPlayer::UpdateRunStats, gpGlobals->curtime + gpGlobals->interval_per_tick,
                    "THINK_EVERY_TICK");
    SetContextThink(&CMomentumPlayer::CheckForBhop, gpGlobals->curtime, "CURTIME");
    SetContextThink(&CMomentumPlayer::CalculateAverageStats, gpGlobals->curtime + AVERAGE_STATS_INTERVAL,
                    "THINK_AVERAGE_STATS");
    SetContextThink(&CMomentumPlayer::LimitSpeedInStartZone, gpGlobals->curtime, "CURTIME_FOR_START");
    SetContextThink(&CMomentumPlayer::TweenSlowdownPlayer, gpGlobals->curtime, "TWEEN");

    SetNextThink(gpGlobals->curtime);
    DevLog("Finished spawn!\n");
}
示例#13
0
	double interpolate( util::matrix_t<double> &data,
		util::matrix_t<double>  &par,
		double I, double T, int idx, bool quiet )
	{
		MatDoub tempirr;
		std::vector<double> parvals;
		std::vector<sp_point> pts, hull;

		double maxz = -1e99;
		double tmin = 1e99;
		double tmax = -1e99;
		double imin = 1e99;
		double imax = -1e99;
		double dist = 1e99;
		int idist = -1;
		for( size_t i=0;i<data.nrows();i++ )
		{
			double z = par(i,idx);
			if ( !std::isfinite( z ) )
				continue;

			double temp = data(i,TC);//x value
			double irr = data(i,IRR);//y value

			if ( temp < tmin ) tmin = temp;
			if ( temp > tmax ) tmax = temp;
			if ( irr < imin ) imin = irr;
			if ( irr > imax ) imax = irr;

			double d = sqrt( (irr-I)*(irr-I) + (temp-T)*(temp-T) );
			if ( d < dist )
			{
				dist = d;
				idist = (int)i;
			}
			
			std::vector<double> it(2,0.0);
			it[0] = temp; it[1] = irr;
			tempirr.push_back( it );

			parvals.push_back( z );

			if ( z > maxz ) maxz = z;

			pts.push_back( sp_point( temp, irr, z ) );
		}

		Toolbox::convex_hull( pts, hull );
		if ( Toolbox::pointInPolygon( hull, sp_point(T, I, 0.0) ) )
		{
			// scale values based on max - helps GM interp routine
			for( size_t i=0;i<parvals.size();i++)
				parvals[i] /= maxz;

			Powvargram vgram( tempirr, parvals, 1.75, 0. );
			GaussMarkov gm( tempirr, parvals, vgram );

			// test the fit against the data
			double err_fit = 0.;
			for( size_t i=0;i<parvals.size();i++ )
			{
				double zref = parvals[i];
				double zfit = gm.interp( tempirr[i] );
				double dz = zref - zfit;
				err_fit += dz*dz;
			}
			err_fit = sqrt(err_fit);
			if ( err_fit > 0.01 )
			{
				log(	util::format("interpolation function for iec61853 parameter '%s' at I=%lg T=%lg is poor: %lg RMS",
							parnames[idx], I, T, err_fit ),

					SSC_WARNING );
			}

			std::vector<double> q(2,0.0);
				q[0] = T;
				q[1] = I;
			
			// now interpolate and return the value
			return gm.interp( q ) * maxz;
		}
		else
		{
			// if we're pretty close, return the nearest known value
			if ( dist < 30. )
			{
				
				if ( !quiet )
					log( util::format("query point (%lg, %lg) is outside convex hull of data but close... returning nearest value from data table at (%lg, %lg)=%lg",
						T, I, data(idist,TC), data(idist,IRR), par(idist,idx) ),

						SSC_WARNING );

				return par(idist,idx);
			}

				

			// fall back to the 5 parameter model's auxiliary equations 
			// to estimate the parameter values outside the convex hull

			int idx_stc = -1;
			for( size_t i=0;i<data.nrows();i++)
				if ( data(i,IRR) == 1000.0
					&& data(i,TC) == 25.0 )
					idx_stc = (int)i;

			if ( idx_stc < 0 )
				throw general_error("STC conditions required to be supplied in the temperature/irradiance data");



			double value = par(idist,idx);;
			if ( idx == A )
			{
				double a_nearest = par( idist, A );
				double T_nearest = data( idist, TC );
				double a_est = a_nearest * T/T_nearest;
				value = a_est;
			}
			else if ( idx == IL )
			{
				double IL_nearest = par( idist, IL );
				double I_nearest = data(idist, IRR );
				double IL_est = IL_nearest * I/I_nearest;
				value = IL_est;
			}/*
			else if ( idx == IO )
			{
#define Tc_ref 298.15
#define Eg_ref 1.12
#define KB 8.618e-5

				double IO_stc = par(idx_stc,IO);
				double TK = T+273.15;
				double EG = Eg_ref * (1-0.0002677*(TK-Tc_ref));
				double IO_oper =  IO_stc * pow(TK/Tc_ref, 3) * exp( 1/KB*(Eg_ref/Tc_ref - EG/TK) );
				value = IO_oper;	
			}*/
			else if ( idx == RSH )
			{
				double RSH_nearest = par( idist, RSH );
				double I_nearest = data(idist, IRR );
				double RSH_est = RSH_nearest * I_nearest/I;
				value = RSH_est;
			}
			
			if ( !quiet )
				log( util::format("query point (%lg, %lg) is too far out of convex hull of data (dist=%lg)... estimating value from 5 parameter modele at (%lg, %lg)=%lg",
					T, I, dist, data(idist,TC), data(idist,IRR), value ),

					SSC_WARNING );

			return value;
		}
	}
	void Create3x1Label3Model(GM& gm_return)
	{
		size_t numberOfNodes=3, numberOflabels=3;
		typename GM::SpaceType space(numberOfNodes,numberOflabels);
	    GM gm(space);

	    // single site factors
        opengm::ExplicitFunction<double> f1(&numberOflabels,&numberOflabels+1, 0.0);
        typename GM::IndexType j;
	    { j=0;
          f1(0) = 1.0;
	      f1(1) = 2.0;
	      f1(2) = 3.0;
	      typename GM::FunctionIdentifier fId = gm.addFunction(f1);
	      gm.addFactor(fId,&j, &j+1);}

	    { j=1;
          f1(0) = 4.0;
	      f1(1) = 5.0;
	      f1(2) = 6.0;
	      typename GM::FunctionIdentifier fId = gm.addFunction(f1);
	      gm.addFactor(fId,&j, &j+1);}

	    { j=2;
          f1(0) = 7.0;
	      f1(1) = 8.0;
	      f1(2) = 9.0;
	      typename GM::FunctionIdentifier fId = gm.addFunction(f1);
	      gm.addFactor(fId,&j, &j+1);}

	    //pw factors
        size_t shape[] = {numberOflabels,numberOflabels};
        opengm::ExplicitFunction<double> f2(shape,shape+2, 0.0);

	    { size_t vi[] = {0,1};
	      f2(0,0) = 5.0;
	      f2(0,1) = 0.0;
	      f2(0,2) = 1.0;

	      f2(1,0) = 5.0;
	      f2(1,1) = 0.0;
	      f2(1,2) = 1.0;

	      f2(2,0) = 1.0;
	      f2(2,1) = 0.0;
	      f2(2,2) = 10.0;
	      typename GM::FunctionIdentifier fId = gm.addFunction(f2);
	      gm.addFactor(fId,vi,vi+2);}

	    { size_t vi[] = {1,2};
	      f2(0,0) = 5.0;
	      f2(0,1) = 5.0;
	      f2(0,2) = 1.0;

	      f2(1,0) = 0.0;
	      f2(1,1) = 0.0;
	      f2(1,2) = 0.0;

	      f2(2,0) = 1.0;
	      f2(2,1) = 1.0;
	      f2(2,2) = 10.0;
	      typename GM::FunctionIdentifier fId = gm.addFunction(f2);
	      gm.addFactor(fId,vi,vi+2);}

	    gm_return=gm;
	};
示例#15
0
bool CMomentumGameMovement::CheckJumpButton()
{

    if (player->pl.deadflag)
    {
        mv->m_nOldButtons |= IN_JUMP;	// don't jump again until released
        return false;
    }

    // See if we are waterjumping.  If so, decrement count and return.
    if (player->m_flWaterJumpTime)
    {
        player->m_flWaterJumpTime -= gpGlobals->frametime;
        if (player->m_flWaterJumpTime < 0)
            player->m_flWaterJumpTime = 0;

        return false;
    }

    // If we are in the water most of the way...
    if (player->GetWaterLevel() >= 2)
    {
        // swimming, not jumping
        SetGroundEntity(NULL);

        if (player->GetWaterType() == CONTENTS_WATER)    // We move up a certain amount
            mv->m_vecVelocity[2] = 100;
        else if (player->GetWaterType() == CONTENTS_SLIME)
            mv->m_vecVelocity[2] = 80;

        // play swiming sound
        if (player->m_flSwimSoundTime <= 0)
        {
            // Don't play sound again for 1 second
            player->m_flSwimSoundTime = 1000;
            PlaySwimSound();
        }

        return false;
    }

    // No more effect
    if (player->GetGroundEntity() == NULL)
    {
        mv->m_nOldButtons |= IN_JUMP;
        return false;		// in air, so no effect
    }

    //AUTOBHOP---
    //only run this code if autobhop is disabled
    if (!player->HasAutoBhop())
    {
        if (mv->m_nOldButtons & IN_JUMP)
            return false;		// don't pogo stick
    }
    
    // In the air now.
    SetGroundEntity(NULL);

    player->PlayStepSound((Vector &) mv->GetAbsOrigin(), player->m_pSurfaceData, 1.0, true);

    //MoveHelper()->PlayerSetAnimation( PLAYER_JUMP );
    //player->DoAnimationEvent(PLAYERANIMEVENT_JUMP);

    float flGroundFactor = 1.0f;
    if (player->m_pSurfaceData)
    {
        flGroundFactor = player->m_pSurfaceData->game.jumpFactor;
    }

    // if we weren't ducking, bots and hostages do a crouchjump programatically
    if ((!player || player->IsBot()) && !(mv->m_nButtons & IN_DUCK))
    {
        player->m_duckUntilOnGround = true;
        FinishDuck();
    }

    // Acclerate upward
    // If we are ducking...
    float startz = mv->m_vecVelocity[2];
    if ((player->m_Local.m_bDucking) || (player->GetFlags() & FL_DUCKING))
    {
        mv->m_vecVelocity[2] = flGroundFactor * sqrt(2 * 800 * 57.0);  // 2 * gravity * height
    }
    else
    {
        mv->m_vecVelocity[2] += flGroundFactor * sqrt(2 * 800 * 57.0);  // 2 * gravity * height
    }

    //stamina stuff (scroll gamemode only)
    ConVarRef gm("mom_gamemode");
    if (gm.GetInt() == MOMGM_SCROLL)
    {
        if (player->m_flStamina > 0)
        {
            float flRatio;

            flRatio = (STAMINA_MAX - ((player->m_flStamina / 1000.0) * STAMINA_RECOVER_RATE)) / STAMINA_MAX;

            mv->m_vecVelocity[2] *= flRatio;
        }

        player->m_flStamina = (STAMINA_COST_JUMP / STAMINA_RECOVER_RATE) * 1000.0;
    }

    FinishGravity();

    mv->m_outWishVel.z += mv->m_vecVelocity[2] - startz;
    mv->m_outStepHeight += 0.1f;

    // Flag that we jumped.
    mv->m_nOldButtons |= IN_JUMP;	// don't jump again until released
    return true;

}
示例#16
0
文件: warthog.cpp 项目: fanioz/ddh
int 
main(int argc, char** argv)
{
	// parse arguments
	warthog::util::param valid_args[] = 
	{
		{"scen",  required_argument, 0, 0},
		{"alg",  required_argument, 0, 1},
		{"gen", required_argument, 0, 3},
		{"help", no_argument, &print_help, 1},
		{"checkopt",  no_argument, &checkopt, 1},
		{"verbose",  no_argument, &verbose, 1},
		{"wgm",  no_argument, &wgm, 1}
	};

	warthog::util::cfg cfg;
	cfg.parse_args(argc, argv, valid_args);

    if(print_help)
    {
		help();
        exit(0);
    }

	std::string sfile = cfg.get_param_value("scen");
	std::string alg = cfg.get_param_value("alg");
	std::string gen = cfg.get_param_value("gen");

    // generate scenarios
	if(gen != "")
	{
		warthog::scenario_manager sm;
		warthog::gridmap gm(gen.c_str());
		sm.generate_experiments(&gm, 1000) ;
		sm.write_scenario(std::cout);
        exit(0);
	}

	// run experiments
	if(alg == "" || sfile == "")
	{
        std::cerr << "Err. Must specify a scenario file and search algorithm. Try --help for options.\n";
		exit(0);
	}

	warthog::scenario_manager scenmgr;
	scenmgr.load_scenario(sfile.c_str());

	if(alg == "jps+")
	{
		run_jpsplus(scenmgr);
	}

	if(alg == "jps2")
	{
		run_jps2(scenmgr);
	}

	if(alg == "jps2+")
	{
		run_jps2plus(scenmgr);
	}

    if(alg == "jps")
    {
        if(wgm)
        {
            run_jps_wgm(scenmgr);
        }
        else
        {
            run_jps(scenmgr);
        }
    }

	if(alg == "astar")
	{
        if(wgm) 
        { 
            run_wgm_astar(scenmgr); 
        }
        else 
        { 
            run_astar(scenmgr); 
        }
	}

	if(alg == "sssp")
	{
        if(wgm) 
        { 
            run_wgm_sssp(scenmgr); 
        }
        else 
        { 
            //run_astar(scenmgr); 
        }
	}
}