feature_extractor.cpp 10.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include "feature_extractor.h"
#include <rcsc/common/logger.h>
#include <rcsc/common/server_param.h>
#include <sstream>

using namespace rcsc;

12 13 14 15 16 17 18
FeatureExtractor::FeatureExtractor(int num_teammates,
                                   int num_opponents,
                                   bool playing_offense) :
    numFeatures(-1),
    numTeammates(num_teammates),
    numOpponents(num_opponents),
    playingOffense(playing_offense)
19 20 21 22 23 24 25 26 27 28 29 30 31
{
  const ServerParam& SP = ServerParam::i();

  // Grab the field dimensions
  pitchLength = SP.pitchLength();
  pitchWidth = SP.pitchWidth();
  pitchHalfLength = SP.pitchHalfLength();
  pitchHalfWidth = SP.pitchHalfWidth();
  goalHalfWidth = SP.goalHalfWidth();
  penaltyAreaLength = SP.penaltyAreaLength();
  penaltyAreaWidth = SP.penaltyAreaWidth();

  // Maximum possible radius in HFO
32 33
  maxHFODist = sqrtf(pitchHalfLength * pitchHalfLength +
                       pitchWidth * pitchWidth);
34 35 36 37 38
}

FeatureExtractor::~FeatureExtractor() {}

void FeatureExtractor::LogFeatures() {
39
#ifdef ELOG
40 41 42 43 44 45 46
  assert(feature_vec.size() == numFeatures);
  std::stringstream ss;
  for (int i=0; i<numFeatures; ++i) {
    ss << feature_vec[i] << " ";
  }
  elog.addText(Logger::WORLD, "StateFeatures %s", ss.str().c_str());
  elog.flush();
47
#endif
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
}

void FeatureExtractor::addAngFeature(const rcsc::AngleDeg& ang) {
  addFeature(ang.sin());
  addFeature(ang.cos());
}

void FeatureExtractor::addDistFeature(float dist, float maxDist) {
  float proximity = 1.f - std::max(0.f, std::min(1.f, dist/maxDist));
  addNormFeature(proximity, 0., 1.);
}

// Add the angle and distance to the landmark to the feature_vec
void FeatureExtractor::addLandmarkFeatures(const rcsc::Vector2D& landmark,
                                           const rcsc::Vector2D& self_pos,
                                           const rcsc::AngleDeg& self_ang) {
  if (self_pos == Vector2D::INVALIDATED) {
    addFeature(0);
    addFeature(0);
    addFeature(0);
  } else {
    Vector2D vec_to_landmark = landmark - self_pos;
70
    addAngFeature(vec_to_landmark.th() - self_ang);
71
    addDistFeature(vec_to_landmark.r(), maxHFODist);
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
  }
}

void FeatureExtractor::addPlayerFeatures(rcsc::PlayerObject& player,
                                         const rcsc::Vector2D& self_pos,
                                         const rcsc::AngleDeg& self_ang) {
  assert(player.posValid());
  // Angle dist to player.
  addLandmarkFeatures(player.pos(), self_pos, self_ang);
  // Player's body angle
  addAngFeature(player.body());
  if (player.velValid()) {
    // Player's speed
    addNormFeature(player.vel().r(), 0., observedPlayerSpeedMax);
    // Player's velocity direction
    addAngFeature(player.vel().th());
  } else {
    addFeature(0);
    addFeature(0);
    addFeature(0);
  }
}

void FeatureExtractor::addFeature(float val) {
  assert(featIndx < numFeatures);
  feature_vec[featIndx++] = val;
}

100
float FeatureExtractor::normalize(float val, float min_val, float max_val) {
101 102
  if (val < min_val || val > max_val) {
    std::cout << "Feature " << featIndx << " Violated Feature Bounds: " << val
103 104
              << " Expected min/max: [" << min_val << ", "
              << max_val << "]" << std::endl;
105 106
    val = std::min(std::max(val, min_val), max_val);
  }
107
  return ((val - min_val) / (max_val - min_val))
108 109 110
      * (FEAT_MAX - FEAT_MIN) + FEAT_MIN;
}

