void GoalDetector::execute()
{
  getGoalPercept().reset();

  //if there is no field percept, then, there is also no goal ?!
  /*
  if(!theFieldPercept.isValid())
  {
    return;
  }
  */

  // estimate the horizon
  Vector2<double> p1(getArtificialHorizon().begin());
  Vector2<double> p2(getArtificialHorizon().end());
  int heightOfHorizon = (int)((p1.y + p2.y) * 0.5 + 0.5);

  // image over the horizon
  if(heightOfHorizon > (int)getImage().cameraInfo.resolutionHeight-10) return;

  // clamp the scanline
  p1.y = Math::clamp((int)p1.y, 10, (int)getImage().cameraInfo.resolutionHeight-10);
  p2.y = Math::clamp((int)p2.y, 10, (int)getImage().cameraInfo.resolutionHeight-10);


  // calculate the post candidates along of the horizon
  Candidate candidates[maxNumberOfCandidates];
  int numberOfCandidates = scanForCandidates(p1, p2, candidates);
  
  // fallback: try to scan along the center of the image
  if(numberOfCandidates == 0)
  {
    Vector2<double> c1(0,getImage().cameraInfo.getOpticalCenterY());
    Vector2<double> c2(getImage().cameraInfo.resolutionWidth-1,getImage().cameraInfo.getOpticalCenterY());
    numberOfCandidates = scanForCandidates(c1, c2, candidates);
  }//end if

  // try once again...
  if(numberOfCandidates == 0)
  {
    Vector2<double> c1(0,getImage().cameraInfo.resolutionHeight/3);
    Vector2<double> c2(getImage().cameraInfo.resolutionWidth-1,getImage().cameraInfo.resolutionHeight/3);
    numberOfCandidates = scanForCandidates(c1, c2, candidates);
  }//end if


  // estimate the post base points
  vector<GoalPercept::GoalPost> postvector;
  estimatePostsByScanlines(candidates, numberOfCandidates, postvector);
  //estimatePostsByBlobs(candidates, numberOfCandidates, postvector);


  if(postvector.empty()) return;

  // sort the posts by height in the image
  // the first is the biggest
  GoalPercept::GoalPost post; // only for comparison
  sort(postvector.begin(), postvector.end(), post); 



  // minimal height (in px) of an accepted goal post
  int minimalHeightOfAGoalPost = 20;
  int numberOfPostsFound = 0;

  // we are searching for two goal posts
  GoalPercept::GoalPost postOne;
  GoalPercept::GoalPost postTwo;

  int distToBottomImage = getImage().cameraInfo.resolutionHeight - max(postOne.basePoint.y, postTwo.basePoint.y) - 1;
  // look max 5 pixel down
  Vector2<int> extraBase(0, min(distToBottomImage,5));

  // if the longest post is to short
  if(postvector.begin()->seenHeight < minimalHeightOfAGoalPost)
  {
    return;
  }


  // index of the first found post
  unsigned int idxFirst = 0;
  // search for the first goal post candidate
  for(idxFirst = 0; idxFirst < postvector.size(); idxFirst++)
  {
    if(postvector[idxFirst].seenHeight >= minimalHeightOfAGoalPost)
       // consider the field percept ONLY if it is valid
       //&& theFieldPercept.getLargestValidPoly(getCameraMatrix().horizon).isInside(postvector[idxFirst].basePoint + extraBase))
    {
      numberOfPostsFound = 1;
      break;
    }
  }//end for


  // if a post were found search for the second one
  if(numberOfPostsFound > 0)
  {
    // at least one post was seen
    postOne = postvector[idxFirst];
    idxFirst++;

    for(unsigned int i = idxFirst; i < postvector.size(); i++)
    {
      postTwo = postvector[i];

      if( abs(postTwo.basePoint.x - postOne.basePoint.x) > 50 &&
          postTwo.seenHeight > minimalHeightOfAGoalPost &&
          postOne.color == postTwo.color) //&& // posts have the same color
          // consider the field percept ONLY if it is valid
          //theFieldPercept.getLargestValidPoly(getCameraMatrix().horizon).isInside(postvector[i].basePoint + extraBase))
      {
        numberOfPostsFound = 2;
        break;
      }//end if
    }//end for
  }//end if first found



  if(numberOfPostsFound > 1)
  {
    // sort: which one is left or right
    if(postOne.basePoint.x > postTwo.basePoint.x)
    {
      postOne.type = GoalPercept::GoalPost::rightPost;
      postTwo.type = GoalPercept::GoalPost::leftPost;
    }else
    {
      postOne.type = GoalPercept::GoalPost::leftPost;
      postTwo.type = GoalPercept::GoalPost::rightPost;
    }


    //TODO: handle the case if the projection is not possible
    // position on the ground is not reliable if the post cannot be projected
    postOne.positionReliable =
      CameraGeometry::imagePixelToFieldCoord(
        getCameraMatrix(),
        getImage().cameraInfo,
        postOne.basePoint.x, postOne.basePoint.y, 0.0,
        postOne.position);

    //TODO: handle the case if the projection is not possible
    // position on the ground is not reliable if the post cannot be projected
    postTwo.positionReliable = 
      CameraGeometry::imagePixelToFieldCoord(
        getCameraMatrix(),
        getImage().cameraInfo,
        postTwo.basePoint.x, postTwo.basePoint.y, 0.0,
        postTwo.position);

    //TODO: try to calculate the position by the top of the post

    // translate by the post radius
    postOne.position.normalize(postOne.position.abs() + getFieldInfo().goalpostRadius);
    postTwo.position.normalize(postTwo.position.abs() + getFieldInfo().goalpostRadius);

    postOne.positionReliable = postOne.positionReliable && checkIfPostReliable(postOne.basePoint);
    postTwo.positionReliable = postTwo.positionReliable && checkIfPostReliable(postTwo.basePoint);

    getGoalPercept().add(postOne);
    getGoalPercept().add(postTwo);
  }
  else if(numberOfPostsFound > 0) // only one post found
  {
    //TODO: handle the case if the projection is not possible
    postOne.positionReliable = 
      CameraGeometry::imagePixelToFieldCoord(
        getCameraMatrix(),
        getImage().cameraInfo,
        postOne.basePoint.x, postOne.basePoint.y, 0.0,
        postOne.position);

    postOne.positionReliable = postOne.positionReliable && checkIfPostReliable(postOne.basePoint);

    postOne.type = GoalPercept::GoalPost::unknownPost;
    getGoalPercept().add(postOne);
  }//end else




  /*************************************************/
  // calculate the centroid
  // at least one post was seen
  // TODO: clean it up (calculation of the centroid)
  if(getGoalPercept().getNumberOfSeenPosts() > 0)
  {

    //Vector2<double> centroid;
    //double mainAxisAngle = -getMajorAxis( goalColor, centroid);

    Vector2<double> centroid = getGoalPercept().getPost(0).basePoint -
      Vector2<double>(0.0, getGoalPercept().getPost(0).seenHeight*0.5); 

    if(getGoalPercept().getNumberOfSeenPosts() > 1)
    {
      centroid += getGoalPercept().getPost(1).basePoint -
            Vector2<double>(0.0, getGoalPercept().getPost(1).seenHeight*0.5);

      centroid /= 2.0;
    }//end if

    Vector2<double> angles = CameraGeometry::angleToPointInImage(
            getCameraMatrix(), 
            getImage().cameraInfo,
            (int)centroid.x, 
            (int)centroid.y);

    getGoalPercept().angleToSeenGoal = angles.x;

    getGoalPercept().goalCentroid = CameraGeometry::imagePixelToWorld(
            getCameraMatrix(), 
            getImage().cameraInfo,
            centroid.x,
            centroid.y,
            3000.0);

    DEBUG_REQUEST("ImageProcessor:GoalDetector:mark_goal",
      CIRCLE_PX(ColorClasses::red, (int)centroid.x, (int)centroid.y, 5);
    );
Esempio n. 2
0
int tc_libcxx_containers_unord_map_swap_member(void)
{
    {
        typedef test_hash<std::hash<int> > Hash;
        typedef test_compare<std::equal_to<int> > Compare;
        typedef test_allocator<std::pair<const int, std::string> > Alloc;
        typedef std::unordered_map<int, std::string, Hash, Compare, Alloc> C;
        C c1(0, Hash(1), Compare(1), Alloc(1, 1));
        C c2(0, Hash(2), Compare(2), Alloc(1, 2));
        c2.max_load_factor(2);
        c1.swap(c2);

        LIBCPP_ASSERT(c1.bucket_count() == 0);
        TC_ASSERT_EXPR(c1.size() == 0);
        TC_ASSERT_EXPR(c1.hash_function() == Hash(2));
        TC_ASSERT_EXPR(c1.key_eq() == Compare(2));
        TC_ASSERT_EXPR(c1.get_allocator().get_id() == 1);
        TC_ASSERT_EXPR(static_cast<std::size_t>(std::distance(c1.begin(), c1.end())) == c1.size());
        TC_ASSERT_EXPR(static_cast<std::size_t>(std::distance(c1.cbegin(), c1.cend())) == c1.size());
        TC_ASSERT_EXPR(c1.max_load_factor() == 2);

        LIBCPP_ASSERT(c2.bucket_count() == 0);
        TC_ASSERT_EXPR(c2.size() == 0);
        TC_ASSERT_EXPR(c2.hash_function() == Hash(1));
        TC_ASSERT_EXPR(c2.key_eq() == Compare(1));
        TC_ASSERT_EXPR(c2.get_allocator().get_id() == 2);
        TC_ASSERT_EXPR(static_cast<std::size_t>(std::distance(c2.begin(), c2.end())) == c2.size());
        TC_ASSERT_EXPR(static_cast<std::size_t>(std::distance(c2.cbegin(), c2.cend())) == c2.size());
        TC_ASSERT_EXPR(c2.max_load_factor() == 1);
    }
    {
        typedef test_hash<std::hash<int> > Hash;
        typedef test_compare<std::equal_to<int> > Compare;
        typedef test_allocator<std::pair<const int, std::string> > Alloc;
        typedef std::unordered_map<int, std::string, Hash, Compare, Alloc> C;
        typedef std::pair<int, std::string> P;
        P a2[] =
        {
            P(10, "ten"),
            P(20, "twenty"),
            P(30, "thirty"),
            P(40, "forty"),
            P(50, "fifty"),
            P(60, "sixty"),
            P(70, "seventy"),
            P(80, "eighty"),
        };
        C c1(0, Hash(1), Compare(1), Alloc(1, 1));
        C c2(std::begin(a2), std::end(a2), 0, Hash(2), Compare(2), Alloc(1, 2));
        c2.max_load_factor(2);
        c1.swap(c2);

        TC_ASSERT_EXPR(c1.bucket_count() >= 8);
        TC_ASSERT_EXPR(c1.size() == 8);
        TC_ASSERT_EXPR(c1.at(10) == "ten");
        TC_ASSERT_EXPR(c1.at(20) == "twenty");
        TC_ASSERT_EXPR(c1.at(30) == "thirty");
        TC_ASSERT_EXPR(c1.at(40) == "forty");
        TC_ASSERT_EXPR(c1.at(50) == "fifty");
        TC_ASSERT_EXPR(c1.at(60) == "sixty");
        TC_ASSERT_EXPR(c1.at(70) == "seventy");
        TC_ASSERT_EXPR(c1.at(80) == "eighty");
        TC_ASSERT_EXPR(c1.hash_function() == Hash(2));
        TC_ASSERT_EXPR(c1.key_eq() == Compare(2));
        TC_ASSERT_EXPR(c1.get_allocator().get_id() == 1);
        TC_ASSERT_EXPR(static_cast<std::size_t>(std::distance(c1.begin(), c1.end())) == c1.size());
        TC_ASSERT_EXPR(static_cast<std::size_t>(std::distance(c1.cbegin(), c1.cend())) == c1.size());
        TC_ASSERT_EXPR(c1.max_load_factor() == 2);

        LIBCPP_ASSERT(c2.bucket_count() == 0);
        TC_ASSERT_EXPR(c2.size() == 0);
        TC_ASSERT_EXPR(c2.hash_function() == Hash(1));
        TC_ASSERT_EXPR(c2.key_eq() == Compare(1));
        TC_ASSERT_EXPR(c2.get_allocator().get_id() == 2);
        TC_ASSERT_EXPR(static_cast<std::size_t>(std::distance(c2.begin(), c2.end())) == c2.size());
        TC_ASSERT_EXPR(static_cast<std::size_t>(std::distance(c2.cbegin(), c2.cend())) == c2.size());
        TC_ASSERT_EXPR(c2.max_load_factor() == 1);
    }
    {
        typedef test_hash<std::hash<int> > Hash;
        typedef test_compare<std::equal_to<int> > Compare;
        typedef test_allocator<std::pair<const int, std::string> > Alloc;
        typedef std::unordered_map<int, std::string, Hash, Compare, Alloc> C;
        typedef std::pair<int, std::string> P;
        P a1[] =
        {
            P(1, "one"),
            P(2, "two"),
            P(3, "three"),
            P(4, "four"),
            P(1, "four"),
            P(2, "four"),
        };
        C c1(std::begin(a1), std::end(a1), 0, Hash(1), Compare(1), Alloc(1, 1));
        C c2(0, Hash(2), Compare(2), Alloc(1, 2));
        c2.max_load_factor(2);
        c1.swap(c2);

        LIBCPP_ASSERT(c1.bucket_count() == 0);
        TC_ASSERT_EXPR(c1.size() == 0);
        TC_ASSERT_EXPR(c1.hash_function() == Hash(2));
        TC_ASSERT_EXPR(c1.key_eq() == Compare(2));
        TC_ASSERT_EXPR(c1.get_allocator().get_id() == 1);
        TC_ASSERT_EXPR(static_cast<std::size_t>(std::distance(c1.begin(), c1.end())) == c1.size());
        TC_ASSERT_EXPR(static_cast<std::size_t>(std::distance(c1.cbegin(), c1.cend())) == c1.size());
        TC_ASSERT_EXPR(c1.max_load_factor() == 2);

        TC_ASSERT_EXPR(c2.bucket_count() >= 4);
        TC_ASSERT_EXPR(c2.size() == 4);
        TC_ASSERT_EXPR(c2.at(1) == "one");
        TC_ASSERT_EXPR(c2.at(2) == "two");
        TC_ASSERT_EXPR(c2.at(3) == "three");
        TC_ASSERT_EXPR(c2.at(4) == "four");
        TC_ASSERT_EXPR(c2.hash_function() == Hash(1));
        TC_ASSERT_EXPR(c2.key_eq() == Compare(1));
        TC_ASSERT_EXPR(c2.get_allocator().get_id() == 2);
        TC_ASSERT_EXPR(static_cast<std::size_t>(std::distance(c2.begin(), c2.end())) == c2.size());
        TC_ASSERT_EXPR(static_cast<std::size_t>(std::distance(c2.cbegin(), c2.cend())) == c2.size());
        TC_ASSERT_EXPR(c2.max_load_factor() == 1);
    }
    {
        typedef test_hash<std::hash<int> > Hash;
        typedef test_compare<std::equal_to<int> > Compare;
        typedef test_allocator<std::pair<const int, std::string> > Alloc;
        typedef std::unordered_map<int, std::string, Hash, Compare, Alloc> C;
        typedef std::pair<int, std::string> P;
        P a1[] =
        {
            P(1, "one"),
            P(2, "two"),
            P(3, "three"),
            P(4, "four"),
            P(1, "four"),
            P(2, "four"),
        };
        P a2[] =
        {
            P(10, "ten"),
            P(20, "twenty"),
            P(30, "thirty"),
            P(40, "forty"),
            P(50, "fifty"),
            P(60, "sixty"),
            P(70, "seventy"),
            P(80, "eighty"),
        };
        C c1(std::begin(a1), std::end(a1), 0, Hash(1), Compare(1), Alloc(1, 1));
        C c2(std::begin(a2), std::end(a2), 0, Hash(2), Compare(2), Alloc(1, 2));
        c2.max_load_factor(2);
        c1.swap(c2);

        TC_ASSERT_EXPR(c1.bucket_count() >= 8);
        TC_ASSERT_EXPR(c1.size() == 8);
        TC_ASSERT_EXPR(c1.at(10) == "ten");
        TC_ASSERT_EXPR(c1.at(20) == "twenty");
        TC_ASSERT_EXPR(c1.at(30) == "thirty");
        TC_ASSERT_EXPR(c1.at(40) == "forty");
        TC_ASSERT_EXPR(c1.at(50) == "fifty");
        TC_ASSERT_EXPR(c1.at(60) == "sixty");
        TC_ASSERT_EXPR(c1.at(70) == "seventy");
        TC_ASSERT_EXPR(c1.at(80) == "eighty");
        TC_ASSERT_EXPR(c1.hash_function() == Hash(2));
        TC_ASSERT_EXPR(c1.key_eq() == Compare(2));
        TC_ASSERT_EXPR(c1.get_allocator().get_id() == 1);
        TC_ASSERT_EXPR(static_cast<std::size_t>(std::distance(c1.begin(), c1.end())) == c1.size());
        TC_ASSERT_EXPR(static_cast<std::size_t>(std::distance(c1.cbegin(), c1.cend())) == c1.size());
        TC_ASSERT_EXPR(c1.max_load_factor() == 2);

        TC_ASSERT_EXPR(c2.bucket_count() >= 4);
        TC_ASSERT_EXPR(c2.size() == 4);
        TC_ASSERT_EXPR(c2.at(1) == "one");
        TC_ASSERT_EXPR(c2.at(2) == "two");
        TC_ASSERT_EXPR(c2.at(3) == "three");
        TC_ASSERT_EXPR(c2.at(4) == "four");
        TC_ASSERT_EXPR(c2.hash_function() == Hash(1));
        TC_ASSERT_EXPR(c2.key_eq() == Compare(1));
        TC_ASSERT_EXPR(c2.get_allocator().get_id() == 2);
        TC_ASSERT_EXPR(static_cast<std::size_t>(std::distance(c2.begin(), c2.end())) == c2.size());
        TC_ASSERT_EXPR(static_cast<std::size_t>(std::distance(c2.cbegin(), c2.cend())) == c2.size());
        TC_ASSERT_EXPR(c2.max_load_factor() == 1);
    }

    {
        typedef test_hash<std::hash<int> > Hash;
        typedef test_compare<std::equal_to<int> > Compare;
        typedef other_allocator<std::pair<const int, std::string> > Alloc;
        typedef std::unordered_map<int, std::string, Hash, Compare, Alloc> C;
        C c1(0, Hash(1), Compare(1), Alloc(1));
        C c2(0, Hash(2), Compare(2), Alloc(2));
        c2.max_load_factor(2);
        c1.swap(c2);

        LIBCPP_ASSERT(c1.bucket_count() == 0);
        TC_ASSERT_EXPR(c1.size() == 0);
        TC_ASSERT_EXPR(c1.hash_function() == Hash(2));
        TC_ASSERT_EXPR(c1.key_eq() == Compare(2));
        TC_ASSERT_EXPR(c1.get_allocator() == Alloc(2));
        TC_ASSERT_EXPR(static_cast<std::size_t>(std::distance(c1.begin(), c1.end())) == c1.size());
        TC_ASSERT_EXPR(static_cast<std::size_t>(std::distance(c1.cbegin(), c1.cend())) == c1.size());
        TC_ASSERT_EXPR(c1.max_load_factor() == 2);

        LIBCPP_ASSERT(c2.bucket_count() == 0);
        TC_ASSERT_EXPR(c2.size() == 0);
        TC_ASSERT_EXPR(c2.hash_function() == Hash(1));
        TC_ASSERT_EXPR(c2.key_eq() == Compare(1));
        TC_ASSERT_EXPR(c2.get_allocator() == Alloc(1));
        TC_ASSERT_EXPR(static_cast<std::size_t>(std::distance(c2.begin(), c2.end())) == c2.size());
        TC_ASSERT_EXPR(static_cast<std::size_t>(std::distance(c2.cbegin(), c2.cend())) == c2.size());
        TC_ASSERT_EXPR(c2.max_load_factor() == 1);
    }
    {
        typedef test_hash<std::hash<int> > Hash;
        typedef test_compare<std::equal_to<int> > Compare;
        typedef other_allocator<std::pair<const int, std::string> > Alloc;
        typedef std::unordered_map<int, std::string, Hash, Compare, Alloc> C;
        typedef std::pair<int, std::string> P;
        P a2[] =
        {
            P(10, "ten"),
            P(20, "twenty"),
            P(30, "thirty"),
            P(40, "forty"),
            P(50, "fifty"),
            P(60, "sixty"),
            P(70, "seventy"),
            P(80, "eighty"),
        };
        C c1(0, Hash(1), Compare(1), Alloc(1));
        C c2(std::begin(a2), std::end(a2), 0, Hash(2), Compare(2), Alloc(2));
        c2.max_load_factor(2);
        c1.swap(c2);

        TC_ASSERT_EXPR(c1.bucket_count() >= 8);
        TC_ASSERT_EXPR(c1.size() == 8);
        TC_ASSERT_EXPR(c1.at(10) == "ten");
        TC_ASSERT_EXPR(c1.at(20) == "twenty");
        TC_ASSERT_EXPR(c1.at(30) == "thirty");
        TC_ASSERT_EXPR(c1.at(40) == "forty");
        TC_ASSERT_EXPR(c1.at(50) == "fifty");
        TC_ASSERT_EXPR(c1.at(60) == "sixty");
        TC_ASSERT_EXPR(c1.at(70) == "seventy");
        TC_ASSERT_EXPR(c1.at(80) == "eighty");
        TC_ASSERT_EXPR(c1.hash_function() == Hash(2));
        TC_ASSERT_EXPR(c1.key_eq() == Compare(2));
        TC_ASSERT_EXPR(c1.get_allocator() == Alloc(2));
        TC_ASSERT_EXPR(static_cast<std::size_t>(std::distance(c1.begin(), c1.end())) == c1.size());
        TC_ASSERT_EXPR(static_cast<std::size_t>(std::distance(c1.cbegin(), c1.cend())) == c1.size());
        TC_ASSERT_EXPR(c1.max_load_factor() == 2);

        LIBCPP_ASSERT(c2.bucket_count() == 0);
        TC_ASSERT_EXPR(c2.size() == 0);
        TC_ASSERT_EXPR(c2.hash_function() == Hash(1));
        TC_ASSERT_EXPR(c2.key_eq() == Compare(1));
        TC_ASSERT_EXPR(c2.get_allocator() == Alloc(1));
        TC_ASSERT_EXPR(static_cast<std::size_t>(std::distance(c2.begin(), c2.end())) == c2.size());
        TC_ASSERT_EXPR(static_cast<std::size_t>(std::distance(c2.cbegin(), c2.cend())) == c2.size());
        TC_ASSERT_EXPR(c2.max_load_factor() == 1);
    }
    {
        typedef test_hash<std::hash<int> > Hash;
        typedef test_compare<std::equal_to<int> > Compare;
        typedef other_allocator<std::pair<const int, std::string> > Alloc;
        typedef std::unordered_map<int, std::string, Hash, Compare, Alloc> C;
        typedef std::pair<int, std::string> P;
        P a1[] =
        {
            P(1, "one"),
            P(2, "two"),
            P(3, "three"),
            P(4, "four"),
            P(1, "four"),
            P(2, "four"),
        };
        C c1(std::begin(a1), std::end(a1), 0, Hash(1), Compare(1), Alloc(1));
        C c2(0, Hash(2), Compare(2), Alloc(2));
        c2.max_load_factor(2);
        c1.swap(c2);

        LIBCPP_ASSERT(c1.bucket_count() == 0);
        TC_ASSERT_EXPR(c1.size() == 0);
        TC_ASSERT_EXPR(c1.hash_function() == Hash(2));
        TC_ASSERT_EXPR(c1.key_eq() == Compare(2));
        TC_ASSERT_EXPR(c1.get_allocator() == Alloc(2));
        TC_ASSERT_EXPR(static_cast<std::size_t>(std::distance(c1.begin(), c1.end())) == c1.size());
        TC_ASSERT_EXPR(static_cast<std::size_t>(std::distance(c1.cbegin(), c1.cend())) == c1.size());
        TC_ASSERT_EXPR(c1.max_load_factor() == 2);

        TC_ASSERT_EXPR(c2.bucket_count() >= 4);
        TC_ASSERT_EXPR(c2.size() == 4);
        TC_ASSERT_EXPR(c2.at(1) == "one");
        TC_ASSERT_EXPR(c2.at(2) == "two");
        TC_ASSERT_EXPR(c2.at(3) == "three");
        TC_ASSERT_EXPR(c2.at(4) == "four");
        TC_ASSERT_EXPR(c2.hash_function() == Hash(1));
        TC_ASSERT_EXPR(c2.key_eq() == Compare(1));
        TC_ASSERT_EXPR(c2.get_allocator() == Alloc(1));
        TC_ASSERT_EXPR(static_cast<std::size_t>(std::distance(c2.begin(), c2.end())) == c2.size());
        TC_ASSERT_EXPR(static_cast<std::size_t>(std::distance(c2.cbegin(), c2.cend())) == c2.size());
        TC_ASSERT_EXPR(c2.max_load_factor() == 1);
    }
    {
        typedef test_hash<std::hash<int> > Hash;
        typedef test_compare<std::equal_to<int> > Compare;
        typedef other_allocator<std::pair<const int, std::string> > Alloc;
        typedef std::unordered_map<int, std::string, Hash, Compare, Alloc> C;
        typedef std::pair<int, std::string> P;
        P a1[] =
        {
            P(1, "one"),
            P(2, "two"),
            P(3, "three"),
            P(4, "four"),
            P(1, "four"),
            P(2, "four"),
        };
        P a2[] =
        {
            P(10, "ten"),
            P(20, "twenty"),
            P(30, "thirty"),
            P(40, "forty"),
            P(50, "fifty"),
            P(60, "sixty"),
            P(70, "seventy"),
            P(80, "eighty"),
        };
        C c1(std::begin(a1), std::end(a1), 0, Hash(1), Compare(1), Alloc(1));
        C c2(std::begin(a2), std::end(a2), 0, Hash(2), Compare(2), Alloc(2));
        c2.max_load_factor(2);
        c1.swap(c2);

        TC_ASSERT_EXPR(c1.bucket_count() >= 8);
        TC_ASSERT_EXPR(c1.size() == 8);
        TC_ASSERT_EXPR(c1.at(10) == "ten");
        TC_ASSERT_EXPR(c1.at(20) == "twenty");
        TC_ASSERT_EXPR(c1.at(30) == "thirty");
        TC_ASSERT_EXPR(c1.at(40) == "forty");
        TC_ASSERT_EXPR(c1.at(50) == "fifty");
        TC_ASSERT_EXPR(c1.at(60) == "sixty");
        TC_ASSERT_EXPR(c1.at(70) == "seventy");
        TC_ASSERT_EXPR(c1.at(80) == "eighty");
        TC_ASSERT_EXPR(c1.hash_function() == Hash(2));
        TC_ASSERT_EXPR(c1.key_eq() == Compare(2));
        TC_ASSERT_EXPR(c1.get_allocator() == Alloc(2));
        TC_ASSERT_EXPR(static_cast<std::size_t>(std::distance(c1.begin(), c1.end())) == c1.size());
        TC_ASSERT_EXPR(static_cast<std::size_t>(std::distance(c1.cbegin(), c1.cend())) == c1.size());
        TC_ASSERT_EXPR(c1.max_load_factor() == 2);

        TC_ASSERT_EXPR(c2.bucket_count() >= 4);
        TC_ASSERT_EXPR(c2.size() == 4);
        TC_ASSERT_EXPR(c2.at(1) == "one");
        TC_ASSERT_EXPR(c2.at(2) == "two");
        TC_ASSERT_EXPR(c2.at(3) == "three");
        TC_ASSERT_EXPR(c2.at(4) == "four");
        TC_ASSERT_EXPR(c2.hash_function() == Hash(1));
        TC_ASSERT_EXPR(c2.key_eq() == Compare(1));
        TC_ASSERT_EXPR(c2.get_allocator() == Alloc(1));
        TC_ASSERT_EXPR(static_cast<std::size_t>(std::distance(c2.begin(), c2.end())) == c2.size());
        TC_ASSERT_EXPR(static_cast<std::size_t>(std::distance(c2.cbegin(), c2.cend())) == c2.size());
        TC_ASSERT_EXPR(c2.max_load_factor() == 1);
    }
    TC_SUCCESS_RESULT();
    return 0;
}
Esempio n. 3
0
int main(int argc, char *argv[]) 
{

  Pooma::initialize(argc, argv);
  Pooma::Tester tester(argc, argv);

  Interval<1> n1(1,5);
  Interval<1> n2(4,8);
  Interval<1> n3(10,20);
  Interval<2> a(n1,n2);
  Interval<3> b(n1,n2,n3);

  Range<1> r1(1,5);
  Range<1> r2(4,8,2);
  Range<1> r3(5,9,2);
  Range<1> r4(10,20,5);
  Range<2> ra(r1,r2);
  Range<2> rb(r1,r3);
  Range<3> rc(r1,r2,r3);

  tester.out() << "1: touches(" << a[0] << "," << a[1] << ") ? ";
  tester.out() << touches(a[0], a[1]) << std::endl;
  tester.check( touches(a[0], a[1]) );
  tester.out() << "0: touches(" << a[0] << "," << b[2] << ") ? ";
  tester.out() << touches(a[0], b[2]) << std::endl;
  tester.check( touches(a[0], b[2])==0);
  tester.out() << "1: touches(" << a[0] << "," << ra[0] << ") ? ";
  tester.out() << touches(a[0], ra[0]) << std::endl;
  tester.check(touches(a[0], ra[0]));
  tester.out() << "1: touches(" << ra[0] << "," << ra[1] << ") ? ";
  tester.out() << touches(ra[0], ra[1]) << std::endl;
  tester.check( touches(ra[0], ra[1]));
  tester.out() << "0: touches(" << r2 << "," << r3 << ") ? ";
  tester.out() << touches(r2, r3) << std::endl;
  tester.check( touches(r2, r3)==0);
  tester.out() << "0: touches(" << ra << "," << rb << ") ? ";
  tester.out() << touches(ra, rb) << std::endl;
  tester.check(  touches(ra, rb) ==0);
  tester.out() << "1: touches(" << rc << "," << rc << ") ? ";
  tester.out() << touches(rc, rc) << std::endl;
  tester.check( touches(rc, rc) );
  tester.out() << "------------------------------------" << std::endl;

  tester.check(" touches ", true);

  Interval<1> c1(1,10);
  Interval<1> c2(3,8);
  Interval<1> c3(5,15);
  Interval<2> ca(c1, c1);
  Interval<2> cb(c1, c2);
  Range<1>    cr1(2,20,2);
  Range<1>    cr2(4,16,4);
  Range<1>    cr3(3,15,2);
  Range<1>    cr4(5,15,5);

  tester.out() << "1: contains(" << c1 << "," << c2 << ") ? ";
  tester.out() << contains(c1,c2) << std::endl;
  tester.check(contains(c1,c2));
  tester.out() << "0: contains(" << c2 << "," << c1 << ") ? ";
  tester.out() << contains(c2,c1) << std::endl;
  tester.check(contains(c2,c1)==0);
  tester.out() << "0: contains(" << c1 << "," << c3 << ") ? ";
  tester.out() << contains(c1,c3) << std::endl;
  tester.check(contains(c1,c3)==0);
  tester.out() << "1: contains(" << ca << "," << cb << ") ? ";
  tester.out() << contains(ca,cb) << std::endl;
  tester.check(contains(ca,cb));
  tester.out() << "0: contains(" << cb << "," << ca << ") ? ";
  tester.out() << contains(cb,ca) << std::endl;
  tester.check(contains(cb,ca)==0);
  tester.out() << "1: contains(" << cr1 << "," << cr2 << ") ? ";
  tester.out() << contains(cr1,cr2) << std::endl;
  tester.check( contains(cr1,cr2));
  tester.out() << "0: contains(" << cr1 << "," << cr3 << ") ? ";
  tester.out() << contains(cr1,cr3) << std::endl;
  tester.check(contains(cr1,cr3)==0);
  tester.out() << "1: contains(" << c3 << "," << cr4 << ") ? ";
  tester.out() << contains(c3,cr4) << std::endl;
  tester.check(contains(c3,cr4));
  tester.out() << "0: contains(" << cr4 << "," << c3 << ") ? ";
  tester.out() << contains(cr4,c3) << std::endl;
  tester.check(contains(cr4,c3)==0);
  tester.out() << "------------------------------------" << std::endl;

  Interval<2> s1, s2;
  Range<2>    sr1, sr2;

  split(cb, s1, s2);
  tester.out() << "split(" << cb << ") = " << s1 << " and " << s2 << std::endl;
  tester.check(s1==Interval<2>(Interval<1>(1,5),Interval<1>(3,5)));
  tester.check(s2==Interval<2>(Interval<1>(6,10),Interval<1>(6,8)));

 

  split(rb, sr1, sr2);
  tester.out() << "split(" << rb << ") = " << sr1 << " and " << sr2 << std::endl;
  tester.check(sr1==Range<2>(Range<1>(1,2),Range<1>(5,5,2)));
  tester.check(sr2==Range<2>(Range<1>(3,5),Range<1>(7,9,2)));

  tester.out() << "------------------------------------" << std::endl;

  tester.out() << "intersect(" << cb << "," << ca << ") = ";
  tester.out() << intersect(cb,ca) << std::endl;
  tester.check(intersect(cb,ca)==Interval<2>(Interval<1>(1,10),
					     Interval<1>(3,8)));

  tester.out() << "intersect(" << rb << "," << ra << ") = ";
  tester.out() << intersect(rb,ra) << std::endl;


  Range<1> i1(1,16,3);
  Range<1> i2(17,3,-2);
  tester.out() << "intersect(" << i1 << "," << i2 << ") = ";
  tester.out() << intersect(i1,i2) << std::endl;
  tester.check( intersect(i1,i2) == Range<1>(7,14,6));

  tester.out() << "intersect(" << i2 << "," << i1 << ") = ";
  tester.out() << intersect(i2,i1) << std::endl;
  tester.check( intersect(i2,i1) == Range<1>(13,7,-6));

  tester.out() << "------------------------------------" << std::endl;

  Interval<1> eq1(1,5);
  Range<1> eq2 = -2 * eq1 + 3;
  Range<1> eq3(-8,8,4);
  Range<1> eq4 = 3 * eq1;
  Range<1> eq5 = 2 * eq1;
  Range<1> eq6 = 6 * eq1 + 1;

  tester.out() << "For " << eq1 << " --> " << eq4 << ", then " << eq3 << " --> ";
  tester.out() << equivSubset(eq1,eq4,eq3) << std::endl;

  tester.out() << "For " << eq4 << " --> " << eq6 << ", then " << eq3 << " --> ";
  tester.out() << equivSubset(eq4,eq6,eq3) << std::endl;

  tester.out() << "For " << eq1 << " --> " << eq2 << ", then " << eq3 << " --> ";
  tester.out() << equivSubset(eq1,eq2,eq3) << std::endl;

  tester.out() << "------------------------------------" << std::endl;

  NewDomain3<Interval<1>, Interval<1>, int>::SliceType_t  ba;
  //  tester.out() << "Created initial slice domain ba = " << ba << std::endl;
  ba = NewDomain3<Interval<1>, Interval<1>, int>::combineSlice(ba,eq1,eq1,7);
  tester.out() << "After taking slice, ba = " << ba << std::endl;

  int retval = tester.results("Domain Calc");
  Pooma::finalize();
  return retval;


}
Esempio n. 4
0
int main()
{
    {
        int ab[] = {3, 4, 2, 8, 0, 1, 44, 34, 45, 96, 80, 1, 13, 31, 45};
        int* an = ab + sizeof(ab)/sizeof(ab[0]);
        typedef test_allocator<MoveOnly> A;
        std::deque<MoveOnly, A> c1(A(5));
        for (int* p = ab; p < an; ++p)
            c1.push_back(MoveOnly(*p));
        std::deque<MoveOnly, A> c2(A(5));
        for (int* p = ab; p < an; ++p)
            c2.push_back(MoveOnly(*p));
        std::deque<MoveOnly, A> c3(A(5));
        c3 = std::move(c1);
        assert(c2 == c3);
        assert(c1.size() == 0);
        assert(c3.get_allocator() == A(5));
    }
    {
        int ab[] = {3, 4, 2, 8, 0, 1, 44, 34, 45, 96, 80, 1, 13, 31, 45};
        int* an = ab + sizeof(ab)/sizeof(ab[0]);
        typedef test_allocator<MoveOnly> A;
        std::deque<MoveOnly, A> c1(A(5));
        for (int* p = ab; p < an; ++p)
            c1.push_back(MoveOnly(*p));
        std::deque<MoveOnly, A> c2(A(5));
        for (int* p = ab; p < an; ++p)
            c2.push_back(MoveOnly(*p));
        std::deque<MoveOnly, A> c3(A(6));
        c3 = std::move(c1);
        assert(c2 == c3);
        assert(c1.size() != 0);
        assert(c3.get_allocator() == A(6));
    }
    {
        int ab[] = {3, 4, 2, 8, 0, 1, 44, 34, 45, 96, 80, 1, 13, 31, 45};
        int* an = ab + sizeof(ab)/sizeof(ab[0]);
        typedef other_allocator<MoveOnly> A;
        std::deque<MoveOnly, A> c1(A(5));
        for (int* p = ab; p < an; ++p)
            c1.push_back(MoveOnly(*p));
        std::deque<MoveOnly, A> c2(A(5));
        for (int* p = ab; p < an; ++p)
            c2.push_back(MoveOnly(*p));
        std::deque<MoveOnly, A> c3(A(6));
        c3 = std::move(c1);
        assert(c2 == c3);
        assert(c1.size() == 0);
        assert(c3.get_allocator() == A(5));
    }
    {
        int ab[] = {3, 4, 2, 8, 0, 1, 44, 34, 45, 96, 80, 1, 13, 31, 45};
        int* an = ab + sizeof(ab)/sizeof(ab[0]);
        typedef min_allocator<MoveOnly> A;
        std::deque<MoveOnly, A> c1(A{});
        for (int* p = ab; p < an; ++p)
            c1.push_back(MoveOnly(*p));
        std::deque<MoveOnly, A> c2(A{});
        for (int* p = ab; p < an; ++p)
            c2.push_back(MoveOnly(*p));
        std::deque<MoveOnly, A> c3(A{});
        c3 = std::move(c1);
        assert(c2 == c3);
        assert(c1.size() == 0);
        assert(c3.get_allocator() == A());
    }
}
Esempio n. 5
0
void VariableTestFixture::testSimpleExpression() {
 Datum six(M_INTEGER, 6);
	ConstantVariable c1(six);
 Datum five(M_INTEGER, 5);
	ConstantVariable c2(five);
	
	// boolean expressions
	shared_ptr<ExpressionVariable> e;
	e = shared_ptr<ExpressionVariable>(new ExpressionVariable(&c1, &c2, M_IS_EQUAL));
	CPPUNIT_ASSERT(!e->getValue().getBool());

	e = shared_ptr<ExpressionVariable>(new ExpressionVariable(&c2, &c2, M_IS_EQUAL));
	CPPUNIT_ASSERT(e->getValue().getBool());
	
	e = shared_ptr<ExpressionVariable>(new ExpressionVariable(&c1, &c2, M_IS_NOT_EQUAL));
	CPPUNIT_ASSERT(e->getValue().getBool());
	
	e = shared_ptr<ExpressionVariable>(new ExpressionVariable(&c1, &c1, M_IS_NOT_EQUAL));
	CPPUNIT_ASSERT(!e->getValue().getBool());
	
	e = shared_ptr<ExpressionVariable>(new ExpressionVariable(&c1, &c2, M_IS_GREATER_THAN));
	CPPUNIT_ASSERT(e->getValue().getBool());
	
	e = shared_ptr<ExpressionVariable>(new ExpressionVariable(&c2, &c1, M_IS_GREATER_THAN));
	CPPUNIT_ASSERT(!e->getValue().getBool());
	
	e = shared_ptr<ExpressionVariable>(new ExpressionVariable(&c1, &c1, M_IS_GREATER_THAN));
	CPPUNIT_ASSERT(!e->getValue().getBool());
	
	e = shared_ptr<ExpressionVariable>(new ExpressionVariable(&c1, &c2, M_IS_GREATER_THAN_OR_EQUAL));
	CPPUNIT_ASSERT(e->getValue().getBool());
	
	e = shared_ptr<ExpressionVariable>(new ExpressionVariable(&c2, &c1, M_IS_GREATER_THAN_OR_EQUAL));
	CPPUNIT_ASSERT(!e->getValue().getBool());
	
	e = shared_ptr<ExpressionVariable>(new ExpressionVariable(&c1, &c1, M_IS_GREATER_THAN_OR_EQUAL));
	CPPUNIT_ASSERT(e->getValue().getBool());
	
	e = shared_ptr<ExpressionVariable>(new ExpressionVariable(&c1, &c2, M_IS_LESS_THAN));
	CPPUNIT_ASSERT(!e->getValue().getBool());
	
	e = shared_ptr<ExpressionVariable>(new ExpressionVariable(&c2, &c1, M_IS_LESS_THAN));
	CPPUNIT_ASSERT(e->getValue().getBool());
	
	e = shared_ptr<ExpressionVariable>(new ExpressionVariable(&c1, &c1, M_IS_LESS_THAN));
	CPPUNIT_ASSERT(!e->getValue().getBool());
	
	e = shared_ptr<ExpressionVariable>(new ExpressionVariable(&c1, &c2, M_IS_LESS_THAN_OR_EQUAL));
	CPPUNIT_ASSERT(!e->getValue().getBool());
	
	e = shared_ptr<ExpressionVariable>(new ExpressionVariable(&c2, &c1, M_IS_LESS_THAN_OR_EQUAL));
	CPPUNIT_ASSERT(e->getValue().getBool());
	
	e = shared_ptr<ExpressionVariable>(new ExpressionVariable(&c1, &c1, M_IS_LESS_THAN_OR_EQUAL));
	CPPUNIT_ASSERT(e->getValue().getBool());
	
	// arithmatic expressions
	e = shared_ptr<ExpressionVariable>(new ExpressionVariable(&c1, &c2, M_PLUS));
	CPPUNIT_ASSERT(e->getValue().getInteger() == (long)(six + five));
	
	e = shared_ptr<ExpressionVariable>(new ExpressionVariable(&c1, &c2, M_MINUS));
	CPPUNIT_ASSERT(e->getValue().getInteger() == (long)(six - five));
	
	e = shared_ptr<ExpressionVariable>(new ExpressionVariable(&c1, &c2, M_TIMES));
	CPPUNIT_ASSERT(e->getValue().getFloat() == (float)(six * five));
	
	e = shared_ptr<ExpressionVariable>(new ExpressionVariable(&c1, &c2, M_DIVIDE));
	CPPUNIT_ASSERT(e->getValue().getFloat() == (double)(six / five));
	
	e = shared_ptr<ExpressionVariable>(new ExpressionVariable(&c1, &c2, M_MOD));
	CPPUNIT_ASSERT(e->getValue().getInteger() == (long)(six % five));
	
	e = shared_ptr<ExpressionVariable>(new ExpressionVariable(&c1, &c2, M_INCREMENT));
	CPPUNIT_ASSERT(e->getValue().getInteger() == (long)(six + Datum(M_FLOAT,1)));
	
	e = shared_ptr<ExpressionVariable>(new ExpressionVariable(&c1, &c2, M_DECREMENT));
	CPPUNIT_ASSERT(e->getValue().getInteger() == (long)(six - Datum(M_FLOAT,1)));
	
	e = shared_ptr<ExpressionVariable>(new ExpressionVariable(&c1, NULL, M_INCREMENT));
	CPPUNIT_ASSERT(e->getValue().getInteger() == (long)(six + Datum(M_FLOAT,1)));
	
	e = shared_ptr<ExpressionVariable>(new ExpressionVariable(&c1, NULL, M_DECREMENT));
	CPPUNIT_ASSERT(e->getValue().getInteger() == (long)(six - Datum(M_FLOAT,1)));
	
 Datum seven(M_INTEGER, 0x7);
	ConstantVariable c3(seven);
 Datum eight(M_INTEGER, 0x8);
	ConstantVariable c4(eight);
	
	e = shared_ptr<ExpressionVariable>(new ExpressionVariable(&c3, &c4, M_AND));
	CPPUNIT_ASSERT(e->getValue().getInteger() == (long)(seven && eight));
	
	e = shared_ptr<ExpressionVariable>(new ExpressionVariable(&c3, &c4, M_OR));
	CPPUNIT_ASSERT(e->getValue().getInteger() == (long)(seven || eight));
	
	e = shared_ptr<ExpressionVariable>(new ExpressionVariable(&c3, &c4, M_NOT));
	CPPUNIT_ASSERT(e->getValue().getInteger() == (long)(!seven));
	
	e = shared_ptr<ExpressionVariable>(new ExpressionVariable(&c3, NULL, M_NOT));
	CPPUNIT_ASSERT(e->getValue().getInteger() == (long)(!seven));
	
	e = shared_ptr<ExpressionVariable>(new ExpressionVariable(&c1, &c2, M_UNARY_MINUS));
	CPPUNIT_ASSERT(e->getValue().getInteger() == (long)(six)*-1);
	
	e = shared_ptr<ExpressionVariable>(new ExpressionVariable(&c1, NULL, M_UNARY_MINUS));
	CPPUNIT_ASSERT(e->getValue().getInteger() == (long)(six)*-1);
	
	e = shared_ptr<ExpressionVariable>(new ExpressionVariable(&c1, &c2, M_UNARY_PLUS));
	CPPUNIT_ASSERT(e->getValue().getInteger() == (long)(six));
	
	e = shared_ptr<ExpressionVariable>(new ExpressionVariable(&c1, NULL, M_UNARY_PLUS));
	CPPUNIT_ASSERT(e->getValue().getInteger() == (long)(six));
}
Esempio n. 6
0
int main() {
  ic::Plot::SetHTTStyle();

  std::string dir="/vols/cms04/pjd12/invcmssws/CMSSW_7_1_5/src/HiggsAnalysis/CombinedLimit/exocombcards/";

  std::vector<Scan> scans;
  //  scans.push_back({"higgsCombinefullScan.MultiDimFit.mH125.root", "Observed", 1, nullptr});
  //  scans.push_back({"higgsCombineexpected.MultiDimFit.mH125.root", "Exp. for SM H", 32, nullptr});
//   scans.push_back({"higgsCombinenoBBBScan.MultiDimFit.mH125.root", "no bbb syst.", 38, nullptr});
  scans.push_back({dir+"higgsCombineCombExp.MultiDimFit.mH125.root", "Exp. for SM H", 1, nullptr});
  scans.push_back({dir+"higgsCombineCombObs.MultiDimFit.mH125.root", "Obs. for SM H", 1, nullptr});

  TCanvas c1("canvas","canvas");

  std::vector<TLine *> lines;


  TLegend *leg = new TLegend(0.65,0.75,0.9,0.9,"","brNDC");

  unsigned counter = 0;
  for (auto & sc : scans) {
    TFile f1(sc.file.c_str());
    TTree *t1 = dynamic_cast<TTree*>(f1.Get("limit"));
    double best1 = 0.0;
    TString res;
    sc.gr = new TGraph(ExtractGraph(t1, best1));
    if(counter==1){
      auto x1 = GetCrossings(*(sc.gr), 1.0);
      auto x2 = GetCrossings(*(sc.gr), 3.84);
      lines.push_back(new TLine(x1[0],0,x1[0],1.0));
      lines.back()->SetLineColor(2);
      lines.back()->SetLineWidth(2);
      lines.push_back(new TLine(x2[0],0,x2[0],3.84));
      lines.back()->SetLineColor(2);
      lines.back()->SetLineWidth(2);
    }
    sc.gr->SetLineColor(sc.color);
    sc.gr->SetLineWidth(3);
    sc.gr->Draw(counter ? "LSAME" : "AL");
    TString leg_text = "#splitline{"+sc.label+"}{"+res+"}";
    leg->AddEntry(sc.gr, leg_text, "L");
    counter++;
  }
  // c1.cd();
  // // g1.Print();
  // g1.SetLineColor(1);
  // g1.SetLineWidth(2);
  // // g1.SetMarkerColor(7);
  // g1.Draw("AC");
  scans[0].gr->SetMaximum(9);
  scans[0].gr->SetMinimum(0.);
  scans[0].gr->GetXaxis()->SetRangeUser(0., 0.9);
  scans[0].gr->GetXaxis()->SetTitle("BR_{inv}");
  scans[0].gr->GetXaxis()->SetTitleOffset(1.1);
  scans[0].gr->GetXaxis()->SetNdivisions(1005,true);
  scans[0].gr->GetXaxis()->SetLabelSize(0.05);
  scans[0].gr->GetYaxis()->SetLabelSize(0.05);
  scans[0].gr->GetXaxis()->SetLabelOffset(0.02);
  scans[0].gr->GetYaxis()->SetLabelOffset(0.02);
  scans[0].gr->GetYaxis()->SetTitle("-2 #Delta ln L");
  scans[0].gr->SetLineStyle(2);
  scans[0].gr->SetLineColor(1);
  leg->SetBorderSize(1);
  leg->SetTextFont(42);
  leg->SetTextSize(0.03);
  leg->SetLineColor(1);
  leg->SetLineStyle(1);
  leg->SetLineWidth(1);
  leg->SetFillColor(0);
  leg->SetFillStyle(1001);
  leg->Draw();
  lines.push_back(new TLine(0.,1,0.9,1.0));
  lines.back()->SetLineColor(2);
  lines.push_back(new TLine(0.,3.84,0.9,3.84));
  lines.back()->SetLineColor(2);
  //  for (auto l : lines) l->Draw();

  DrawCMSLogoTest(&c1,"CMS","preliminary",10);

  TLatex lat = TLatex();
  lat.SetNDC();
  lat.SetTextSize(0.04);                                                                                                                                    
  lat.SetTextFont(42);

  TLatex lat2 = TLatex();
  lat2.SetNDC();
  lat2.SetTextSize(0.03);
  lat2.SetTextFont(42);

  lat.DrawLatex(0.2,0.73,"Combination of all");
  lat.DrawLatex(0.2,0.68,"H#rightarrow inv. channels");


  c1.Update();
  c1.SaveAs("scan.pdf");
  return 0;
}
int main(int argc, char* argv[]) {
  Matrix G;
  Matrix Y;
  Matrix Cov;

  LoadMatrix("input.mt.g", G);
  LoadMatrix("input.mt.y", Y);
  LoadMatrix("input.mt.cov", Cov);
  Cov.SetColumnLabel(0, "c1");
  Cov.SetColumnLabel(1, "c2");
  Y.SetColumnLabel(0, "y1");
  Y.SetColumnLabel(1, "y2");
  Y.SetColumnLabel(2, "y3");

  FormulaVector tests;
  {
    const char* tp1[] = {"y1"};
    const char* tc1[] = {"c1"};
    std::vector<std::string> p1(tp1, tp1 + 1);
    std::vector<std::string> c1(tc1, tc1 + 1);
    tests.add(p1, c1);
  }

  {
    const char* tp1[] = {"y2"};
    const char* tc1[] = {"c2"};
    std::vector<std::string> p1(tp1, tp1 + 1);
    std::vector<std::string> c1(tc1, tc1 + 1);
    tests.add(p1, c1);
  }

  {
    const char* tp1[] = {"y2"};
    const char* tc1[] = {"c1", "c2"};
    std::vector<std::string> p1(tp1, tp1 + 1);
    std::vector<std::string> c1(tc1, tc1 + 2);
    tests.add(p1, c1);
  }

  {
    const char* tp1[] = {"y1"};
    const char* tc1[] = {"1"};
    std::vector<std::string> p1(tp1, tp1 + 1);
    std::vector<std::string> c1(tc1, tc1 + 1);
    tests.add(p1, c1);
  }

  AccurateTimer t;
  {
    FastMultipleTraitLinearRegressionScoreTest mt(1024);

    bool ret = mt.FitNullModel(Cov, Y, tests);
    if (ret == false) {
      printf("Fit null model failed!\n");
      exit(1);
    }

    ret = mt.AddGenotype(G);
    if (ret == false) {
      printf("Add covariate failed!\n");
      exit(1);
    }
    ret = mt.TestCovariateBlock();
    if (ret == false) {
      printf("Test covariate block failed!\n");
      exit(1);
    }
    const Vector& u = mt.GetU(0);
    printf("u\t");
    Print(u);
    printf("\n");

    const Vector& v = mt.GetV(0);
    printf("v\t");
    Print(v);
    printf("\n");

    const Vector& pval = mt.GetPvalue(0);
    printf("pval\t");
    Print(pval);
    printf("\n");
  }
  return 0;
}
Esempio n. 8
0
void tst_QPixmapCache::insert()
{
    QPixmap p1(10, 10);
    p1.fill(Qt::red);

    QPixmap p2(10, 10);
    p2.fill(Qt::yellow);

    // Calcuate estimated num of items what fits to cache
    int estimatedNum = (1024 * QPixmapCache::cacheLimit())
                       / ((p1.width() * p1.height() * p1.depth()) / 8);

    // Mare sure we will put enough items to reach the cache limit
    const int numberOfKeys = estimatedNum + 1000;

    // make sure it doesn't explode
    for (int i = 0; i < numberOfKeys; ++i)
        QPixmapCache::insert("0", p1);

    // ditto
    for (int j = 0; j < numberOfKeys; ++j)
        QPixmapCache::insert(QString::number(j), p1);

    int num = 0;
    for (int k = 0; k < numberOfKeys; ++k) {
        if (QPixmapCache::find(QString::number(k)))
            ++num;
    }

    if (QPixmapCache::find("0"))
        ++num;

    QVERIFY(num <= estimatedNum);
    QPixmap p3;
    QPixmapCache::insert("null", p3);

    QPixmap c1(10, 10);
    c1.fill(Qt::yellow);
    QPixmapCache::insert("custom", c1);
    QVERIFY(!c1.isDetached());
    QPixmap c2(10, 10);
    c2.fill(Qt::red);
    QPixmapCache::insert("custom", c2);
    //We have deleted the old pixmap in the cache for the same key
    QVERIFY(c1.isDetached());

    //The int part of the API
    // make sure it doesn't explode
    QList<QPixmapCache::Key> keys;
    for (int i = 0; i < numberOfKeys; ++i)
        keys.append(QPixmapCache::insert(p1));

    num = 0;
    for (int k = 0; k < numberOfKeys; ++k) {
        if (QPixmapCache::find(keys.at(k), &p2))
            ++num;
    }

    estimatedNum = (1024 * QPixmapCache::cacheLimit())
                       / ((p1.width() * p1.height() * p1.depth()) / 8);
    QVERIFY(num <= estimatedNum);
}
Esempio n. 9
0
int FacilityLocation::createConsFacilityActivation(int)
{
	int numCons = 0;
	VariableHash::iterator vit;
	Row::ROWSENSE sense = Row::LESS;
	int maxnnz = 2;
	double rhs = 0.0;
	int colVarX, colVarY, colVarZ;

	for (vit = vHash[Variable::V_X].begin(); vit != vHash[Variable::V_X].end(); ++vit)
	{
		colVarX = vit->second;
		Arc arc = vit->first.getArc();
		Vertex router = vit->first.getArc().getHead();
		Vertex client = vit->first.getArc().getTail();

		Constraint c(maxnnz, sense, rhs);
		c.setType(Constraint::C_FACILITY_ACTIVATION);
		c.setClass(1);
		c.setArc(arc);

		Variable y;
		y.setType(Variable::V_Y);
		y.setVertex1(router);
		VariableHash::iterator aux = vHash[Variable::V_Y].find(y);
		if (aux != vHash[Variable::V_Y].end())
		{
			colVarY = aux->second;

			c.rowAddVar(colVarX, 1.0);
			c.rowAddVar(colVarY, -1.0);
		}

		if (c.getRowNnz() > 0)
		{
			bool isInserted = addRow(&c);

			if (isInserted)
			{
				c.setRowIdx(getNRows() - 1);
				cHash[c] = c.getRowIdx();
				numCons++;
			}
		}
	}

	for (vit = vHash[Variable::V_Z].begin(); vit != vHash[Variable::V_Z].end(); ++vit)
	{
		colVarZ = vit->second;
		Arc arc = vit->first.getArc();
		Vertex head = vit->first.getArc().getHead();
		Vertex tail = vit->first.getArc().getTail();

		Constraint c1(maxnnz, sense, rhs);
		c1.setType(Constraint::C_FACILITY_ACTIVATION);
		c1.setClass(2);
		c1.setArc(arc);

		Variable yHead;
		yHead.setType(Variable::V_Y);
		yHead.setVertex1(head);
		VariableHash::iterator aux = vHash[Variable::V_Y].find(yHead);
		if (aux != vHash[Variable::V_Y].end())
		{
			colVarY = aux->second;

			c1.rowAddVar(colVarZ, 1.0);
			c1.rowAddVar(colVarY, -1.0);
		}

		if (c1.getRowNnz() > 0)
		{
			bool isInserted = addRow(&c1);

			if (isInserted)
			{
				c1.setRowIdx(getNRows() - 1);
				cHash[c1] = c1.getRowIdx();
				numCons++;
			}
		}

		Constraint c2(maxnnz, sense, rhs);
		c2.setType(Constraint::C_FACILITY_ACTIVATION);
		c2.setClass(2);
		c2.setArc(arc.reverse());

		Variable yTail;
		yTail.setType(Variable::V_Y);
		yTail.setVertex1(tail);
		aux = vHash[Variable::V_Y].find(yTail);
		if (aux != vHash[Variable::V_Y].end())
		{
			colVarY = aux->second;

			c2.rowAddVar(colVarZ, 1.0);
			c2.rowAddVar(colVarY, -1.0);
		}

		if (c2.getRowNnz() > 0)
		{
			bool isInserted = addRow(&c2);

			if (isInserted)
			{
				c2.setRowIdx(getNRows() - 1);
				cHash[c2] = c2.getRowIdx();
				numCons++;
			}
		}
	}

	return numCons;
}
int main()
{
    {
        std::vector<int> v(100);
        std::vector<int>::iterator i = v.insert(v.cbegin() + 10, 5, 1);
        assert(v.size() == 105);
        assert(is_contiguous_container_asan_correct(v)); 
        assert(i == v.begin() + 10);
        int j;
        for (j = 0; j < 10; ++j)
            assert(v[j] == 0);
        for (; j < 15; ++j)
            assert(v[j] == 1);
        for (++j; j < 105; ++j)
            assert(v[j] == 0);
    }
    {
        std::vector<int, stack_allocator<int, 300> > v(100);
        std::vector<int, stack_allocator<int, 300> >::iterator i = v.insert(v.cbegin() + 10, 5, 1);
        assert(v.size() == 105);
        assert(is_contiguous_container_asan_correct(v)); 
        assert(i == v.begin() + 10);
        int j;
        for (j = 0; j < 10; ++j)
            assert(v[j] == 0);
        for (; j < 15; ++j)
            assert(v[j] == 1);
        for (++j; j < 105; ++j)
            assert(v[j] == 0);
    }
#if _LIBCPP_DEBUG >= 1
    {
        std::vector<int> c1(100);
        std::vector<int> c2;
        std::vector<int>::iterator i = c1.insert(c2.cbegin() + 10, 5, 1);
        assert(false);
    }
#endif
#if __cplusplus >= 201103L
    {
        std::vector<int, min_allocator<int>> v(100);
        std::vector<int, min_allocator<int>>::iterator i = v.insert(v.cbegin() + 10, 5, 1);
        assert(v.size() == 105);
        assert(is_contiguous_container_asan_correct(v)); 
        assert(i == v.begin() + 10);
        int j;
        for (j = 0; j < 10; ++j)
            assert(v[j] == 0);
        for (; j < 15; ++j)
            assert(v[j] == 1);
        for (++j; j < 105; ++j)
            assert(v[j] == 0);
    }
    {
        std::vector<int, min_allocator<int>> v(100);
        std::vector<int, min_allocator<int>>::iterator i = v.insert(v.cbegin() + 10, 5, 1);
        assert(v.size() == 105);
        assert(is_contiguous_container_asan_correct(v)); 
        assert(i == v.begin() + 10);
        int j;
        for (j = 0; j < 10; ++j)
            assert(v[j] == 0);
        for (; j < 15; ++j)
            assert(v[j] == 1);
        for (++j; j < 105; ++j)
            assert(v[j] == 0);
    }
#if _LIBCPP_DEBUG >= 1
    {
        std::vector<int, min_allocator<int>> c1(100);
        std::vector<int, min_allocator<int>> c2;
        std::vector<int, min_allocator<int>>::iterator i = c1.insert(c2.cbegin() + 10, 5, 1);
        assert(false);
    }
#endif
#endif
}
Esempio n. 11
0
void yieldVcent(const char* inName=
	   "links/P01hi.minbias.2000.hist/hianalysis_1000.hist.root",
	   const char* psDir="ps",
	   int cut = 1,
	   const char* outDir="./",
	   const char* more = "west",
	   float extraValue = 0)
		
{
  
  cout << "--------------------------" << endl;
  cout << "in name=" << inName << endl
       << "ps dir=" << psDir << endl
       << "cut=" << cut << endl;
  cout << "--------------------------" << endl;
 
   inRoot = new TFile(inName);

  if(!inRoot){
    cout << "cannot find the infile" << endl;
    return;
  }
  TCanvas c1("c1","c1",400,500);
  TString sName,sTitle; TH1* h1a,*h1b; TH3* h3a, *h3b; TH2* h2a,*h2b;
  int nSlice=9;
  //---------------------------------------------------
  // zdc cent
  int zdcMin[]={0,5,10,20,30,40,50,60,70,80};
  int zdcMax[]={5,10,20,30,40,50,60,70,80,100};

  gStyle->SetOptLogy(1); gStyle->SetOptStat(0);
  sprintf(name,"raw pt yield, zdc slices (cut %d)",cut);
  Divide(&c1,3,3,name,inName);
  h2a=(TH2*)inRoot.Get("Plus.h2ZDCCentralityPtPr");
  h2b=(TH2*)inRoot.Get("Minus.h2ZDCCentralityPtPr");
  for(int i=1; i<=nSlice; i++){
    c1.cd(i);
    sprintf(name,"zdc%d%s",i,sPM[0]);
    h1a=h2a->ProjectionY(name,i,i,"e");
    sprintf(name,"zdc%d%s",i,sPM[1]);
    h1b=h2b->ProjectionY(name,i,i,"e");
    h1a->SetMarkerSize(0.5); h1b->SetMarkerSize(0.5);
    h1a->SetMarkerStyle(4); h1b->SetMarkerStyle(8);
    sprintf(title,"zdc cent %d (%d-%d %)",
	    h2a->GetXaxis()->GetBinCenter(i),zdcMin[i-1],zdcMax[i-1]);
    h1a->SetTitle(title); SetRange(h1a->GetXaxis(),1.5,6);
    //h1a->SetMinimum(0);
    h1a->Draw(); h1b->Draw("same");
    printHighPtYield(h1a,h1b);
  }
  Print(&c1,psDir,"yieldPtZdcSlices");
  // flow cent
  gStyle->SetOptLogy(1); gStyle->SetOptStat(0);
  sprintf(name,"raw pt yield, flow slices (cut %d)",cut);
  Divide(&c1,3,3,name,inName);
  h2a=(TH2*)inRoot.Get("Plus.h2CentralityPtPr");
  h2b=(TH2*)inRoot.Get("Minus.h2CentralityPtPr");
  for(int i=1; i<=nSlice; i++){
    c1.cd(i);
    sprintf(name,"flow%d%s",i,sPM[0]);
    h1a=h2a->ProjectionY(name,i,i,"e");
    sprintf(name,"flow%d%s",i,sPM[1]);
    h1b=h2b->ProjectionY(name,i,i,"e");
    h1a->SetMarkerStyle(4); h1b->SetMarkerStyle(8);
    h1a->SetMarkerSize(0.5); h1b->SetMarkerSize(0.5);
    sprintf(title,"flow cent %d",h2a->GetXaxis()->GetBinCenter(i));
    h1a->SetTitle(title); SetRange(h1a->GetXaxis(),1.5,6);
    //h1a->SetMinimum(0);
    h1a->Draw(); h1b->Draw("same");
    printHighPtYield(h1a,h1b);
  }
  Print(&c1,psDir,"yieldPtFlowSlices");
}
Esempio n. 12
0
int main(int argc, char *argv[]) {
	long seed = time(NULL);

	srand48(seed);
	SetSeed(to_ZZ(seed));

	unsigned p = 2027;
	unsigned g = 3;
	unsigned logQ = 120;

	FHEcontext context(p-1, logQ, p, g);
	activeContext = &context;
	context.SetUpSIContext();

	FHESISecKey secretKey(context);
	const FHESIPubKey &publicKey(secretKey);
	KeySwitchSI keySwitch(secretKey);

	long phim = context.zMstar.phiM();
	long numSlots = context.GetPlaintextSpace().GetTotalSlots();

	long rotAmt = rand() % numSlots;
	long rotDeg = 1;
	for (int i = 0; i < rotAmt; i++) {
		rotDeg *= context.Generator();
		rotDeg %= context.zMstar.M();
	}
	KeySwitchSI automorphKeySwitch(secretKey, rotDeg);

	Plaintext p0, p1, p2, p3;
	randomizePlaintext(p0, phim, p);
	randomizePlaintext(p1, phim, p);
	randomizePlaintext(p2, phim, p);
	randomizePlaintext(p3, phim, p);

	Plaintext const1, const2;
	randomizePlaintext(const1, phim, p);
	randomizePlaintext(const2, phim, p);

	Ciphertext c0(publicKey);
	Ciphertext c1(publicKey);
	Ciphertext c2(publicKey);
	Ciphertext c3(publicKey);

	publicKey.Encrypt(c0, p0);
	publicKey.Encrypt(c1, p1);
	publicKey.Encrypt(c2, p2);
	publicKey.Encrypt(c3, p3);

	p1 *= p2;
	p0 += const1;
	p2 *= const2;
	p3 >>= rotAmt;
	p1 *= -1;
	p3 *= p2;
	p0 -= p3;

	c1 *= c2;
	keySwitch.ApplyKeySwitch(c1);
	c0 += const1.message;

	c2 *= const2.message;

	c3 >>= rotDeg;
	automorphKeySwitch.ApplyKeySwitch(c3);

	c1 *= -1;
	c3 *= c2;
	keySwitch.ApplyKeySwitch(c3);

	Ciphertext tmp(c3);
	tmp *= -1;
	c0 += tmp;

	Plaintext pp0, pp1, pp2, pp3;
	secretKey.Decrypt(pp0, c0);
	secretKey.Decrypt(pp1, c1);
	secretKey.Decrypt(pp2, c2);
	secretKey.Decrypt(pp3, c3);

    if (!(pp0 == p0)) cerr << "oops 0" << endl;
    if (!(pp1 == p1)) cerr << "oops 1" << endl;
    if (!(pp2 == p2)) cerr << "oops 2" << endl;
    if (!(pp3 == p3)) cerr << "oops 3" << endl;
    cout << "All tests finished." << endl;
}
Esempio n. 13
0
void EditTSCtrl::renderCameraAxis()
{
   GFXDEBUGEVENT_SCOPE( Editor_renderCameraAxis, ColorI::WHITE );

   static MatrixF sRotMat(EulerF( (M_PI_F / -2.0f), 0.0f, 0.0f));

   MatrixF camMat = mLastCameraQuery.cameraMatrix;
   camMat.mul(sRotMat);
   camMat.inverse();

   MatrixF axis;
   axis.setColumn(0, Point3F(1, 0, 0));
   axis.setColumn(1, Point3F(0, 0, 1));
   axis.setColumn(2, Point3F(0, -1, 0));
   axis.mul(camMat);

   Point3F forwardVec, upVec, rightVec;
	axis.getColumn( 2, &forwardVec );
	axis.getColumn( 1, &upVec );
	axis.getColumn( 0, &rightVec );

   Point2I pos = getPosition();
	F32 offsetx = pos.x + 20.0;
	F32 offsety = pos.y + getExtent().y - 42.0; // Take the status bar into account
	F32 scale = 15.0;

   // Generate correct drawing order
   ColorI c1(255,0,0);
   ColorI c2(0,255,0);
   ColorI c3(0,0,255);
	ColorI tc;
	Point3F *p1, *p2, *p3, *tp;
	p1 = &rightVec;
	p2 = &upVec;
	p3 = &forwardVec;
	if(p3->y > p2->y)
	{
		tp = p2; tc = c2;
		p2 = p3; c2 = c3;
		p3 = tp; c3 = tc;
	}
	if(p2->y > p1->y)
	{
		tp = p1; tc = c1;
		p1 = p2; c1 = c2;
		p2 = tp; c2 = tc;
	}

   PrimBuild::begin( GFXLineList, 6 );
		//*** Axis 1
		PrimBuild::color(c1);
		PrimBuild::vertex3f(offsetx, offsety, 0);
		PrimBuild::vertex3f(offsetx+p1->x*scale, offsety-p1->z*scale, 0);

		//*** Axis 2
		PrimBuild::color(c2);
		PrimBuild::vertex3f(offsetx, offsety, 0);
		PrimBuild::vertex3f(offsetx+p2->x*scale, offsety-p2->z*scale, 0);

		//*** Axis 3
		PrimBuild::color(c3);
		PrimBuild::vertex3f(offsetx, offsety, 0);
		PrimBuild::vertex3f(offsetx+p3->x*scale, offsety-p3->z*scale, 0);
   PrimBuild::end();
}
Esempio n. 14
0
void test_basic_template(
  ForwardIterator first,ForwardIterator last
  BOOST_APPEND_EXPLICIT_TEMPLATE_TYPE(Flyweight))
{
  typedef typename Flyweight::value_type value_type;

  ForwardIterator it;

  for(it=first;it!=last;++it){
    /* construct/copy/destroy */

    Flyweight                            f1(*it);
    Flyweight                            f2;
    Flyweight                            c1(f1);
    const Flyweight                      c2(static_cast<const Flyweight&>(f2));
    value_type                           v1(*it);
    boost::value_initialized<value_type> v2;
    BOOST_TEST(f1.get_key()==*it);
    BOOST_TEST((f1==f2)==(f1.get()==v2.data()));
    BOOST_TEST(f1==c1);
    BOOST_TEST(f2==c2);

#if !defined(BOOST_NO_CXX11_RVALUE_REFERENCES)
    Flyweight cr1(std::move(c1));
    Flyweight cr2(std::move(c2));
    BOOST_TEST(f1==cr1);
    BOOST_TEST(f2==cr2);
#endif

#if !defined(BOOST_NO_CXX11_UNIFIED_INITIALIZATION_SYNTAX)
    /* testcase for https://svn.boost.org/trac/boost/ticket/10439 */

    Flyweight f3={};
    BOOST_TEST(f3==f2);
#endif

    f1=f1;
    BOOST_TEST(f1==f1);

    c1=f2;
    BOOST_TEST(c1==f2);

    c1=f1;
    BOOST_TEST(c1==f1);

    /* convertibility to underlying type */

    BOOST_TEST(f1.get()==v1);

    /* identity of reference */

    BOOST_TEST(&f1.get()==&c1.get());

    /* modifiers */

    f1.swap(f1);
    BOOST_TEST(f1==c1);

    f1.swap(f2);
    BOOST_TEST(f1==c2);
    BOOST_TEST(f2==c1);

    boost::flyweights::swap(f1,f2);
    BOOST_TEST(f1==c1);
    BOOST_TEST(f2==c2);

    /* specialized algorithms */

    std::ostringstream oss1;
    oss1<<f1;
    std::ostringstream oss2;
    oss2<<f1.get();
    BOOST_TEST(oss1.str()==oss2.str());

#if !defined(BOOST_FLYWEIGHT_DISABLE_HASH_SUPPORT)

    /* hash support */

    BOOST_TEST(boost::hash<Flyweight>()(f1)==boost::hash<Flyweight>()(c1));
    BOOST_TEST(boost::hash<Flyweight>()(f1)==
               boost::hash<const value_type*>()(&f1.get()));

#if !defined(BOOST_NO_CXX11_HDR_FUNCTIONAL)
    BOOST_TEST(std::hash<Flyweight>()(f1)==std::hash<Flyweight>()(c1));
    BOOST_TEST(std::hash<Flyweight>()(f1)==
               std::hash<const value_type*>()(&f1.get()));
#endif
#endif
  }
}
Esempio n. 15
0
bool QQuickSvgParser::parsePathDataFast(const QString &dataStr, QPainterPath &path)
{
    qreal x0 = 0, y0 = 0;              // starting point
    qreal x = 0, y = 0;                // current point
    char lastMode = 0;
    QPointF ctrlPt;
    const QChar *str = dataStr.constData();
    const QChar *end = str + dataStr.size();

    while (str != end) {
        while (str->isSpace())
            ++str;
        QChar pathElem = *str;
        ++str;
        QChar endc = *end;
        *const_cast<QChar *>(end) = 0; // parseNumbersArray requires 0-termination that QStringRef cannot guarantee
        QVarLengthArray<qreal, 8> arg;
        parseNumbersArray(str, arg);
        *const_cast<QChar *>(end) = endc;
        if (pathElem == QLatin1Char('z') || pathElem == QLatin1Char('Z'))
            arg.append(0);//dummy
        const qreal *num = arg.constData();
        int count = arg.count();
        while (count > 0) {
            qreal offsetX = x;        // correction offsets
            qreal offsetY = y;        // for relative commands
            switch (pathElem.unicode()) {
            case 'm': {
                if (count < 2) {
                    num++;
                    count--;
                    break;
                }
                x = x0 = num[0] + offsetX;
                y = y0 = num[1] + offsetY;
                num += 2;
                count -= 2;
                path.moveTo(x0, y0);

                 // As per 1.2  spec 8.3.2 The "moveto" commands
                 // If a 'moveto' is followed by multiple pairs of coordinates without explicit commands,
                 // the subsequent pairs shall be treated as implicit 'lineto' commands.
                 pathElem = QLatin1Char('l');
            }
                break;
            case 'M': {
                if (count < 2) {
                    num++;
                    count--;
                    break;
                }
                x = x0 = num[0];
                y = y0 = num[1];
                num += 2;
                count -= 2;
                path.moveTo(x0, y0);

                // As per 1.2  spec 8.3.2 The "moveto" commands
                // If a 'moveto' is followed by multiple pairs of coordinates without explicit commands,
                // the subsequent pairs shall be treated as implicit 'lineto' commands.
                pathElem = QLatin1Char('L');
            }
                break;
            case 'z':
            case 'Z': {
                x = x0;
                y = y0;
                count--; // skip dummy
                num++;
                path.closeSubpath();
            }
                break;
            case 'l': {
                if (count < 2) {
                    num++;
                    count--;
                    break;
                }
                x = num[0] + offsetX;
                y = num[1] + offsetY;
                num += 2;
                count -= 2;
                path.lineTo(x, y);

            }
                break;
            case 'L': {
                if (count < 2) {
                    num++;
                    count--;
                    break;
                }
                x = num[0];
                y = num[1];
                num += 2;
                count -= 2;
                path.lineTo(x, y);
            }
                break;
            case 'h': {
                x = num[0] + offsetX;
                num++;
                count--;
                path.lineTo(x, y);
            }
                break;
            case 'H': {
                x = num[0];
                num++;
                count--;
                path.lineTo(x, y);
            }
                break;
            case 'v': {
                y = num[0] + offsetY;
                num++;
                count--;
                path.lineTo(x, y);
            }
                break;
            case 'V': {
                y = num[0];
                num++;
                count--;
                path.lineTo(x, y);
            }
                break;
            case 'c': {
                if (count < 6) {
                    num += count;
                    count = 0;
                    break;
                }
                QPointF c1(num[0] + offsetX, num[1] + offsetY);
                QPointF c2(num[2] + offsetX, num[3] + offsetY);
                QPointF e(num[4] + offsetX, num[5] + offsetY);
                num += 6;
                count -= 6;
                path.cubicTo(c1, c2, e);
                ctrlPt = c2;
                x = e.x();
                y = e.y();
                break;
            }
            case 'C': {
                if (count < 6) {
                    num += count;
                    count = 0;
                    break;
                }
                QPointF c1(num[0], num[1]);
                QPointF c2(num[2], num[3]);
                QPointF e(num[4], num[5]);
                num += 6;
                count -= 6;
                path.cubicTo(c1, c2, e);
                ctrlPt = c2;
                x = e.x();
                y = e.y();
                break;
            }
            case 's': {
                if (count < 4) {
                    num += count;
                    count = 0;
                    break;
                }
                QPointF c1;
                if (lastMode == 'c' || lastMode == 'C' ||
                    lastMode == 's' || lastMode == 'S')
                    c1 = QPointF(2*x-ctrlPt.x(), 2*y-ctrlPt.y());
                else
                    c1 = QPointF(x, y);
                QPointF c2(num[0] + offsetX, num[1] + offsetY);
                QPointF e(num[2] + offsetX, num[3] + offsetY);
                num += 4;
                count -= 4;
                path.cubicTo(c1, c2, e);
                ctrlPt = c2;
                x = e.x();
                y = e.y();
                break;
            }
            case 'S': {
                if (count < 4) {
                    num += count;
                    count = 0;
                    break;
                }
                QPointF c1;
                if (lastMode == 'c' || lastMode == 'C' ||
                    lastMode == 's' || lastMode == 'S')
                    c1 = QPointF(2*x-ctrlPt.x(), 2*y-ctrlPt.y());
                else
                    c1 = QPointF(x, y);
                QPointF c2(num[0], num[1]);
                QPointF e(num[2], num[3]);
                num += 4;
                count -= 4;
                path.cubicTo(c1, c2, e);
                ctrlPt = c2;
                x = e.x();
                y = e.y();
                break;
            }
            case 'q': {
                if (count < 4) {
                    num += count;
                    count = 0;
                    break;
                }
                QPointF c(num[0] + offsetX, num[1] + offsetY);
                QPointF e(num[2] + offsetX, num[3] + offsetY);
                num += 4;
                count -= 4;
                path.quadTo(c, e);
                ctrlPt = c;
                x = e.x();
                y = e.y();
                break;
            }
            case 'Q': {
                if (count < 4) {
                    num += count;
                    count = 0;
                    break;
                }
                QPointF c(num[0], num[1]);
                QPointF e(num[2], num[3]);
                num += 4;
                count -= 4;
                path.quadTo(c, e);
                ctrlPt = c;
                x = e.x();
                y = e.y();
                break;
            }
            case 't': {
                if (count < 2) {
                    num += count;
                    count = 0;
                    break;
                }
                QPointF e(num[0] + offsetX, num[1] + offsetY);
                num += 2;
                count -= 2;
                QPointF c;
                if (lastMode == 'q' || lastMode == 'Q' ||
                    lastMode == 't' || lastMode == 'T')
                    c = QPointF(2*x-ctrlPt.x(), 2*y-ctrlPt.y());
                else
                    c = QPointF(x, y);
                path.quadTo(c, e);
                ctrlPt = c;
                x = e.x();
                y = e.y();
                break;
            }
            case 'T': {
                if (count < 2) {
                    num += count;
                    count = 0;
                    break;
                }
                QPointF e(num[0], num[1]);
                num += 2;
                count -= 2;
                QPointF c;
                if (lastMode == 'q' || lastMode == 'Q' ||
                    lastMode == 't' || lastMode == 'T')
                    c = QPointF(2*x-ctrlPt.x(), 2*y-ctrlPt.y());
                else
                    c = QPointF(x, y);
                path.quadTo(c, e);
                ctrlPt = c;
                x = e.x();
                y = e.y();
                break;
            }
            case 'a': {
                if (count < 7) {
                    num += count;
                    count = 0;
                    break;
                }
                qreal rx = (*num++);
                qreal ry = (*num++);
                qreal xAxisRotation = (*num++);
                qreal largeArcFlag  = (*num++);
                qreal sweepFlag = (*num++);
                qreal ex = (*num++) + offsetX;
                qreal ey = (*num++) + offsetY;
                count -= 7;
                qreal curx = x;
                qreal cury = y;
                pathArc(path, rx, ry, xAxisRotation, int(largeArcFlag),
                        int(sweepFlag), ex, ey, curx, cury);

                x = ex;
                y = ey;
            }
                break;
            case 'A': {
                if (count < 7) {
                    num += count;
                    count = 0;
                    break;
                }
                qreal rx = (*num++);
                qreal ry = (*num++);
                qreal xAxisRotation = (*num++);
                qreal largeArcFlag  = (*num++);
                qreal sweepFlag = (*num++);
                qreal ex = (*num++);
                qreal ey = (*num++);
                count -= 7;
                qreal curx = x;
                qreal cury = y;
                pathArc(path, rx, ry, xAxisRotation, int(largeArcFlag),
                        int(sweepFlag), ex, ey, curx, cury);

                x = ex;
                y = ey;
            }
                break;
            default:
                return false;
            }
            lastMode = pathElem.toLatin1();
        }
    }
    return true;
}
Esempio n. 16
0
void plot(const char* type = "eps")
{
  gROOT->ProcessLine(".x ../../style.C");

  TFile *f = new TFile("../../SharedRootFiles/Osc.root");

  TH1D *data[6];
  TH1D *predOsc[6];
  TH1D *acc[6];
  TH1D *li9[6];
  TH1D *fsn[6];
  TH1D *afn[6];
  TH1D *amc[6];

  data[0] = (TH1D*)f->Get("ibd_spectrum_site1_det1");
  data[1] = (TH1D*)f->Get("ibd_spectrum_site1_det2");
  data[2] = (TH1D*)f->Get("ibd_spectrum_site2_det1");
  data[3] = (TH1D*)f->Get("ibd_spectrum_site4_det1");
  data[4] = (TH1D*)f->Get("ibd_spectrum_site4_det2");
  data[5] = (TH1D*)f->Get("ibd_spectrum_site4_det3");

  predOsc[0] = (TH1D*)f->Get("total_spectrum_expected_AD1");
  predOsc[1] = (TH1D*)f->Get("total_spectrum_expected_AD2");
  predOsc[2] = (TH1D*)f->Get("total_spectrum_expected_AD3");
  predOsc[3] = (TH1D*)f->Get("total_spectrum_expected_AD4");
  predOsc[4] = (TH1D*)f->Get("total_spectrum_expected_AD5");
  predOsc[5] = (TH1D*)f->Get("total_spectrum_expected_AD6");

  acc[0] = (TH1D*)f->Get("acc_spectrum_expected_AD1");
  acc[1] = (TH1D*)f->Get("acc_spectrum_expected_AD2");
  acc[2] = (TH1D*)f->Get("acc_spectrum_expected_AD3");
  acc[3] = (TH1D*)f->Get("acc_spectrum_expected_AD4");
  acc[4] = (TH1D*)f->Get("acc_spectrum_expected_AD5");
  acc[5] = (TH1D*)f->Get("acc_spectrum_expected_AD6");

  li9[0] = (TH1D*)f->Get("li9he8_spectrum_expected_AD1");
  li9[1] = (TH1D*)f->Get("li9he8_spectrum_expected_AD2");
  li9[2] = (TH1D*)f->Get("li9he8_spectrum_expected_AD3");
  li9[3] = (TH1D*)f->Get("li9he8_spectrum_expected_AD4");
  li9[4] = (TH1D*)f->Get("li9he8_spectrum_expected_AD5");
  li9[5] = (TH1D*)f->Get("li9he8_spectrum_expected_AD6");

  fsn[0] = (TH1D*)f->Get("fastn_spectrum_expected_AD1");
  fsn[1] = (TH1D*)f->Get("fastn_spectrum_expected_AD2");
  fsn[2] = (TH1D*)f->Get("fastn_spectrum_expected_AD3");
  fsn[3] = (TH1D*)f->Get("fastn_spectrum_expected_AD4");
  fsn[4] = (TH1D*)f->Get("fastn_spectrum_expected_AD5");
  fsn[5] = (TH1D*)f->Get("fastn_spectrum_expected_AD6");

  amc[0] = (TH1D*)f->Get("amc_spectrum_expected_AD1");
  amc[1] = (TH1D*)f->Get("amc_spectrum_expected_AD2");
  amc[2] = (TH1D*)f->Get("amc_spectrum_expected_AD3");
  amc[3] = (TH1D*)f->Get("amc_spectrum_expected_AD4");
  amc[4] = (TH1D*)f->Get("amc_spectrum_expected_AD5");
  amc[5] = (TH1D*)f->Get("amc_spectrum_expected_AD6");

  afn[0] = (TH1D*)f->Get("alphan_spectrum_expected_AD1");
  afn[1] = (TH1D*)f->Get("alphan_spectrum_expected_AD2");
  afn[2] = (TH1D*)f->Get("alphan_spectrum_expected_AD3");
  afn[3] = (TH1D*)f->Get("alphan_spectrum_expected_AD4");
  afn[4] = (TH1D*)f->Get("alphan_spectrum_expected_AD5");
  afn[5] = (TH1D*)f->Get("alphan_spectrum_expected_AD6");


  TH1D *data_site1 = data[0]->Clone("data_site1");
  data_site1->GetXaxis()->SetTitle("Prompt Energy [MeV]");
  data_site1->GetYaxis()->SetTitle("Events / 50KeV");
  data_site1->SetTitle("IBDs at EH1");

  TH1D *data_site2 = data[2]->Clone("data_site2");
  data_site2->GetXaxis()->SetTitle("Prompt Energy [MeV]");
  data_site2->GetYaxis()->SetTitle("Events / 50KeV");
  data_site2->SetTitle("IBDs at EH2");

  TH1D *data_site3 = data[3]->Clone("data_site3");
  data_site3->GetXaxis()->SetTitle("Prompt Energy [MeV]");
  data_site3->GetYaxis()->SetTitle("Events / 50KeV");
  data_site3->SetTitle("IBDs at EH3");

  TH1D *pred_site1 = predOsc[0]->Clone("pred_site1");
  THStack *hs_site1 = new THStack("hs_site1", "");
  TH1D *acc_site1  = acc[0]->Clone("acc_site1");
  TH1D *li9_site1  = li9[0]->Clone("li9_site1");
  TH1D *fsn_site1  = fsn[0]->Clone("fsn_site1");
  TH1D *amc_site1  = amc[0]->Clone("amc_site1");
  TH1D *afn_site1  = afn[0]->Clone("afn_site1");

  TH1D *pred_site2 = predOsc[2]->Clone("pred_site2");
  THStack *hs_site2 = new THStack("hs_site2", "");
  TH1D *acc_site2  = acc[2]->Clone("acc_site2");
  TH1D *li9_site2  = li9[2]->Clone("li9_site2");
  TH1D *fsn_site2  = fsn[2]->Clone("fsn_site2");
  TH1D *amc_site2  = amc[2]->Clone("amc_site2");
  TH1D *afn_site2  = afn[2]->Clone("afn_site2");

  TH1D *pred_site3 = predOsc[3]->Clone("pred_site3");
  THStack *hs_site3 = new THStack("hs_site3", "");
  TH1D *acc_site3  = acc[3]->Clone("acc_site3");
  TH1D *li9_site3  = li9[3]->Clone("li9_site3");
  TH1D *fsn_site3  = fsn[3]->Clone("fsn_site3");
  TH1D *amc_site3  = amc[3]->Clone("amc_site3");
  TH1D *afn_site3  = afn[3]->Clone("afn_site3");

  data_site1->Reset();
  pred_site1->Reset();
  acc_site1->Reset();
  li9_site1->Reset();
  fsn_site1->Reset();
  amc_site1->Reset();
  afn_site1->Reset();

  data_site2->Reset();
  pred_site2->Reset();
  acc_site2->Reset();
  li9_site2->Reset();
  fsn_site2->Reset();
  amc_site2->Reset();
  afn_site2->Reset();

  data_site3->Reset();
  pred_site3->Reset();
  acc_site3->Reset();
  li9_site3->Reset();
  fsn_site3->Reset();
  amc_site3->Reset();
  afn_site3->Reset();


  pred_site1->SetLineColor(2);
  pred_site1->SetMarkerColor(2);

  acc_site1->SetLineColor(9);
  acc_site1->SetMarkerColor(9);
  acc_site1->SetFillColor(9);

  li9_site1->SetLineColor(5);
  li9_site1->SetMarkerColor(5);
  li9_site1->SetFillColor(5);

  fsn_site1->SetLineColor(6);
  fsn_site1->SetMarkerColor(6);
  fsn_site1->SetFillColor(6);

  amc_site1->SetLineColor(7);
  amc_site1->SetMarkerColor(7);
  amc_site1->SetFillColor(7);

  afn_site1->SetLineColor(8);
  afn_site1->SetLineColor(8);
  afn_site1->SetFillColor(8);



  pred_site2->SetLineColor(2);
  pred_site2->SetMarkerColor(2);

  acc_site2->SetLineColor(9);
  acc_site2->SetMarkerColor(9);
  acc_site2->SetFillColor(9);

  li9_site2->SetLineColor(5);
  li9_site2->SetMarkerColor(5);
  li9_site2->SetFillColor(5);

  fsn_site2->SetLineColor(6);
  fsn_site2->SetMarkerColor(6);
  fsn_site2->SetFillColor(6);

  amc_site2->SetLineColor(7);
  amc_site2->SetMarkerColor(7);
  amc_site2->SetFillColor(7);

  afn_site2->SetLineColor(8);
  afn_site2->SetLineColor(8);
  afn_site2->SetFillColor(8);


  pred_site3->SetLineColor(2);
  pred_site3->SetMarkerColor(2);

  acc_site3->SetLineColor(9);
  acc_site3->SetMarkerColor(9);
  acc_site3->SetFillColor(9);

  li9_site3->SetLineColor(5);
  li9_site3->SetMarkerColor(5);
  li9_site3->SetFillColor(5);

  fsn_site3->SetLineColor(6);
  fsn_site3->SetMarkerColor(6);
  fsn_site3->SetFillColor(6);

  amc_site3->SetLineColor(7);
  amc_site3->SetMarkerColor(7);
  amc_site3->SetFillColor(7);

  afn_site3->SetLineColor(8);
  afn_site3->SetLineColor(8);
  afn_site3->SetFillColor(8);


  for (int i=0; i<2; i++) {
    data_site1->Add(data[i]);
    pred_site1->Add(predOsc[i]);
    acc_site1->Add(acc[i]);
    li9_site1->Add(li9[i]);
    fsn_site1->Add(fsn[i]);
    amc_site1->Add(amc[i]);
    afn_site1->Add(afn[i]);
  }

  for (int i=2; i<3; i++) {
    data_site2->Add(data[i]);
    pred_site2->Add(predOsc[i]);
    acc_site2->Add(acc[i]);
    li9_site2->Add(li9[i]);
    fsn_site2->Add(fsn[i]);
    amc_site2->Add(amc[i]);
    afn_site2->Add(afn[i]);
  }

  for (int i=3; i<6; i++) {
    data_site3->Add(data[i]);
    pred_site3->Add(predOsc[i]);
    acc_site3->Add(acc[i]);
    li9_site3->Add(li9[i]);
    fsn_site3->Add(fsn[i]);
    amc_site3->Add(amc[i]);
    afn_site3->Add(afn[i]);
  }

  hs_site1->Add(fsn_site1);
  hs_site1->Add(afn_site1);
  hs_site1->Add(amc_site1);
  hs_site1->Add(li9_site1);
  hs_site1->Add(acc_site1);

  hs_site2->Add(fsn_site2);
  hs_site2->Add(afn_site2);
  hs_site2->Add(amc_site2);
  hs_site2->Add(li9_site2);
  hs_site2->Add(acc_site2);

  hs_site3->Add(fsn_site3);
  hs_site3->Add(afn_site3);
  hs_site3->Add(amc_site3);
  hs_site3->Add(li9_site3);
  hs_site3->Add(acc_site3);

  TCanvas c1("c1", "c1", 800, 800);
  TPad *can_1 = new TPad("can_1", "can_1",0, 0.66, 1, 0.99);
  TPad *can_2 = new TPad("can_2", "can_2",0, 0.33, 1, 0.66);
  TPad *can_3 = new TPad("can_3", "can_3",0, 0, 1, 0.33);

  can_1->Draw();
  can_1->cd();
  can_1->SetBottomMargin(1e-05);
  can_1->SetFrameBorderMode(0);
  can_1->SetBorderMode(0);
  data_site1->Draw();
  data_site1->SetTitle("");
  hs_site1->Draw("same");
  data_site1->Draw("same");
  // pred_site1->Draw("same");
  data_site1->GetXaxis()->SetLabelSize(0.09);
  data_site1->GetYaxis()->SetNdivisions(508);
  data_site1->GetYaxis()->SetTitleSize(0.08);
  data_site1->GetYaxis()->SetLabelSize(0.08);
  data_site1->GetYaxis()->SetTitleOffset(0.6);
  data_site1->GetYaxis()->CenterTitle(true);
  TLegend leg(0.65,0.85-0.20,0.85,0.85);
  leg.AddEntry(data_site1, " EH1", "lp");
  leg.AddEntry(acc_site1, " Acc. Bkgd", "f");
  leg.SetFillColor(kWhite);
  leg.Draw();
  can_1->Modified();
  c1.cd();

  can_2->Draw();
  can_2->cd();
  can_2->SetTopMargin(1e-05);
  can_2->SetBottomMargin(1e-05);
  can_2->SetFrameBorderMode(0);
  can_2->SetBorderMode(0);
  data_site2->Draw();
  hs_site2->Draw("same");
  data_site2->SetTitle("");
  // data_site2->Draw("same");
  // pred_site2->Draw("same");
  data_site2->GetXaxis()->SetLabelSize(0.09);
  data_site2->GetYaxis()->SetNdivisions(508);
  data_site2->GetYaxis()->SetTitleSize(0.08);
  data_site2->GetYaxis()->SetLabelSize(0.08);
  data_site2->GetYaxis()->SetTitleOffset(0.6);
  data_site2->GetYaxis()->CenterTitle(true);
  TLegend leg2(0.65,0.85-0.20,0.85,0.85);
  leg2.AddEntry(data_site2, " EH2", "lp");
  leg2.AddEntry(acc_site2, " Acc. Bkgd", "f");
  leg2.SetFillColor(kWhite);
  leg2.Draw();
  can_2->Modified();
  c1.cd();

  can_3->Draw();
  can_3->cd();
  can_3->SetTopMargin(1e-05);
  can_3->SetFrameBorderMode(0);
  can_3->SetBottomMargin(0.3);
  can_3->SetBorderMode(0);
  data_site3->Draw();
  hs_site3->Draw("same");
  data_site3->SetTitle("");
  // data_site3->Draw("same");
  // pred_site3->Draw("same");
  data_site3->GetXaxis()->SetTitle("Reconstructed Energy [MeV]");
  data_site3->GetXaxis()->SetTitleSize(0.09);
  data_site3->GetXaxis()->SetTitleOffset(1.45);
  data_site3->GetXaxis()->SetLabelSize(0.09);
  data_site3->GetXaxis()->Draw();
  data_site3->GetYaxis()->SetNdivisions(508);
  data_site3->GetYaxis()->SetLabelSize(0.08);
  data_site3->GetYaxis()->SetTitleSize(0.08);
  data_site3->GetYaxis()->SetTitleOffset(0.6);
  data_site3->GetYaxis()->CenterTitle(true);
  can_3->RedrawAxis();
  TLegend leg3(0.65,0.85-0.20,0.85,0.85);
  leg3.AddEntry(data_site3, " EH3", "lp");
  leg3.AddEntry(acc_site3, " Acc. Bkgd", "f");
  leg3.SetFillColor(kWhite);
  leg3.Draw();
  can_3->Modified();
  c1.cd();

  TString name("SpectraSite");
  // print 3 figures by default
  c1.SaveAs(name + ".eps");
  c1.SaveAs(name + ".pdf");
  c1.SaveAs(name + ".png");

  TString extra(type);
  if (! (extra == "eps" || extra == "pdf" || extra == "png")) {
    c1.SaveAs(name + "." + type);
  }
}
Esempio n. 17
0
int main(int argc, char *argv[]) 
{
  ArgMapping amap;

  long m=17;
  amap.arg("m", m, "cyclotomic index");
  amap.note("e.g., m=2047");

  long p=2;
  amap.arg("p", p, "plaintext base");

  long r=1;
  amap.arg("r", r,  "lifting");

  Vec<long> gens0;
  amap.arg("gens", gens0, "use specified vector of generators", NULL);
  amap.note("e.g., gens='[562 1871 751]'");

  Vec<long> ords0;
  amap.arg("ords", ords0, "use specified vector of orders", NULL);
  amap.note("e.g., ords='[4 2 -4]', negative means 'bad'");

  amap.parse(argc, argv);

  cout << "m = " << m << ", p = " << p <<  ", r = " << r << endl;

  vector<long> f;
  factorize(f,m);
  cout << "factoring "<<m<<" gives [";
  for (unsigned long i=0; i<f.size(); i++)
    cout << f[i] << " ";
  cout << "]\n";

  vector<long> gens1, ords1;
  convert(gens1, gens0);
  convert(ords1, ords0);

  PAlgebra al(m, p, gens1, ords1);
  al.printout();
  cout << "\n";

  PAlgebraMod almod(al, r);

  FHEcontext context(m, p, r);
  buildModChain(context, 5, 2);

  stringstream s1;
  writeContextBase(s1, context);
  s1 << context;

  string s2 = s1.str();

  cout << s2 << endl;

  stringstream s3(s2);

  unsigned long m1, p1, r1;
  vector<long> gens, ords;
  readContextBase(s3, m1, p1, r1, gens, ords);

  FHEcontext c1(m1, p1, r1, gens, ords);
  s3 >> c1;

  if (context == c1)
    cout << "equal\n";
  else
    cout << "not equal\n";

  return 0;
}
Esempio n. 18
0
void CBoxProxyView::functionTest()
{
	Wm5::Vector3d c1(0,0,0);
	Wm5::Vector3d c2(4,4,0);
	Wm5::Vector3d c3(3,1,0);
	Wm5::Vector3d x1(1,0,0);
	Wm5::Vector3d y1(0,1,0);
	Wm5::Vector3d z1(0,0,1);
	Wm5::Vector3d x2(1,1,0);
	Wm5::Vector3d y2(-1,1,0);
	Wm5::Vector3d z2(0,0,1);

	Wm5::Box3d b(c1,x1,y1,z1,1,1,1);
	Wm5::Box3d c(c2,x2,y2,z2,1,1,1);
	Wm5::Box3d d(c3,x1,y1,z1,1,1,1);


	testBoxA=new Box(b);
	testBoxB=new Box(c);
	testBoxC=new Box(d);
	//*testBoxA=boxes.at(2);
	for (int i=1;i<boxes.size();i++)
	{
			cI.alignBox(boxes.at(i),downDir);
	}
	for (int i=1;i<boxes.size()-1;i++)
	{
		for (int j=i+1;j<boxes.size();j++)
		{
			cI.alignBoxes(boxes.at(i),boxes.at(j));
		}
	}

	
	for (int i=0;i<boxes.size()-1;i++)
	{
		for (int j=i+1;j<boxes.size();j++)
		{
			cI.removePenetrate(boxes.at(i),boxes.at(j));
		}
	}
	Wm5::Box3d FBox=boxes.at(0).GetWmBox();

	for (int i = 0; i < 6; i++)
	{
		Wm5::Vector3d Normal=cI.getNormal(FBox,i);
		if (fabs(Normal.Dot(downDir))<0.95)
		{
			cI.extendWmBox(FBox,1,i);
		}
	}
	boxes.at(0)=Box(FBox);
	boxes.at(0).type=1;
	extendedBoxes=boxes;
	//cI.getTouch(testConSet,boxes.at(4),boxes.at(6),boxes.at(4).GetWmBox(),boxes.at(6).GetWmBox());
	//cI.getContact(testConSet,boxes.at(4),boxes.at(6),boxes.at(4).GetWmBox(),boxes.at(6).GetWmBox());
	//cI.removePenetrate(boxes.at(4),boxes.at(6));
	//cI.alignBox(boxes.at(2),Axis);
	//cI.alignBox(boxes.at(1),boxes.at(0).GetWmBox().Axis[1]);
	//cI.getContactCandidateEx(testConSet,boxes.at(1),boxes.at(4));
	//cI.getContactCandidateEx(testConSet,*testBoxA,*testBoxB);
	//cI.getContactCandidateEx(testConSet2,*testBoxA,*testBoxC);
	//cI.updateBox(b,testConSet.at(0),1);
	//cI.updateBox(b,testConSet2.at(0),1);
	//delete testBoxA;
	//testBoxA=new Box(b);
	vector<Box> testBoxes;
	//testBoxes.push_back(*testBoxA);
	//testBoxes.push_back(*testBoxB);
	//testBoxes.push_back(*testBoxC);
	//testBoxes.push_back(boxes.at(0));
	//testBoxes.push_back(boxes.at(6));
	//testBoxes.push_back(boxes.at(7));
	//boxes=testBoxes;
	//conGraph=new ContactGraph(boxes,Wm5::Vector3d::ZERO,0);
	//while(conGraph->IterateOneStep());
	//GraphCreated=true;
	//Box bc=boxes.at(2);

}
Esempio n. 19
0
void TeMANAGER::TeGDLegend::draw(std::vector<TeLegendEntryVector>& legends,
					  std::vector<std::string>& legendTitles,
					  const int& width)
{
// verifica quantas linhas tera a legenda: uma para cada legenda e mais uma para cada agrupamento
	int legendVecSize = 0;

	for(unsigned int i = 0; i < legends.size(); ++i)
	{
		if(legends[i].size() > 1)	// se existe mais de uma legenda, entao temos um agrupamento!
			legendVecSize += legends[i].size() + 1;
		else						// caso contrario, temos somente uma legenda
			++legendVecSize;
	}

	if(legendVecSize == 0)
		return;

// determina as dimensoes do canvas
	int legendHeight =  legendVecSize * 20;

	double nlin = (double)legendHeight / 20.0;
    double ncol = (double)width/20.0;

	TeCoord2D c1(0.0, 0.0);
	TeCoord2D c2(ncol, nlin);
	TeBox b(0.0, 0.0, ncol, nlin);

// ajusta o canvas
	gdCanvas_->setWorld(b, width, legendHeight);

// marca a posicao inicial de escrita
	int currentLinePosition = 0;

	double posd = legendVecSize - 1;

	TeCoord2D c(ncol/2.0, posd + 0.60);

// desenha as legendas
	for(unsigned int i = 0; i < legends.size(); ++i)
	{
		for(unsigned int j = 0; j < legends[i].size(); ++j)
		{
			posd = legendVecSize - 1 - currentLinePosition;

			if((j == 0) && legends[i].size() > 1)
			{
				TeCoord2D c(0.2, posd + 0.60);

				gdCanvas_->draw(c, legendTitles[i], 0.0, 0.5, 0.0);

				++currentLinePosition;

				posd = legendVecSize - 1 - currentLinePosition;
			}

			bool hasPOLYGONS = (legends[i][j].getVisualMap().find(TePOLYGONS) != legends[i][j].getVisualMap().end());
			bool hasLINES    = (legends[i][j].getVisualMap().find(TeLINES) != legends[i][j].getVisualMap().end());
			bool hasPOINTS   = (legends[i][j].getVisualMap().find(TePOINTS) != legends[i][j].getVisualMap().end());

			double dx = 0;

			if(hasPOLYGONS)
				dx = 1.75;

			if(hasLINES)
				dx += 1.75;

			if(hasPOINTS)
				dx += 1.75;

			if((j == 0) && legends[i].size() == 1)
			{
				TeCoord2D c(dx, posd + 0.60);

				gdCanvas_->draw(c, legendTitles[i], 0.0, 0.5, 0.0);
			}
			else
			{
				TeCoord2D c(dx, posd + 0.60);

				gdCanvas_->draw(c, legends[i][j].label(), 0.0, 0.5, 0.0);
			}

			if(hasPOLYGONS)
			{
				TeCoord2D c1, c2, c3, c4;
				
				c1.setXY(0.2, posd + 0.15);
				c2.setXY(0.2, posd + 0.9);
				c3.setXY(1.5, posd + 0.9);
				c4.setXY(1.5, posd + 0.15);

				TeLine2D l;
				l.add(c1); l.add(c2); l.add(c3); l.add(c4); l.add(c1);

				TeLinearRing r(l);

				TePolygon p;
				p.add(r);
				
				// Draw the legend polygon
				TeGeomRepVisualMap& visualMap = legends[i][j].getVisualMap();
				TeVisual& polygonVisual = *(visualMap[TePOLYGONS]);
				TeColor& polygonColor = polygonVisual.color();
				TeColor& polygonContourColor = polygonVisual.contourColor();

				gdCanvas_->setPolygonColor(polygonColor.red_, polygonColor.green_, polygonColor.blue_, polygonVisual.transparency());
				gdCanvas_->setPolygonStyle(polygonVisual.style());
				gdCanvas_->setPolygonLineColor(polygonContourColor.red_, polygonContourColor.green_, polygonContourColor.blue_);
				gdCanvas_->setPolygonLineStyle(polygonVisual.contourStyle(), polygonVisual.contourWidth());

				gdCanvas_->draw(p);
			}

			if(hasLINES)
			{
				dx = 0;

				if(hasPOLYGONS)
					dx = 1.75;

				TeCoord2D c1, c2, c3, c4;
				
				c1.setXY(0.2 + dx, posd + 0.15);
				c2.setXY(0.6 + dx, posd + 0.9);
				c3.setXY(1.0 + dx, posd + 0.15);
				c4.setXY(1.5 + dx, posd + 0.9);

				TeLine2D l;
				l.add(c1); l.add(c2); l.add(c3); l.add(c4);

				TeGeomRepVisualMap& visualMap = legends[i][j].getVisualMap();
				TeVisual& lnVisual = *(visualMap[TeLINES]);
				TeColor& lnColor = lnVisual.color();			

				gdCanvas_->setLineColor(lnColor.red_, lnColor.green_, lnColor.blue_);
				gdCanvas_->setLineStyle(lnVisual.style(), lnVisual.width() + 1);
	
				gdCanvas_->draw(l);
			}

			if(hasPOINTS)
			{
				dx = 0;

				if(hasPOLYGONS)
					dx = 1.75;

				if(hasLINES)
					dx += 1.75;

				TeCoord2D c(0.6 + dx, posd + 0.6);
				TePoint pt(c);				

				TeGeomRepVisualMap& visualMap = legends[i][j].getVisualMap();
				TeVisual& ptVisual = *(visualMap[TePOINTS]);
				TeColor& ptColor = ptVisual.color();

				gdCanvas_->setPointColor(ptColor.red_, ptColor.green_, ptColor.blue_);
				gdCanvas_->setPointStyle(ptVisual.style(), ptVisual.size() + 1);
				gdCanvas_->draw(pt);				
			}

			++currentLinePosition;
		}
	}
}
Esempio n. 20
0
/** return cloned graphic path with coordinates modified with crispEdges algorithm
@remarks
	depending on fCreateStorageForCrispEdges status & on VGraphicContext crispEdges status

	return NULL if crispEdges is disabled 
*/
VGraphicPath *VGraphicPath::CloneWithCrispEdges( VGraphicContext *inGC, bool inFillOnly) const
{
	if (inGC == NULL || !inGC->IsShapeCrispEdgesEnabled() || !inGC->IsAllowedCrispEdgesOnPath() || !fCreateStorageForCrispEdges || fDrawCmds.empty())
		return NULL;
	if (fHasBezier && !inGC->IsAllowedCrispEdgesOnBezier())
		return NULL;

	VGraphicPath *path = inGC->CreatePath();
	if (!path)
		return NULL;
	path->fCreateStorageForCrispEdges = false;
	path->Begin();
	VGraphicPathDrawCmds::const_iterator it = fDrawCmds.begin();
	bool isIdentity = fCurTransform.IsIdentity();
	VAffineTransform ctm;
	if (!isIdentity)
	{
		inGC->GetTransform( ctm);
		inGC->SetTransform( fCurTransform * ctm);
	}
	for (;it != fDrawCmds.end(); it++)
	{
		switch (it->GetType())
		{
		case GPDCT_BEGIN_SUBPATH_AT:
			{
			VPoint pt(*(it->GetPoints()));
			inGC->_CEAdjustPointInTransformedSpace( pt, inFillOnly);
			path->BeginSubPathAt( pt);
			}
			break;
		case GPDCT_ADD_LINE_TO:
			{
			VPoint pt(*(it->GetPoints()));
			inGC->_CEAdjustPointInTransformedSpace( pt, inFillOnly);
			path->AddLineTo( pt);
			}
			break;
		case GPDCT_ADD_BEZIER_TO:
			{
			VPoint c1(*(it->GetPoints()));
			VPoint d(*(it->GetPoints()+1));
			VPoint c2(*(it->GetPoints()+2));

			inGC->_CEAdjustPointInTransformedSpace( c1, inFillOnly);
			inGC->_CEAdjustPointInTransformedSpace( d, inFillOnly);
			inGC->_CEAdjustPointInTransformedSpace( c2, inFillOnly);
			path->AddBezierTo( c1, d, c2);
			}
			break;
		case GPDCT_CLOSE_SUBPATH:
			path->CloseSubPath();
			break;
		case GPDCT_ADD_OVAL:
			{
			VRect rect(it->GetRect());
			inGC->_CEAdjustRectInTransformedSpace( rect, inFillOnly);
			path->AddOval( rect);
			}
			break;
		case GPDCT_SET_POS_BY:
			path->SetPosBy( it->GetPoints()->GetX(), it->GetPoints()->GetY());
			break;
		case GPDCT_SET_SIZE_BY:
			path->SetSizeBy( it->GetPoints()->GetX(), it->GetPoints()->GetY());
			break;
		default:
			xbox_assert(false);
			break;
		}
	}
	if (!isIdentity)
		inGC->SetTransform( ctm);
	path->End();
	return path;
}
Esempio n. 21
0
void SkpThemedBase::skp_draw_themed()
{
//    QPainterPath path;
//    path.setFillRule(Qt::WindingFill);
//    path.addRect(10, 10, m_parent->width()-20, m_parent->height()-20);

//    QPainter painter(m_parent);
//    painter.setRenderHint(QPainter::Antialiasing, true);
//    painter.fillPath(path, QBrush(Qt::white));

//    QColor color(0, 0, 0, 50);
//    for(int i=0; i<10; i++)
//    {
//        QPainterPath path;
//        path.setFillRule(Qt::WindingFill);
//        path.addRect(10-i, 10-i, m_parent->width()-(10-i)*2, m_parent->height()-(10-i)*2);
//        color.setAlpha(150 - qSqrt(i)*50);
//        painter.setPen(color);
//        painter.drawPath(path);
//    }



        /*
    QPainter p(m_parent);

    QPen pen(QColor(255, 255, 255, 255));
    pen.setWidth(2);
    pen.setStyle(Qt::NoPen);
    p.setPen(pen);

    QPainterPath path;
    QPoint bottomRight = m_parent->rect().bottomRight();
    QRect pathRect = m_parent->rect();
    pathRect.setBottomRight(QPoint(bottomRight.x()-1, bottomRight.y()-1));
    path.addRoundedRect(pathRect, 0, 0);




    QString themeType = MOption::instance()->option("WindowBGPixmapType", "theme").toString();
    if(themeType == "bitmap") {
        if(!m_cachedPixmap.isNull()) {
            p.fillPath(path, QBrush(m_cachedPixmap));
        } else {
            QColor color(100,178,226,255);
            MOption::instance()->setOption(QVariant(color), "WindowBGColor", "theme");
            MOption::instance()->setOption("color", "WindowBGPixmapType", "theme");
            MOption::instance()->setOption(QVariant(color), OPTION_AVERAGE_COLOR, OPTION_GROUP_Theme);

            p.fillPath(path, color);
        }
    } else if(themeType == "color") {
        QImage image(QSize(100, 100), QImage::Format_ARGB32);
        image.fill(MOption::instance()->option("WindowBGColor", "theme").value<QColor>());
        m_cachedPixmap = setAlphaPixmap(QPixmap::fromImage(image), m_aeroTransparent);
        p.fillPath(path, QBrush(m_cachedPixmap));
    }

    QRect linearRect(0, m_titleHeight, m_parent->width(), m_linearHeight);
    QLinearGradient linear(0, m_titleHeight, 0, m_linearHeight+m_titleHeight);

    QColor c1(255, 255, 255, m_widgetTransparent /2);;
    QColor c2(255, 255, 255, m_widgetTransparent);

    linear.setColorAt(0.0, QColor(255, 255, 255, 255));
    linear.setColorAt(0.5, c1);
    linear.setColorAt(1.0, c2);

    p.setBrush(QBrush(linear));
    p.fillRect(linearRect, QBrush(linear));

    QPainterPath clientPath;
    QRect clientRect(0, m_titleHeight + m_linearHeight,
                     m_parent->width(), m_parent->height() - m_titleHeight - m_linearHeight - m_statusHeight);
    clientPath.addRect(clientRect);
    p.fillPath(clientPath, QBrush(QColor(255, 255, 255, m_widgetTransparent)));

    p.strokePath(path, QPen(QColor(0, 0, 0, 150)));
    */


    QPainter p(m_parent);

    int width = 5;
    QColor color(0, 0, 0, 20);
    for(int i=0; i<width; i++)
    {
        QPainterPath path;
        path.setFillRule(Qt::WindingFill);
        path.addRect(width-i, width-i, m_parent->width()-(width-i)*2, m_parent->height()-(width-i)*2);

        color.setAlpha(60 - qSqrt(i)*30);
        p.setPen(color);
        p.drawPath(path);
    }

    QRect pathRect(width, width, m_parent->rect().width() - width * 2, m_parent->rect().height() - width * 2);
    QPainterPath path;
    path.addRoundedRect(pathRect, 0, 0);



    QString themeType = MOption::instance()->option("WindowBGPixmapType", "theme").toString();
    if(themeType == "bitmap") {
        if(!m_cachedPixmap.isNull()) {
            p.fillPath(path, QBrush(m_cachedPixmap));
        } else {
            QColor color(100,178,226,255);
            MOption::instance()->setOption(QVariant(color), "WindowBGColor", "theme");
            MOption::instance()->setOption("color", "WindowBGPixmapType", "theme");
            MOption::instance()->setOption(QVariant(color), OPTION_AVERAGE_COLOR, OPTION_GROUP_Theme);

            p.fillPath(path, color);
        }
    } else if(themeType == "color") {
        QImage image(QSize(100, 100), QImage::Format_ARGB32);
        image.fill(MOption::instance()->option("WindowBGColor", "theme").value<QColor>());
        m_cachedPixmap = setAlphaPixmap(QPixmap::fromImage(image), m_aeroTransparent);
        p.fillPath(path, QBrush(m_cachedPixmap));
    }

    QRect linearRect(0, m_titleHeight, m_parent->width(), m_linearHeight);
    QLinearGradient linear(0, m_titleHeight, 0, m_linearHeight+m_titleHeight);

    QColor c1(255, 255, 255, m_widgetTransparent /2);;
    QColor c2(255, 255, 255, m_widgetTransparent);

    linear.setColorAt(0.0, QColor(255, 255, 255, 255));
    linear.setColorAt(0.5, c1);
    linear.setColorAt(1.0, c2);

    p.setBrush(QBrush(linear));
    p.fillRect(linearRect, QBrush(linear));

    QPainterPath clientPath;
    QRect clientRect(width, m_titleHeight + m_linearHeight,
                     m_parent->width() - width * 2, m_parent->height() - m_titleHeight - m_linearHeight - m_statusHeight - width * 2);
    clientPath.addRect(clientRect);
    p.fillPath(clientPath, QBrush(QColor(255, 255, 255, m_widgetTransparent)));

}
Esempio n. 22
0
/************** Each round consists of the following:
1. c1.multiplyBy(c0)
2. c0 += random constant
3. c2 *= random constant
4. tmp = c1
5. ea.rotate(tmp, random amount in [-nSlots/2, nSlots/2])
6. c2 += tmp
7. ea.rotate(c2, random amount in [1-nSlots, nSlots-1])
8. c1.negate()
9. c3.multiplyBy(c2) 
10. c0 -= c3
**************/
void testGeneralOps(const FHEPubKey& publicKey, const FHESecKey& secretKey,
                    const EncryptedArrayCx& ea, double epsilon,
                    long nRounds)
{
  long nslots = ea.size();
  char buffer[32];

  vector<cx_double> p0, p1, p2, p3;
  ea.random(p0);
  ea.random(p1);
  ea.random(p2);
  ea.random(p3);

  Ctxt c0(publicKey), c1(publicKey), c2(publicKey), c3(publicKey);
  ea.encrypt(c0, publicKey, p0, /*size=*/1.0);
  ea.encrypt(c1, publicKey, p1, /*size=*/1.0);
  ea.encrypt(c2, publicKey, p2, /*size=*/1.0);
  ea.encrypt(c3, publicKey, p3, /*size=*/1.0);

  resetAllTimers();
  FHE_NTIMER_START(Circuit);

  for (long i = 0; i < nRounds; i++) {

    if (verbose) std::cout << "*** round " << i << "..."<<endl;

     long shamt = RandomBnd(2*(nslots/2) + 1) - (nslots/2);
                  // random number in [-nslots/2..nslots/2]
     long rotamt = RandomBnd(2*nslots - 1) - (nslots - 1);
                  // random number in [-(nslots-1)..nslots-1]

     // two random constants
     vector<cx_double> const1, const2;
     ea.random(const1);
     ea.random(const2);

     ZZX const1_poly, const2_poly;
     ea.encode(const1_poly, const1, /*size=*/1.0);
     ea.encode(const2_poly, const2, /*size=*/1.0);

     mul(p1, p0);     // c1.multiplyBy(c0)
     c1.multiplyBy(c0);
     if (verbose) {
       CheckCtxt(c1, "c1*=c0");
       debugCompare(ea, secretKey, p1, c1, epsilon);
     }

     add(p0, const1); // c0 += random constant
     c0.addConstant(const1_poly);
     if (verbose) {
       CheckCtxt(c0, "c0+=k1");
       debugCompare(ea, secretKey, p0, c0, epsilon);
     }
     mul(p2, const2); // c2 *= random constant
     c2.multByConstant(const2_poly);
     if (verbose) {
       CheckCtxt(c2, "c2*=k2");
       debugCompare(ea, secretKey, p2, c2, epsilon);
     }
     vector<cx_double> tmp_p(p1); // tmp = c1
     Ctxt tmp(c1);
     sprintf(buffer, "tmp=c1>>=%d", (int)shamt);
     rotate(tmp_p, shamt); // ea.shift(tmp, random amount in [-nSlots/2,nSlots/2])
     ea.rotate(tmp, shamt);
     if (verbose) {
       CheckCtxt(tmp, buffer);
       debugCompare(ea, secretKey, tmp_p, tmp, epsilon);
     }
     add(p2, tmp_p);  // c2 += tmp
     c2 += tmp;
     if (verbose) {
       CheckCtxt(c2, "c2+=tmp");
       debugCompare(ea, secretKey, p2, c2, epsilon);
     }
     sprintf(buffer, "c2>>>=%d", (int)rotamt);
     rotate(p2, rotamt); // ea.rotate(c2, random amount in [1-nSlots, nSlots-1])
     ea.rotate(c2, rotamt);
     if (verbose) {
       CheckCtxt(c2, buffer);
       debugCompare(ea, secretKey, p2, c2, epsilon);
     }
     negateVec(p1); // c1.negate()
     c1.negate();
     if (verbose) {
       CheckCtxt(c1, "c1=-c1");
       debugCompare(ea, secretKey, p1, c1, epsilon);
     }
     mul(p3, p2); // c3.multiplyBy(c2) 
     c3.multiplyBy(c2);
     if (verbose) {
       CheckCtxt(c3, "c3*=c2");
       debugCompare(ea, secretKey, p3, c3, epsilon);
     }
     sub(p0, p3); // c0 -= c3
     c0 -= c3;
     if (verbose) {
       CheckCtxt(c0, "c0=-c3");
       debugCompare(ea, secretKey, p0, c0, epsilon);
     }
  }

  c0.cleanUp();
  c1.cleanUp();
  c2.cleanUp();
  c3.cleanUp();

  FHE_NTIMER_STOP(Circuit);

  vector<cx_double> pp0, pp1, pp2, pp3;
   
  ea.decrypt(c0, secretKey, pp0);
  ea.decrypt(c1, secretKey, pp1);
  ea.decrypt(c2, secretKey, pp2);
  ea.decrypt(c3, secretKey, pp3);

  std::cout << "Test "<<nRounds<<" rounds of mixed operations, ";
  if (cx_equals(pp0, p0,conv<double>(epsilon*c0.getPtxtMag()))
      && cx_equals(pp1, p1,conv<double>(epsilon*c1.getPtxtMag()))
      && cx_equals(pp2, p2,conv<double>(epsilon*c2.getPtxtMag()))
      && cx_equals(pp3, p3,conv<double>(epsilon*c3.getPtxtMag())))
    std::cout << "PASS\n\n";
  else {
    std::cout << "FAIL:\n";
    std::cout << "  max(p0)="<<largestCoeff(p0)
              << ", max(pp0)="<<largestCoeff(pp0)
              << ", maxDiff="<<calcMaxDiff(p0,pp0) << endl;
    std::cout << "  max(p1)="<<largestCoeff(p1)
              << ", max(pp1)="<<largestCoeff(pp1)
              << ", maxDiff="<<calcMaxDiff(p1,pp1) << endl;
    std::cout << "  max(p2)="<<largestCoeff(p2)
              << ", max(pp2)="<<largestCoeff(pp2)
              << ", maxDiff="<<calcMaxDiff(p2,pp2) << endl;
    std::cout << "  max(p3)="<<largestCoeff(p3)
              << ", max(pp3)="<<largestCoeff(pp3)
              << ", maxDiff="<<calcMaxDiff(p3,pp3) << endl<<endl;
  }

  if (verbose) {
    std::cout << endl;
    printAllTimers();
    std::cout << endl;
  }
  resetAllTimers();
   }
Esempio n. 23
0
int main()
{
	// test if two ints are equal or not
	cout << "***  Integers Tests  ***" << endl;

	int leftInts[4] = { 1, 2, -1, -1 }; // lhs integers used for testing equality
	int rightInts[4] = { 1, 4, 1, -1 }; // rhs integers used for testing equality
	for (int a = 0; a < 4; a++)
	{
		cout << "Integers: " << leftInts[a] << " and " << rightInts[a] << " are "
			<< (isEqualTo(leftInts[a], rightInts[a]) ? "equal" : "\"NOT\" equal") << '\n';
	}

	// test if two chars are equal or not
	cout << "\n\n***  Chars Tests  ***" << endl;
	char leftChars[4] = { 'a', 'a', 'c', 'c' }; // lhs chars used for testing equality
	char rightChars[4] = { 'a', 'c', 'a', 'c' }; // rhs chars used for testing equality
	for (int a = 0; a < 4; a++)
	{
		cout << "Characters: " << leftChars[a] << " and " << rightChars[a] << " are "
			<< (isEqualTo(leftChars[a], rightChars[a]) ? "equal" : "\"NOT\" equal") << '\n';
	}

	// test if two doubles are equal or not
	cout << "\n\n***  Double Tests  ***" << endl;
	double leftDoubles[4] = { 2.2, 2.2, -2.2, -2.2 }; // lhs integers used for testing equality
	double rightDoubles[4] = { 2.2, 2.3, 2.2, -2.2 }; // rhs integers used for testing equality
	for (int a = 0; a < 4; a++)
	{
		cout << "Double numbers: " << leftDoubles[a] << " and " << rightDoubles[a] << " are "
			<< (isEqualTo(leftDoubles[a], rightDoubles[a]) ? "equal" : "\"NOT\" equal") << '\n';
	}

	// test if two Complex objects are equal
	cout << "\n\n***  Complex Tests  ***" << endl;
	Complex a(10, 5); // Complex objects used
	Complex a1(10, 5); // for testing equality
	cout << "Class objects: " << a << " and " << a1 << " are "
		<< (isEqualTo(a, a1) ? "equal" : "\"NOT\" equal");

	Complex b(10, 5); // Complex objects used
	Complex b1(10, 54); // for testing equality
	cout << "\nClass objects: " << b << " and " << b1 << " are "
		<< (isEqualTo(b, b1) ? "equal" : "\"NOT\" equal");

	Complex c(10, -5); // Complex objects used
	Complex c1(10, 5); // for testing equality
	cout << "\nClass objects: " << c << " and " << c1 << " are "
		<< (isEqualTo(c, c1) ? "equal" : "\"NOT\" equal");

	Complex d(-10, -5); // Complex objects used
	Complex d1(-10, -5); // for testing equality
	cout << "\nClass objects: " << d << " and " << d1 << " are "
		<< (isEqualTo(d, d1) ? "equal" : "\"NOT\" equal");

	//test if two strings are equal or not
	cout << "\n\n\n***  String Tests  ***" << endl;
	string leftStrings[4] = { "abcdefg", "abcdefg", "-abcdefg", "-abcdefg" }; // lhs chars used for testing equality
	string rightStrings[4] = { "abcdefg", "abcdefh", "abcdefg", "-abcdefg" }; // rhs chars used for testing equality
	for (int a = 0; a < 4; a++)
	{
		cout << "String objects: " << leftStrings[a] << " and " << rightStrings[a] << " are "
			<< (isEqualTo(leftStrings[a], rightStrings[a]) ? "equal" : "\"NOT\" equal") << '\n';
	}

	//test if two dates are equal or not
	cout << "\n\n***  Date Tests  ***";
	Date dayA(2, 31, 2016); // create date object
	Date dayB(2, 31, 2016); // create date object
	cout << "\nDate objects: " << dayA << " and " << dayB << " are "
		<< (isEqualTo(dayA, dayB) ? "equal" : "\"NOT\" equal");

	Date dayC(-2, 13, 2016); // create date object
	Date dayD(2, 14, 2016); // create date object
	cout << "\nDate objects: " << dayC << " and " << dayD << " are "
		<< (isEqualTo(dayC, dayD) ? "equal" : "\"NOT\" equal");

	Date dayE(-2, 13, 2016); // create date object
	Date dayF(2, 13, 2016); // create date object
	cout << "\nDate objects: " << dayE << " and " << dayF << " are "
		<< (isEqualTo(dayE, dayF) ? "equal" : "\"NOT\" equal");

	Date dayG(-2, 13, 2016); // create date object
	Date dayH(2, 31, 2016); // create date object
	cout << "\nDate objects: " << dayG << " and " << dayH << " are "
		<< (isEqualTo(dayG, dayH) ? "equal" : "\"NOT\" equal") << '\n';

	cout << endl << endl;
	return 0;
} // end main
Esempio n. 24
0
void testBasicArith(const FHEPubKey& publicKey,
                    const FHESecKey& secretKey,
                    const EncryptedArrayCx& ea, double epsilon)
{
  if (verbose)  cout << "Test Arithmetic ";
  // Test objects

  Ctxt c1(publicKey), c2(publicKey), c3(publicKey);
  
  vector<cx_double> vd;
  vector<cx_double> vd1, vd2, vd3;
  ea.random(vd1);
  ea.random(vd2);

  // test encoding of shorter vectors
  vd1.resize(vd1.size()-2);
  ea.encrypt(c1, publicKey, vd1, /*size=*/1.0);
  vd1.resize(vd1.size()+2, 0.0);

  ea.encrypt(c2, publicKey, vd2, /*size=*/1.0);

  // Test - Multiplication
  c1 *= c2;
  for (long i=0; i<lsize(vd1); i++) vd1[i] *= vd2[i];

  ZZX poly;
  ea.random(vd3);
  ea.encode(poly, vd3, /*size=*/1.0);
  c1.addConstant(poly); // vd1*vd2 + vd3
  for (long i=0; i<lsize(vd1); i++) vd1[i] += vd3[i];

  // Test encoding, encryption of a single number
  double xx = NTL::RandomLen_long(16)/double(1L<<16); // random in [0,1]
  ea.encryptOneNum(c2, publicKey, xx);
  c1 += c2;
  for (auto& x : vd1) x += xx;

  // Test - Multiply by a mask
  vector<long> mask(lsize(vd1), 1);
  for (long i=0; i*(i+1)<lsize(mask); i++) {
    mask[i*i] = 0;
    mask[i*(i+1)] = -1;
  }

  ea.encode(poly,mask, /*size=*/1.0);
  c1.multByConstant(poly); // mask*(vd1*vd2 + vd3)
  for (long i=0; i<lsize(vd1); i++) vd1[i] *= mask[i];

  // Test - Addition
  ea.random(vd3);
  ea.encrypt(c3, publicKey, vd3, /*size=*/1.0);
  c1 += c3;
  for (long i=0; i<lsize(vd1); i++) vd1[i] += vd3[i];

  c1.negate();
  c1.addConstant(to_ZZ(1));
  for (long i=0; i<lsize(vd1); i++) vd1[i] = 1.0 - vd1[i];

  // Diff between approxNums HE scheme and plaintext floating  
  ea.decrypt(c1, secretKey, vd);
#ifdef DEBUG_PRINTOUT
  printVec(cout<<"res=", vd, 10)<<endl;
  printVec(cout<<"vec=", vd1, 10)<<endl;
#endif
  if (verbose)
    cout << "(max |res-vec|_{infty}="<< calcMaxDiff(vd, vd1) << "): ";

  if (cx_equals(vd, vd1, conv<double>(epsilon*c1.getPtxtMag())))
    cout << "GOOD\n";
  else {
    cout << "BAD:\n";
    std::cout << "  max(vd)="<<largestCoeff(vd)
              << ", max(vd1)="<<largestCoeff(vd1)
              << ", maxDiff="<<calcMaxDiff(vd,vd1) << endl<<endl;
  }
}
Esempio n. 25
0
 void operator()(MESH& m, double t) {
     c1(m,t);
     c2(m,t);
 }
Esempio n. 26
0
void testComplexArith(const FHEPubKey& publicKey,
                      const FHESecKey& secretKey,
                      const EncryptedArrayCx& ea, double epsilon)
{

  // Test complex conjugate
  Ctxt c1(publicKey), c2(publicKey);

  vector<cx_double> vd;
  vector<cx_double> vd1, vd2;
  ea.random(vd1);
  ea.random(vd2);
   
  ea.encrypt(c1, publicKey, vd1, /*size=*/1.0);
  ea.encrypt(c2, publicKey, vd2, /*size=*/1.0);

  if (verbose)
    cout << "Test Conjugate: ";
  for_each(vd1.begin(), vd1.end(), [](cx_double& d){d=std::conj(d);});
  c1.complexConj();  
  ea.decrypt(c1, secretKey, vd);
#ifdef DEBUG_PRINTOUT
  printVec(cout<<"vd1=", vd1, 10)<<endl;
  printVec(cout<<"res=", vd, 10)<<endl;
#endif
  if (cx_equals(vd, vd1, conv<double>(epsilon*c1.getPtxtMag())))
    cout << "GOOD\n";
  else {
    cout << "BAD:\n";
    std::cout << "  max(vd)="<<largestCoeff(vd)
              << ", max(vd1)="<<largestCoeff(vd1)
              << ", maxDiff="<<calcMaxDiff(vd,vd1) << endl<<endl;
  }

  // Test that real and imaginary parts are actually extracted.
  Ctxt realCtxt(c2), imCtxt(c2);
  vector<cx_double> realParts(vd2), real_dec;
  vector<cx_double> imParts(vd2), im_dec;

  if (verbose)
    cout << "Test Real and Im parts: ";
  for_each(realParts.begin(), realParts.end(), [](cx_double& d){d=std::real(d);});
  for_each(imParts.begin(), imParts.end(), [](cx_double& d){d=std::imag(d);});

  ea.extractRealPart(realCtxt);
  ea.decrypt(realCtxt, secretKey, real_dec);

  ea.extractImPart(imCtxt);
  ea.decrypt(imCtxt, secretKey, im_dec);

#ifdef DEBUG_PRINTOUT
  printVec(cout<<"vd2=", vd2, 10)<<endl;
  printVec(cout<<"real=", realParts, 10)<<endl;
  printVec(cout<<"res=", real_dec, 10)<<endl;
  printVec(cout<<"im=", imParts, 10)<<endl;
  printVec(cout<<"res=", im_dec, 10)<<endl;
#endif
  if (cx_equals(realParts,real_dec,conv<double>(epsilon*realCtxt.getPtxtMag()))
      && cx_equals(imParts, im_dec, conv<double>(epsilon*imCtxt.getPtxtMag())))
    cout << "GOOD\n";
  else {
    cout << "BAD:\n";
    std::cout << "  max(re)="<<largestCoeff(realParts)
              << ", max(re1)="<<largestCoeff(real_dec)
              << ", maxDiff="<<calcMaxDiff(realParts,real_dec) << endl;
    std::cout << "  max(im)="<<largestCoeff(imParts)
              << ", max(im1)="<<largestCoeff(im_dec)
              << ", maxDiff="<<calcMaxDiff(imParts,im_dec) << endl<<endl;
  }
}
Esempio n. 27
0
int main()
{
    {
        int a1[] = {1, 3, 7, 9, 10};
        int a2[] = {0, 2, 4, 5, 6, 8, 11};
        std::vector<int> c1(a1, a1+sizeof(a1)/sizeof(a1[0]));
        std::vector<int> c2(a2, a2+sizeof(a2)/sizeof(a2[0]));
        assert(is_contiguous_container_asan_correct(c1));
        assert(is_contiguous_container_asan_correct(c2));
        swap(c1, c2);
        assert(c1 == std::vector<int>(a2, a2+sizeof(a2)/sizeof(a2[0])));
        assert(c2 == std::vector<int>(a1, a1+sizeof(a1)/sizeof(a1[0])));
        assert(is_contiguous_container_asan_correct(c1));
        assert(is_contiguous_container_asan_correct(c2));
    }
    {
        int a1[] = {1, 3, 7, 9, 10};
        int a2[] = {0, 2, 4, 5, 6, 8, 11};
        std::vector<int> c1(a1, a1);
        std::vector<int> c2(a2, a2+sizeof(a2)/sizeof(a2[0]));
        assert(is_contiguous_container_asan_correct(c1));
        assert(is_contiguous_container_asan_correct(c2));
        swap(c1, c2);
        assert(c1 == std::vector<int>(a2, a2+sizeof(a2)/sizeof(a2[0])));
        assert(c2.empty());
        assert(distance(c2.begin(), c2.end()) == 0);
        assert(is_contiguous_container_asan_correct(c1));
        assert(is_contiguous_container_asan_correct(c2));
    }
    {
        int a1[] = {1, 3, 7, 9, 10};
        int a2[] = {0, 2, 4, 5, 6, 8, 11};
        std::vector<int> c1(a1, a1+sizeof(a1)/sizeof(a1[0]));
        std::vector<int> c2(a2, a2);
        assert(is_contiguous_container_asan_correct(c1));
        assert(is_contiguous_container_asan_correct(c2));
        swap(c1, c2);
        assert(c1.empty());
        assert(distance(c1.begin(), c1.end()) == 0);
        assert(c2 == std::vector<int>(a1, a1+sizeof(a1)/sizeof(a1[0])));
        assert(is_contiguous_container_asan_correct(c1));
        assert(is_contiguous_container_asan_correct(c2));
    }
    {
        int a1[] = {1, 3, 7, 9, 10};
        int a2[] = {0, 2, 4, 5, 6, 8, 11};
        std::vector<int> c1(a1, a1);
        std::vector<int> c2(a2, a2);
        assert(is_contiguous_container_asan_correct(c1));
        assert(is_contiguous_container_asan_correct(c2));
        swap(c1, c2);
        assert(c1.empty());
        assert(distance(c1.begin(), c1.end()) == 0);
        assert(c2.empty());
        assert(distance(c2.begin(), c2.end()) == 0);
        assert(is_contiguous_container_asan_correct(c1));
        assert(is_contiguous_container_asan_correct(c2));
    }
    {
        int a1[] = {1, 3, 7, 9, 10};
        int a2[] = {0, 2, 4, 5, 6, 8, 11};
        typedef test_allocator<int> A;
        std::vector<int, A> c1(a1, a1+sizeof(a1)/sizeof(a1[0]), A(1, 1));
        std::vector<int, A> c2(a2, a2+sizeof(a2)/sizeof(a2[0]), A(1, 2));
        swap(c1, c2);
        assert((c1 == std::vector<int, A>(a2, a2+sizeof(a2)/sizeof(a2[0]))));
        assert(c1.get_allocator().get_id() == 1);
        assert((c2 == std::vector<int, A>(a1, a1+sizeof(a1)/sizeof(a1[0]))));
        assert(c2.get_allocator().get_id() == 2);
    }
    {
        int a1[] = {1, 3, 7, 9, 10};
        int a2[] = {0, 2, 4, 5, 6, 8, 11};
        typedef other_allocator<int> A;
        std::vector<int, A> c1(a1, a1+sizeof(a1)/sizeof(a1[0]), A(1));
        std::vector<int, A> c2(a2, a2+sizeof(a2)/sizeof(a2[0]), A(2));
        assert(is_contiguous_container_asan_correct(c1));
        assert(is_contiguous_container_asan_correct(c2));
        swap(c1, c2);
        assert((c1 == std::vector<int, A>(a2, a2+sizeof(a2)/sizeof(a2[0]))));
        assert(c1.get_allocator() == A(2));
        assert((c2 == std::vector<int, A>(a1, a1+sizeof(a1)/sizeof(a1[0]))));
        assert(c2.get_allocator() == A(1));
        assert(is_contiguous_container_asan_correct(c1));
        assert(is_contiguous_container_asan_correct(c2));
    }
#if TEST_STD_VER >= 11
    {
        int a1[] = {1, 3, 7, 9, 10};
        int a2[] = {0, 2, 4, 5, 6, 8, 11};
        std::vector<int, min_allocator<int>> c1(a1, a1+sizeof(a1)/sizeof(a1[0]));
        std::vector<int, min_allocator<int>> c2(a2, a2+sizeof(a2)/sizeof(a2[0]));
        assert(is_contiguous_container_asan_correct(c1));
        assert(is_contiguous_container_asan_correct(c2));
        swap(c1, c2);
        assert((c1 == std::vector<int, min_allocator<int>>(a2, a2+sizeof(a2)/sizeof(a2[0]))));
        assert((c2 == std::vector<int, min_allocator<int>>(a1, a1+sizeof(a1)/sizeof(a1[0]))));
        assert(is_contiguous_container_asan_correct(c1));
        assert(is_contiguous_container_asan_correct(c2));
    }
    {
        int a1[] = {1, 3, 7, 9, 10};
        int a2[] = {0, 2, 4, 5, 6, 8, 11};
        std::vector<int, min_allocator<int>> c1(a1, a1);
        std::vector<int, min_allocator<int>> c2(a2, a2+sizeof(a2)/sizeof(a2[0]));
        assert(is_contiguous_container_asan_correct(c1));
        assert(is_contiguous_container_asan_correct(c2));
        swap(c1, c2);
        assert((c1 == std::vector<int, min_allocator<int>>(a2, a2+sizeof(a2)/sizeof(a2[0]))));
        assert(c2.empty());
        assert(distance(c2.begin(), c2.end()) == 0);
        assert(is_contiguous_container_asan_correct(c1));
        assert(is_contiguous_container_asan_correct(c2));
    }
    {
        int a1[] = {1, 3, 7, 9, 10};
        int a2[] = {0, 2, 4, 5, 6, 8, 11};
        std::vector<int, min_allocator<int>> c1(a1, a1+sizeof(a1)/sizeof(a1[0]));
        std::vector<int, min_allocator<int>> c2(a2, a2);
        assert(is_contiguous_container_asan_correct(c1));
        assert(is_contiguous_container_asan_correct(c2));
        swap(c1, c2);
        assert(c1.empty());
        assert(distance(c1.begin(), c1.end()) == 0);
        assert((c2 == std::vector<int, min_allocator<int>>(a1, a1+sizeof(a1)/sizeof(a1[0]))));
        assert(is_contiguous_container_asan_correct(c1));
        assert(is_contiguous_container_asan_correct(c2));
    }
    {
        int a1[] = {1, 3, 7, 9, 10};
        int a2[] = {0, 2, 4, 5, 6, 8, 11};
        std::vector<int, min_allocator<int>> c1(a1, a1);
        std::vector<int, min_allocator<int>> c2(a2, a2);
        assert(is_contiguous_container_asan_correct(c1));
        assert(is_contiguous_container_asan_correct(c2));
        swap(c1, c2);
        assert(c1.empty());
        assert(distance(c1.begin(), c1.end()) == 0);
        assert(c2.empty());
        assert(distance(c2.begin(), c2.end()) == 0);
        assert(is_contiguous_container_asan_correct(c1));
        assert(is_contiguous_container_asan_correct(c2));
    }
#ifndef _LIBCPP_DEBUG_LEVEL
// This test known to result in undefined behavior detected by _LIBCPP_DEBUG_LEVEL >= 1
    {
        int a1[] = {1, 3, 7, 9, 10};
        int a2[] = {0, 2, 4, 5, 6, 8, 11};
        typedef min_allocator<int> A;
        std::vector<int, A> c1(a1, a1+sizeof(a1)/sizeof(a1[0]), A());
        std::vector<int, A> c2(a2, a2+sizeof(a2)/sizeof(a2[0]), A());
        assert(is_contiguous_container_asan_correct(c1));
        assert(is_contiguous_container_asan_correct(c2));
        swap(c1, c2);
        assert((c1 == std::vector<int, A>(a2, a2+sizeof(a2)/sizeof(a2[0]))));
        assert(c1.get_allocator() == A());
        assert((c2 == std::vector<int, A>(a1, a1+sizeof(a1)/sizeof(a1[0]))));
        assert(c2.get_allocator() == A());
        assert(is_contiguous_container_asan_correct(c1));
        assert(is_contiguous_container_asan_correct(c2));
    }
#endif
#endif
}
Esempio n. 28
0
void test01()
{
    // class MyClass : YourClass
    // {
    //     string message = "Hello";
    // }
    try
    {
        CIMName a = "A_class1";
        CIMName b = "A_class2";
        CIMClass c0(a, b);
        CIMClass c1(a, CIMName("A_class2"));
        CIMClass c2(CIMName("A_class1"), b);
        CIMClass c3(b, a);
    }
    catch (InvalidNameException & ine)
    {
        if (verbose)
        {
        cout << "Caught unexpected exception: " << ine.getMessage() << endl;
        }
    }
    try
    {
        //
        //  Invalid class name
        //
        CIMClass class0(CIMName ("//localhost/root/cimv2:MyClass"), 
            CIMName ("YourClass"));

        PEGASUS_TEST_ASSERT(class0.getPath() == 
            CIMObjectPath("//localhost/root/cimv2:MyClass"));
    }
    catch (InvalidNameException & ine)
    {
        if (verbose)
        {
        cout << "Caught expected exception: " << ine.getMessage() << endl;
        }
    }

    CIMClass class1(CIMName ("MyClass"), CIMName ("YourClass"));

    class1
    .addQualifier(CIMQualifier(CIMName ("association"), true))
    .addQualifier(CIMQualifier(CIMName ("q1"), Uint32(55)))
    .addQualifier(CIMQualifier(CIMName ("q2"), String("Hello")))
    .addProperty(CIMProperty(CIMName ("message"), String("Hello")))
    .addProperty(CIMProperty(CIMName ("count"), Uint32(77), 0, CIMName(),
            CIMName("YourClass"), true))
    .addMethod(CIMMethod(CIMName ("isActive"), CIMTYPE_BOOLEAN)
        .addParameter(CIMParameter(CIMName ("hostname"), CIMTYPE_STRING))
        .addParameter(CIMParameter(CIMName ("port"), CIMTYPE_UINT32)));

    // Test the method count function
    PEGASUS_TEST_ASSERT(class1.getClassName().equal(CIMName ("myclass")));
    PEGASUS_TEST_ASSERT(class1.getSuperClassName() == CIMName ("YourClass"));

    PEGASUS_TEST_ASSERT(class1.getMethodCount() ==1);


    // Test the findMethod and isMethod functions
    PEGASUS_TEST_ASSERT(class1.findMethod(
                CIMName ("isActive")) != PEG_NOT_FOUND);
    PEGASUS_TEST_ASSERT(class1.findMethod(
                CIMName ("DoesNotExist")) == PEG_NOT_FOUND);

    PEGASUS_TEST_ASSERT(class1.findMethod(
                CIMName ("isActive")) != PEG_NOT_FOUND);
    PEGASUS_TEST_ASSERT(class1.findMethod(
                CIMName ("DoesNotExist")) == PEG_NOT_FOUND);

    // Now add another method and reconfirm.

    class1.addMethod(CIMMethod(CIMName ("makeActive"), CIMTYPE_BOOLEAN)
    .addParameter(CIMParameter(CIMName ("hostname"), CIMTYPE_STRING))
    .addParameter(CIMParameter(CIMName ("port"), CIMTYPE_UINT32)));

    PEGASUS_TEST_ASSERT(class1.getMethodCount() == 2);

    // Test the findMethod and isMethod functions
    // with two methods defined
    PEGASUS_TEST_ASSERT(class1.findMethod(
                CIMName ("isActive")) != PEG_NOT_FOUND);
    PEGASUS_TEST_ASSERT(class1.findMethod(
                CIMName ("makeActive")) != PEG_NOT_FOUND);

    PEGASUS_TEST_ASSERT(class1.findMethod(
                CIMName ("DoesNotExist")) == PEG_NOT_FOUND);
    PEGASUS_TEST_ASSERT(class1.findMethod(
                CIMName ("isActive")) != PEG_NOT_FOUND);
    PEGASUS_TEST_ASSERT(class1.findMethod(
                CIMName ("makeActive")) != PEG_NOT_FOUND);

    PEGASUS_TEST_ASSERT(class1.findMethod(
                CIMName ("DoesNotExist")) == PEG_NOT_FOUND);


    // Test RemoveMethod function
    Uint32 posMethod;
    posMethod = class1.findMethod(CIMName ("isActive"));
    PEGASUS_TEST_ASSERT(posMethod != PEG_NOT_FOUND);

    class1.removeMethod(posMethod);

    PEGASUS_TEST_ASSERT(class1.findMethod(
                CIMName ("isActive")) == PEG_NOT_FOUND);
    PEGASUS_TEST_ASSERT(class1.getMethodCount() == 1);

    //ATTN: P3 TODO add tests for different case names

    //Qualifier manipulation tests  (find, remove)

    PEGASUS_TEST_ASSERT(class1.findQualifier(CIMName ("q1")) != PEG_NOT_FOUND);
    PEGASUS_TEST_ASSERT(class1.findQualifier(CIMName ("q2")) != PEG_NOT_FOUND);
    PEGASUS_TEST_ASSERT(class1.findQualifier(CIMName ("qx")) == PEG_NOT_FOUND);

    PEGASUS_TEST_ASSERT(class1.findQualifier(CIMName ("q1")) != PEG_NOT_FOUND);
    PEGASUS_TEST_ASSERT(class1.findQualifier(CIMName ("q2")) != PEG_NOT_FOUND);
    PEGASUS_TEST_ASSERT(class1.findQualifier(
                CIMName ("association")) != PEG_NOT_FOUND);
    PEGASUS_TEST_ASSERT(class1.isAssociation());

    // Remove middle Qualifier "q2"
    Uint32 posQualifier;
    posQualifier = class1.findQualifier(CIMName ("q2"));
    CIMConstQualifier qconst = class1.getQualifier(posQualifier);

    PEGASUS_TEST_ASSERT(class1.getQualifierCount() == 3);
    PEGASUS_TEST_ASSERT(posQualifier <= class1.getQualifierCount());
    class1.removeQualifier(posQualifier);
    PEGASUS_TEST_ASSERT(class1.getQualifierCount() == 2);

    PEGASUS_TEST_ASSERT(class1.findQualifier(CIMName ("q2")) == PEG_NOT_FOUND);
    PEGASUS_TEST_ASSERT(class1.findQualifier(CIMName ("q1")) != PEG_NOT_FOUND);
    PEGASUS_TEST_ASSERT(class1.isAssociation());


    // Remove the first parameter "q1"
    posQualifier = class1.findQualifier(CIMName ("q1"));

    PEGASUS_TEST_ASSERT(class1.getQualifierCount() == 2);
    CIMQualifier cq = class1.getQualifier( class1.findQualifier(
                CIMName ("q1")));
    PEGASUS_TEST_ASSERT(posQualifier <= class1.getQualifierCount());
    class1.removeQualifier(posQualifier);
    PEGASUS_TEST_ASSERT(class1.getQualifierCount() == 1);

    PEGASUS_TEST_ASSERT(class1.findQualifier(CIMName ("q1")) == PEG_NOT_FOUND);
    PEGASUS_TEST_ASSERT(class1.findQualifier(CIMName ("q2")) == PEG_NOT_FOUND);
    PEGASUS_TEST_ASSERT(class1.isAssociation());


    // ATTH: P3 Add tests for try block for outofbounds



    //The property manipulation tests.

    PEGASUS_TEST_ASSERT(class1.findProperty(
                CIMName ("count")) != PEG_NOT_FOUND);
    PEGASUS_TEST_ASSERT(class1.findProperty(
                CIMName ("message")) != PEG_NOT_FOUND);

    PEGASUS_TEST_ASSERT(class1.findProperty(
                CIMName ("isActive")) == PEG_NOT_FOUND);

    PEGASUS_TEST_ASSERT(class1.getPropertyCount() == 2);


    Uint32  posProperty;
    posProperty = class1.findProperty(CIMName ("count"));
    CIMConstProperty constprop = class1.getProperty(posProperty);
    PEGASUS_TEST_ASSERT(constprop.getClassOrigin() == CIMName("YourClass"));
    PEGASUS_TEST_ASSERT(constprop.getPropagated());
    class1.removeProperty(posProperty);
    PEGASUS_TEST_ASSERT(class1.findProperty(
                CIMName ("message")) != PEG_NOT_FOUND);
    PEGASUS_TEST_ASSERT(class1.findProperty(
                CIMName ("count")) == PEG_NOT_FOUND);

    PEGASUS_TEST_ASSERT(class1.getPropertyCount() == 1);
    CIMProperty cp = class1.getProperty( class1.findProperty
        (CIMName ("message")));
    PEGASUS_TEST_ASSERT(cp.getClassOrigin().isNull());
    PEGASUS_TEST_ASSERT(!cp.getPropagated());

    if(verbose)
    {
        XmlWriter::printClassElement(class1);
        MofWriter::printClassElement(class1);
    }

    Buffer out;
    MofWriter::appendClassElement(out, class1);
    out.clear();
    XmlWriter::appendClassElement(out, class1);
    
    PEGASUS_TEST_ASSERT(!class1.isAbstract());

    CIMName squal("q1");
    PEGASUS_TEST_ASSERT(class1.findQualifier(squal) == PEG_NOT_FOUND);
    
    PEGASUS_TEST_ASSERT(!class1.hasKeys());
    
    Array<CIMName> keyNames;
    class1.getKeyNames(keyNames);

    CIMClass c2(CIMName ("MyClass"));

    PEGASUS_TEST_ASSERT(c2.getClassName().equal(CIMName ("myclass")));


    // Error uninitialized handle
    c2.setSuperClassName(CIMName ("CIM_Element"));
    PEGASUS_TEST_ASSERT(c2.getSuperClassName() == CIMName ("CIM_Element"));

    CIMClass c3 = c2.clone();
    c3 = c2;


    try
    {
        CIMMethod cm = c2.getMethod(0);
    }
    catch(IndexOutOfBoundsException& e)
    {
        if(verbose)
            cout << "Exception: " << e.getMessage() << endl;
    }

    const CIMClass c4(CIMName ("MyClass"), CIMName ("YourClass"));

    CIMConstClass c5(CIMName ("MyClass"), CIMName ("YourClass"));
    CIMConstClass c6(CIMName ("MyClass"));
    CIMConstClass cc7(c6);
    CIMClass c7 = c5.clone();
    const CIMClass c8(class1);

    // Test the findMethod and isMethod functions
    PEGASUS_TEST_ASSERT(c7.findMethod(
                CIMName ("DoesNotExist")) == PEG_NOT_FOUND);

    PEGASUS_TEST_ASSERT(c7.findQualifier(CIMName ("dummy")) == PEG_NOT_FOUND);

    try
    {
        CIMConstMethod cm = c8.getMethod(0);
    }
    catch(IndexOutOfBoundsException& e)
    {
        if(verbose)
            cout << "Exception: " << e.getMessage() << endl;
    }

    try
    {
        CIMConstProperty ccp = c8.getProperty(c8.findProperty
            (CIMName ("count")));
    }
    catch(IndexOutOfBoundsException& e)
    {
        if(verbose)
            cout << "Exception: " << e.getMessage() << endl;
    }

    if(verbose) 
    {
    XmlWriter::printClassElement(c5);
    }

    try
    {
        CIMConstMethod cm = cc7.getMethod(0);
    }
    catch(IndexOutOfBoundsException& e)
    {
    if(verbose)
        cout << "Exception: " << e.getMessage() << endl;
    }
    // Test the findMethod and isMethod functions
    PEGASUS_TEST_ASSERT(c4.findMethod(
                CIMName ("DoesNotExist")) == PEG_NOT_FOUND);

    //Qualifier manipulation tests  (find, remove)

    PEGASUS_TEST_ASSERT(c4.findQualifier(CIMName ("qx")) == PEG_NOT_FOUND);

    PEGASUS_TEST_ASSERT(c4.findQualifier(CIMName ("q1")) == PEG_NOT_FOUND);
    PEGASUS_TEST_ASSERT(c4.findQualifier(CIMName ("q2")) == PEG_NOT_FOUND);
    PEGASUS_TEST_ASSERT(c4.findQualifier(
                CIMName ("association")) == PEG_NOT_FOUND);

    posProperty = c4.findProperty(CIMName ("count"));

    try
    {
        CIMConstQualifier ccq = c4.getQualifier(c4.findQualifier
            (CIMName ("q1")));
    }
    catch (IndexOutOfBoundsException& e)
    {
        if(verbose)
            cout << "Exception: " << e.getMessage() << endl;
    }

    PEGASUS_TEST_ASSERT(c4.findProperty(CIMName ("count")) == PEG_NOT_FOUND);

    PEGASUS_TEST_ASSERT(c4.getClassName() == CIMName ("MyClass"));
    PEGASUS_TEST_ASSERT(c4.getClassName().equal(CIMName ("MyClass")));
    PEGASUS_TEST_ASSERT(c4.getClassName().equal(CIMName ("MYCLASS")));
    PEGASUS_TEST_ASSERT(c4.getClassName().equal(CIMName ("myclass")));
    PEGASUS_TEST_ASSERT(!c4.getClassName().equal(CIMName ("blob")));


    PEGASUS_TEST_ASSERT(c4.getSuperClassName() == CIMName ("YourClass"));

    // test the setSuperClassName function
    /* ATTN KS 29 April.  This test has problems.  Relook later. 
      Think test, not code.
    c4.setSuperClassName(CIMName ("JunkClass")); 
    PEGASUS_TEST_ASSERT(c4.getSuperClassName() == CIMName ("JunkClass")); 
    c4.setSuperClassName(CIMName ("YourClass"));
    */
    PEGASUS_TEST_ASSERT(c5.getSuperClassName() == CIMName ("YourClass"));

    PEGASUS_TEST_ASSERT(c5.getQualifierCount() == 0);
    posQualifier = c5.findQualifier(CIMName ("q2"));

    // throws out of bounds
    try
    {
        CIMConstQualifier qconst1 = c5.getQualifier(posQualifier);
    }
    catch(IndexOutOfBoundsException& e)
    {
        if(verbose)
            cout << "Exception: " << e.getMessage() << endl;
    }
    if(verbose)
    {
        cout << "All tests" << endl;
    }
}
Esempio n. 29
0
void GSVertexTrace::FindMinMax(const void* vertex, const uint32* index, int count)
{
	const GSDrawingContext* context = m_state->m_context;

	int n = 1;

	switch(primclass)
	{
	case GS_POINT_CLASS:
		n = 1;
		break;
	case GS_LINE_CLASS:
	case GS_SPRITE_CLASS:
		n = 2;
		break;
	case GS_TRIANGLE_CLASS:
		n = 3;
		break;
	}

	GSVector4 tmin = s_minmax.xxxx();
	GSVector4 tmax = s_minmax.yyyy();
	GSVector4i cmin = GSVector4i::xffffffff();
	GSVector4i cmax = GSVector4i::zero();

	#if _M_SSE >= 0x401

	GSVector4i pmin = GSVector4i::xffffffff();
	GSVector4i pmax = GSVector4i::zero();

	#else

	GSVector4 pmin = s_minmax.xxxx();
	GSVector4 pmax = s_minmax.yyyy();
	
	#endif

	const GSVertex* RESTRICT v = (GSVertex*)vertex;

	for(int i = 0; i < count; i += n)
	{
		if(primclass == GS_POINT_CLASS)
		{
			GSVector4i c(v[index[i]].m[0]);

			if(color)
			{
				cmin = cmin.min_u8(c);
				cmax = cmax.max_u8(c);
			}

			if(tme)
			{
				if(!fst)
				{
					GSVector4 stq = GSVector4::cast(c);

					GSVector4 q = stq.wwww();

					stq = (stq.xyww() * q.rcpnr()).xyww(q);

					tmin = tmin.min(stq);
					tmax = tmax.max(stq);
				}
				else
				{
					GSVector4i uv(v[index[i]].m[1]);

					GSVector4 st = GSVector4(uv.uph16()).xyxy();

					tmin = tmin.min(st);
					tmax = tmax.max(st);
				}
			}

			GSVector4i xyzf(v[index[i]].m[1]);

			GSVector4i xy = xyzf.upl16();
			GSVector4i z = xyzf.yyyy();

			#if _M_SSE >= 0x401

			GSVector4i p = xy.blend16<0xf0>(z.uph32(xyzf));

			pmin = pmin.min_u32(p);
			pmax = pmax.max_u32(p);

			#else

			GSVector4 p = GSVector4(xy.upl64(z.srl32(1).upl32(xyzf.wwww())));

			pmin = pmin.min(p);
			pmax = pmax.max(p);

			#endif
		}
		else if(primclass == GS_LINE_CLASS)
		{
			GSVector4i c0(v[index[i + 0]].m[0]);
			GSVector4i c1(v[index[i + 1]].m[0]);

			if(color)
			{
				if(iip)
				{
					cmin = cmin.min_u8(c0.min_u8(c1));
					cmax = cmax.max_u8(c0.max_u8(c1));
				}
				else
				{
					cmin = cmin.min_u8(c1);
					cmax = cmax.max_u8(c1);
				}
			}

			if(tme)
			{
				if(!fst)
				{
					GSVector4 stq0 = GSVector4::cast(c0);
					GSVector4 stq1 = GSVector4::cast(c1);

					GSVector4 q = stq0.wwww(stq1).rcpnr();

					stq0 = (stq0.xyww() * q.xxxx()).xyww(stq0);
					stq1 = (stq1.xyww() * q.zzzz()).xyww(stq1);

					tmin = tmin.min(stq0.min(stq1));
					tmax = tmax.max(stq0.max(stq1));
				}
				else
				{
					GSVector4i uv0(v[index[i + 0]].m[1]);
					GSVector4i uv1(v[index[i + 1]].m[1]);

					GSVector4 st0 = GSVector4(uv0.uph16()).xyxy();
					GSVector4 st1 = GSVector4(uv1.uph16()).xyxy();

					tmin = tmin.min(st0.min(st1));
					tmax = tmax.max(st0.max(st1));
				}
			}

			GSVector4i xyzf0(v[index[i + 0]].m[1]);
			GSVector4i xyzf1(v[index[i + 1]].m[1]);

			GSVector4i xy0 = xyzf0.upl16();
			GSVector4i z0 = xyzf0.yyyy();
			GSVector4i xy1 = xyzf1.upl16();
			GSVector4i z1 = xyzf1.yyyy();

			#if _M_SSE >= 0x401

			GSVector4i p0 = xy0.blend16<0xf0>(z0.uph32(xyzf0));
			GSVector4i p1 = xy1.blend16<0xf0>(z1.uph32(xyzf1));

			pmin = pmin.min_u32(p0.min_u32(p1));
			pmax = pmax.max_u32(p0.max_u32(p1));

			#else

			GSVector4 p0 = GSVector4(xy0.upl64(z0.srl32(1).upl32(xyzf0.wwww())));
			GSVector4 p1 = GSVector4(xy1.upl64(z1.srl32(1).upl32(xyzf1.wwww())));

			pmin = pmin.min(p0.min(p1));
			pmax = pmax.max(p0.max(p1));

			#endif
		}
		else if(primclass == GS_TRIANGLE_CLASS)
		{
			GSVector4i c0(v[index[i + 0]].m[0]);
			GSVector4i c1(v[index[i + 1]].m[0]);
			GSVector4i c2(v[index[i + 2]].m[0]);

			if(color)
			{
				if(iip)
				{
					cmin = cmin.min_u8(c2).min_u8(c0.min_u8(c1));
					cmax = cmax.max_u8(c2).max_u8(c0.max_u8(c1));
				}
				else
				{
					cmin = cmin.min_u8(c2);
					cmax = cmax.max_u8(c2);
				}
			}

			if(tme)
			{
				if(!fst)
				{
					GSVector4 stq0 = GSVector4::cast(c0);
					GSVector4 stq1 = GSVector4::cast(c1);
					GSVector4 stq2 = GSVector4::cast(c2);

					GSVector4 q = stq0.wwww(stq1).xzww(stq2).rcpnr();

					stq0 = (stq0.xyww() * q.xxxx()).xyww(stq0);
					stq1 = (stq1.xyww() * q.yyyy()).xyww(stq1);
					stq2 = (stq2.xyww() * q.zzzz()).xyww(stq2);

					tmin = tmin.min(stq2).min(stq0.min(stq1));
					tmax = tmax.max(stq2).max(stq0.max(stq1));
				}
				else
				{
					GSVector4i uv0(v[index[i + 0]].m[1]);
					GSVector4i uv1(v[index[i + 1]].m[1]);
					GSVector4i uv2(v[index[i + 2]].m[1]);

					GSVector4 st0 = GSVector4(uv0.uph16()).xyxy();
					GSVector4 st1 = GSVector4(uv1.uph16()).xyxy();
					GSVector4 st2 = GSVector4(uv2.uph16()).xyxy();

					tmin = tmin.min(st2).min(st0.min(st1));
					tmax = tmax.max(st2).max(st0.max(st1));
				}
			}

			GSVector4i xyzf0(v[index[i + 0]].m[1]);
			GSVector4i xyzf1(v[index[i + 1]].m[1]);
			GSVector4i xyzf2(v[index[i + 2]].m[1]);

			GSVector4i xy0 = xyzf0.upl16();
			GSVector4i z0 = xyzf0.yyyy();
			GSVector4i xy1 = xyzf1.upl16();
			GSVector4i z1 = xyzf1.yyyy();
			GSVector4i xy2 = xyzf2.upl16();
			GSVector4i z2 = xyzf2.yyyy();

			#if _M_SSE >= 0x401

			GSVector4i p0 = xy0.blend16<0xf0>(z0.uph32(xyzf0));
			GSVector4i p1 = xy1.blend16<0xf0>(z1.uph32(xyzf1));
			GSVector4i p2 = xy2.blend16<0xf0>(z2.uph32(xyzf2));

			pmin = pmin.min_u32(p2).min_u32(p0.min_u32(p1));
			pmax = pmax.max_u32(p2).max_u32(p0.max_u32(p1));

			#else

			GSVector4 p0 = GSVector4(xy0.upl64(z0.srl32(1).upl32(xyzf0.wwww())));
			GSVector4 p1 = GSVector4(xy1.upl64(z1.srl32(1).upl32(xyzf1.wwww())));
			GSVector4 p2 = GSVector4(xy2.upl64(z2.srl32(1).upl32(xyzf2.wwww())));

			pmin = pmin.min(p2).min(p0.min(p1));
			pmax = pmax.max(p2).max(p0.max(p1));

			#endif
		}
		else if(primclass == GS_SPRITE_CLASS)
		{
			GSVector4i c0(v[index[i + 0]].m[0]);
			GSVector4i c1(v[index[i + 1]].m[0]);

			if(color)
			{
				if(iip)
				{
					cmin = cmin.min_u8(c0.min_u8(c1));
					cmax = cmax.max_u8(c0.max_u8(c1));
				}
				else
				{
					cmin = cmin.min_u8(c1);
					cmax = cmax.max_u8(c1);
				}
			}

			if(tme)
			{
				if(!fst)
				{
					GSVector4 stq0 = GSVector4::cast(c0);
					GSVector4 stq1 = GSVector4::cast(c1);

					GSVector4 q = stq1.wwww().rcpnr();

					stq0 = (stq0.xyww() * q).xyww(stq1);
					stq1 = (stq1.xyww() * q).xyww(stq1);

					tmin = tmin.min(stq0.min(stq1));
					tmax = tmax.max(stq0.max(stq1));
				}
				else
				{
					GSVector4i uv0(v[index[i + 0]].m[1]);
					GSVector4i uv1(v[index[i + 1]].m[1]);

					GSVector4 st0 = GSVector4(uv0.uph16()).xyxy();
					GSVector4 st1 = GSVector4(uv1.uph16()).xyxy();

					tmin = tmin.min(st0.min(st1));
					tmax = tmax.max(st0.max(st1));
				}
			}

			GSVector4i xyzf0(v[index[i + 0]].m[1]);
			GSVector4i xyzf1(v[index[i + 1]].m[1]);

			GSVector4i xy0 = xyzf0.upl16();
			GSVector4i z0 = xyzf0.yyyy();
			GSVector4i xy1 = xyzf1.upl16();
			GSVector4i z1 = xyzf1.yyyy();

			#if _M_SSE >= 0x401

			GSVector4i p0 = xy0.blend16<0xf0>(z0.uph32(xyzf1));
			GSVector4i p1 = xy1.blend16<0xf0>(z1.uph32(xyzf1));

			pmin = pmin.min_u32(p0.min_u32(p1));
			pmax = pmax.max_u32(p0.max_u32(p1));

			#else

			GSVector4 p0 = GSVector4(xy0.upl64(z0.srl32(1).upl32(xyzf1.wwww())));
			GSVector4 p1 = GSVector4(xy1.upl64(z1.srl32(1).upl32(xyzf1.wwww())));

			pmin = pmin.min(p0.min(p1));
			pmax = pmax.max(p0.max(p1));

			#endif
		}
	}

	#if _M_SSE >= 0x401

	pmin = pmin.blend16<0x30>(pmin.srl32(1));
	pmax = pmax.blend16<0x30>(pmax.srl32(1));

	#endif

	GSVector4 o(context->XYOFFSET);
	GSVector4 s(1.0f / 16, 1.0f / 16, 2.0f, 1.0f);

	m_min.p = (GSVector4(pmin) - o) * s;
	m_max.p = (GSVector4(pmax) - o) * s;

	if(tme)
	{
		if(fst)
		{
			s = GSVector4(1.0f / 16, 1.0f).xxyy();
		}
		else
		{
			s = GSVector4(1 << context->TEX0.TW, 1 << context->TEX0.TH, 1, 1);
		}

		m_min.t = tmin * s;
		m_max.t = tmax * s;
	}
	else
	{
		m_min.t = GSVector4::zero();
		m_max.t = GSVector4::zero();
	}

	if(color)
	{
		m_min.c = cmin.zzzz().u8to32();
		m_max.c = cmax.zzzz().u8to32();
	}
	else
	{
		m_min.c = GSVector4i::zero();
		m_max.c = GSVector4i::zero();
	}
}
Esempio n. 30
0
int main(int argc, char* args[]) {
	Renderer* renderer = new Renderer();

	if(!renderer->init()) {
		printf( "Failed to initialize!\n" );
	} else {
		Character* c = new Character(new Texture("res/img/dot.bmp", 200, 200));
		renderer->addTexture(new Texture("res/img/waterlevel2.png", 0, 0));

		renderer->render();

		renderer->addTexture(c->getTexture());

		bool quit = false;

		SDL_Event e;

		LoadCollisionMap lcm;
		list<Circle> circlesList;
		circlesList = lcm.load();

		list<Circle> l;
		Circle c1(200,0,10);
		l.push_back(c1);

		CollisionDetector cd;
		int y = 0;

		while(!cd.hasCollision(circlesList, l)) {
			l.pop_back();
			y += 1;
			Circle c1(200,y,10);
			l.push_back(c1);
		}
		y -= 1;
		c->setPosX(200);
		c->setPosY(y);

		renderer->render();

		int mVelX = 0;
		int DOT_VEL = 1;

		while(!quit) {
			while(SDL_PollEvent(&e) != 0) {
				if(e.type == SDL_QUIT) {
					quit = true;
				}
				if(e.type == SDL_KEYDOWN && e.key.repeat == 0) {
					switch(e.key.keysym.sym) {
						case SDLK_LEFT: mVelX -= DOT_VEL; break;
						case SDLK_RIGHT: mVelX += DOT_VEL; break;
					}
				} else if(e.type == SDL_KEYUP && e.key.repeat == 0) {
					switch(e.key.keysym.sym) {
						case SDLK_LEFT: mVelX += DOT_VEL; break;
						case SDLK_RIGHT: mVelX -= DOT_VEL; break;
					}
				}
			}
			c->setPosX(c->getPosX() + mVelX);


			LoadCollisionMap lcm;
			list<Circle> circlesList;
			circlesList = lcm.load();

			int mPosX = c->getPosX();
			int mPosY = c->getPosY();

			list<Circle> l;
			Circle c1(mPosX,mPosY,10);
			l.push_back(c1);

			CollisionDetector cd;
			int y = mPosY;
			while(cd.hasCollision(circlesList, l)) {
				l.pop_back();
				y -= 1;
				Circle c1(mPosX,y,10);
				l.push_back(c1);
			};
			while(!cd.hasCollision(circlesList, l)) {
				l.pop_back();
				y += 1;
				Circle c1(mPosX,y,10);
				l.push_back(c1);
			};

			c->setPosY(y);

			renderer->render();
		}
	}
	return 0;
}