111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
float FeatureExtractor::unnormalize(float val, float min_val, float max_val) {
  if (val < FEAT_MIN || val > FEAT_MAX) {
    std::cout << "Unnormalized value Violated Feature Bounds: " << val
              << " Expected min/max: [" << FEAT_MIN << ", "
              << FEAT_MAX << "]" << std::endl;
    float ft_max = FEAT_MAX; // Linker error on OSX otherwise...?
    float ft_min = FEAT_MIN;
    val = std::min(std::max(val, ft_min), ft_max);
  }
  return ((val - FEAT_MIN) / (FEAT_MAX - FEAT_MIN))
      * (max_val - min_val) + min_val;
}

void FeatureExtractor::addNormFeature(float val, float min_val, float max_val) {
  assert(featIndx < numFeatures);
  feature_vec[featIndx++] = normalize(val, min_val, max_val);
}

129 130 131
void FeatureExtractor::checkFeatures() {
  assert(feature_vec.size() == numFeatures);
  for (int i=0; i<numFeatures; ++i) {
132 133 134
    if (feature_vec[i] == FEAT_INVALID) {
      continue;
    }
135 136 137 138 139 140
    if (feature_vec[i] < FEAT_MIN || feature_vec[i] > FEAT_MAX) {
      std::cout << "Invalid Feature! Indx:" << i << " Val:" << feature_vec[i] << std::endl;
      exit(1);
    }
  }
}
141 142 143

bool FeatureExtractor::valid(const rcsc::PlayerObject& player) {
  const rcsc::Vector2D& pos = player.pos();
144
  if (!player.posValid()) {
145 146
    return false;
  }
147
  return pos.isValid();
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
}

float FeatureExtractor::angleToPoint(const rcsc::Vector2D &self,
                                     const rcsc::Vector2D &point) {
  return (point - self).th().radian();
}

void FeatureExtractor::angleDistToPoint(const rcsc::Vector2D &self,
                                        const rcsc::Vector2D &point,
                                        float &ang, float &dist) {
  Vector2D d = point - self;
  ang = d.th().radian();
  dist = d.r();
}

float FeatureExtractor::angleBetween3Points(const rcsc::Vector2D &point1,
                                            const rcsc::Vector2D &centerPoint,
                                            const rcsc::Vector2D &point2) {
  Vector2D diff1 = point1 - centerPoint;
  Vector2D diff2 = point2 - centerPoint;
  float angle1 = atan2(diff1.y,diff1.x);
  float angle2 = atan2(diff2.y,diff2.x);
  return fabs(angle1 - angle2);
}

void FeatureExtractor::calcClosestOpp(const rcsc::WorldModel &wm,
                                      const rcsc::Vector2D &point,
                                      float &ang, float &minDist) {
  minDist = std::numeric_limits<float>::max();
  const PlayerCont& opps = wm.opponents();
  for (PlayerCont::const_iterator it=opps.begin(); it != opps.end(); ++it) {
    const PlayerObject& opponent = *it;
    if (valid(opponent)) {
      float dist;
      float th;
      angleDistToPoint(point, opponent.pos(), th, dist);
      if (dist < minDist) {
        minDist = dist;
        ang = th;
      }
    }
  }
}

float FeatureExtractor::calcLargestTeammateAngle(const rcsc::WorldModel &wm,
                                                 const rcsc::Vector2D &self,
                                                 const Vector2D &teammate) {
  float angTeammate = angleToPoint(self, teammate);
  float angTop = angTeammate + M_PI / 4;
  float angBot = angTeammate - M_PI / 4;
  return calcLargestOpenAngle(wm, self, angTop, angBot, (self - teammate).r());
}

float FeatureExtractor::calcLargestGoalAngle(const rcsc::WorldModel &wm,
                                             const rcsc::Vector2D &self) {
  const rcsc::ServerParam & SP = rcsc::ServerParam::i();
  Vector2D goalPostTop(SP.pitchHalfLength(), SP.goalHalfWidth());
  Vector2D goalPostBot(SP.pitchHalfLength(), -SP.goalHalfWidth());
  float angTop = angleToPoint(self, goalPostTop);
  float angBot = angleToPoint(self, goalPostBot);
  //std::cout << "starting: " << RAD_T_DEG * angTop << " " << RAD_T_DEG * angBot << std::endl;
  float res = calcLargestOpenAngle(wm, self, angTop, angBot, 99999);
  //std::cout << angTop << " " << angBot << " | " << res << std::endl;
  return res;
}

float FeatureExtractor::calcLargestOpenAngle(const rcsc::WorldModel &wm,
                                             const rcsc::Vector2D &self,
                                             float angTop, float angBot,
                                             float maxDist) {
  const rcsc::ServerParam & SP = rcsc::ServerParam::i();
  std::vector<OpenAngle> openAngles;
  openAngles.push_back(OpenAngle(angBot,angTop));
  const PlayerCont& opps = wm.opponents();
  for (PlayerCont::const_iterator it=opps.begin(); it != opps.end(); ++it) {
    const PlayerObject& opp = *it;
    if (valid(opp)) {
      float oppAngle, oppDist;
      angleDistToPoint(self, opp.pos(), oppAngle, oppDist);
      // theta = arctan (opponentWidth / opponentDist)
      float halfWidthAngle = atan2(SP.defaultKickableArea() * 0.5, oppDist);
      //float oppAngleBottom = oppAngle;
      //float oppAngleTop = oppAngle;
      float oppAngleBottom = oppAngle - halfWidthAngle;
      float oppAngleTop = oppAngle + halfWidthAngle;
233
      // std::cout << "    to split? " << oppDist << " " << maxDist << std::endl;
234 235 236 237 238 239 240 241
      if (oppDist < maxDist) {
        splitAngles(openAngles,oppAngleBottom,oppAngleTop);
      }
    }
  }
  float largestOpening = 0;
  for (uint i = 0; i < openAngles.size(); ++i) {
    OpenAngle &open = openAngles[i];
242
    // std::cout << "  opening: " << RAD_T_DEG * open.first << " " << RAD_T_DEG * open.second << std::endl;
243 244 245 246 247 248 249 250 251 252 253
    float opening = open.second - open.first;
    if (opening > largestOpening) {
      largestOpening = opening;
    }
  }
  return largestOpening;
}

void FeatureExtractor::splitAngles(std::vector<OpenAngle> &openAngles,
                                   float oppAngleBottom, float oppAngleTop) {
  std::vector<OpenAngle> resAngles;
254 255
  for (uint i = 0; i < openAngles.size(); ++i) {
    OpenAngle& open = openAngles[i];
256 257 258 259 260 261 262 263 264
    if ((oppAngleTop < open.first) || (oppAngleBottom > open.second)) {
      resAngles.push_back(open);
    } else {
      resAngles.push_back(OpenAngle(open.first, oppAngleBottom));
      resAngles.push_back(OpenAngle(oppAngleTop, open.second));
    }
  }
  openAngles = resAngles;
}
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294

float FeatureExtractor::normalizedXPos(float absolute_x_pos) {
  float tolerance_x = .1 * pitchHalfLength;
  if (playingOffense) {
    return normalize(absolute_x_pos, -tolerance_x, pitchHalfLength + tolerance_x);
  } else {
    return normalize(absolute_x_pos, -pitchHalfLength-tolerance_x, tolerance_x);
  }
}

float FeatureExtractor::normalizedYPos(float absolute_y_pos) {
  float tolerance_y = .1 * pitchHalfWidth;
  return normalize(absolute_y_pos, -pitchHalfWidth - tolerance_y,
                   pitchHalfWidth + tolerance_y);
}

float FeatureExtractor::absoluteXPos(float normalized_x_pos) {
  float tolerance_x = .1 * pitchHalfLength;
  if (playingOffense) {
    return unnormalize(normalized_x_pos, -tolerance_x, pitchHalfLength + tolerance_x);
  } else {
    return unnormalize(normalized_x_pos, -pitchHalfLength-tolerance_x, tolerance_x);
  }
}

float FeatureExtractor::absoluteYPos(float normalized_y_pos) {
  float tolerance_y = .1 * pitchHalfWidth;
  return unnormalize(normalized_y_pos, -pitchHalfWidth - tolerance_y,
                     pitchHalfWidth + tolerance_y);
}