Example #1
0
  /**
   * Converts a given String to a Feature if the String type is not known in advance but the type of
   * the feature is known. This is done by casting the given String to the given type. In general,
   * this method should only be used in special cases where a feature type cannot be inferred from
   * String type.
   *
   * @param name Name of the resulting Feature
   * @param type Type of the resulting Feature
   * @param s String to convert to a Feature
   */
  public static Feature fromType(String name, int type, String s) {
    FeatureType ftype = FeatureType.fromInt(type);
    if (ftype == null) {
      throw new IllegalArgumentException("Cannot construct a Feature " + "from this type.");
    }

    try {
      switch (ftype) {
        case INT:
          return new Feature(name, Integer.parseInt(s));
        case LONG:
          return new Feature(name, Long.parseLong(s));
        case FLOAT:
          return new Feature(name, Float.parseFloat(s));
        case DOUBLE:
          return new Feature(name, Double.parseDouble(s));
        case STRING:
          return new Feature(name, s);
        default:
          throw new IllegalArgumentException("Could not instantiate " + "FeatureData");
      }
    } catch (NumberFormatException nfe) {
      throw new IllegalArgumentException(
          "Could not instantiate feature data. "
              + "Failed to convert the value to given type(s="
              + s
              + ", type="
              + ftype.toClass().getName()
              + ")");
    } catch (Exception e) {
      throw new IllegalArgumentException(
          "Could not instantiate " + "FeatureData. Details - " + e.getMessage());
    }
  }
 /**
  * Determines the "best" split attribute (feature) for a set of items, it is based on the
  * information gain criterion. Thus to determine which feature is "best" (which feature contains
  * the most information)the formulas on page 54 and 55 are used.
  */
 private static String selectSplit(
     Map<Item, String> trainingsSet, Map<String, FeatureType> features) {
   Iterator<String> attr = features.keySet().iterator();
   String split = null;
   double maxGain = 0.0;
   while (attr.hasNext()) {
     String candidate = attr.next();
     FeatureType type = features.get(candidate);
     double gain = evaluateSplitGain(trainingsSet, candidate, type.allowedValues());
     if (gain > maxGain) {
       maxGain = gain;
       split = candidate;
     }
   }
   return split;
 }
Example #3
0
  /**
   * Removes any tiles found at the specified coordinates matching the given feature type
   *
   * @param featureType
   * @param x
   * @param y
   */
  protected void removeMatchingTiles(FeatureType featureType, int x, int y) {
    Iterator<Tile> iter = tiles[x][y].iterator();

    while (iter.hasNext()) {
      if (featureType.getTerrainTile(iter.next().getTileID()) != null) {
        iter.remove();
      }
    }
  }
 @Override
 public int hashCode() {
   final int prime = 31;
   int result = 1;
   result = prime * result + dictionarySize;
   result = prime * result + ((type == null) ? 0 : type.hashCode());
   result = prime * result + (useCropZone ? 1231 : 1237);
   return result;
 }
  /**
   * This method implements algorithm 4.2 on page 54 of the book. Input : a training set of items T,
   * a set of features F Output: a decision tree which can be used to classify other items.
   *
   * @param trainingsSet
   * @param features
   * @return The root Node of the decisiontree created.
   */
  private static Node buildDecisionTree(
      Map<Item, String> trainingsSet, Map<String, FeatureType> features) {
    // 1) 2ab) if the attribute set is empty or the items belong to a single class
    if (features.size() == 0 || information(trainingsSet) == 0.0) {
      //  create a leaf node labeled according to the class of the items
      return new Node(findCategory(trainingsSet));
    }

    // 3)  select the "best" split feature s in F
    //    (in the car example this best split feature might be "airco")
    String splitFeature = selectSplit(trainingsSet, features);
    // 4)  create a node with label s.name
    Node n = new Node(splitFeature);
    // 5)  for each possible value vi of s
    //    (in the car example the possible values of the airco feature are yes/no.
    FeatureType splitType = (FeatureType) features.get(splitFeature);
    //    Split the trainingsset into subsets.
    //    (in the car example you'd get a subset of all cars with airco=yes and
    //     a subset of cars with airco=no)
    Map<String, HashMap<Item, String>> partitions =
        performSplit(trainingsSet, splitFeature, splitType.allowedValues());
    for (Iterator<String> iter = partitions.keySet().iterator(); iter.hasNext(); ) {
      String value = iter.next();
      //    a)  be ni the result of a recursive execution of this algorithm where
      //        the fist input is: Ti = { item in T | item.s == vi }
      //        the second input is: A - { s }
      //        (repeat the algorithm with the feature airco excluded)
      Map<Item, String> partition = partitions.get(value);
      Map<String, FeatureType> remainingFeatures = new HashMap<String, FeatureType>(features);
      remainingFeatures.remove(splitFeature);
      Node child = buildDecisionTree(partition, remainingFeatures);
      //    b)  set ni as child node of n and label the connecting arc vi
      n.addChild(value, child);
    }
    // 4)  n is the resulting root node of the decision tree
    return n;
  }
Example #6
0
  /**
   * Converts a native Object to a Feature if the Object type is not known in advance. This is done
   * by determining if the provided object is an instance of a valid Feature type, and then casting
   * the Object to the type. In general, this method should only be used in special cases where an
   * item's type is not known already.
   *
   * @param name Name of the resulting Feature
   * @param o Object to convert to a Feature
   */
  public static Feature fromNativeType(String name, Object o) {
    FeatureType type = FeatureType.fromPrimitiveType(o);
    if (type == null) {
      throw new IllegalArgumentException("Cannot construct a Feature " + "from this type.");
    }

    switch (type) {
      case INT:
        return new Feature(name, (int) o);
      case LONG:
        return new Feature(name, (long) o);
      case FLOAT:
        return new Feature(name, (float) o);
      case DOUBLE:
        return new Feature(name, (double) o);
      case STRING:
        return new Feature(name, (String) o);
      default:
        throw new IllegalArgumentException("Could not instantiate " + "FeatureData");
    }
  }
Example #7
0
  /**
   * Amend the given NetcdfFile with metadata from HDF-EOS structMetadata
   *
   * @param ncfile Amend this file
   * @param structMetadata structMetadata as String
   * @throws IOException on read error
   */
  private void amendFromODL(NetcdfFile ncfile, String structMetadata) throws IOException {
    Group rootg = ncfile.getRootGroup();

    ODLparser parser = new ODLparser();
    Element root = parser.parseFromString(structMetadata); // now we have the ODL in JDOM elements
    FeatureType featureType = null;

    // SWATH
    Element swathStructure = root.getChild("SwathStructure");
    if (swathStructure != null) {
      List<Element> swaths = swathStructure.getChildren();
      for (Element elemSwath : swaths) {
        Element swathNameElem = elemSwath.getChild("SwathName");
        if (swathNameElem == null) {
          log.warn("No SwathName element in {} {} ", elemSwath.getName(), ncfile.getLocation());
          continue;
        }
        String swathName = NetcdfFile.makeValidCdmObjectName(swathNameElem.getText().trim());
        Group swathGroup = findGroupNested(rootg, swathName);
        // if (swathGroup == null)
        //  swathGroup = findGroupNested(rootg, H4header.createValidObjectName(swathName));

        if (swathGroup != null) {
          featureType = amendSwath(ncfile, elemSwath, swathGroup);
        } else {
          log.warn("Cant find swath group {} {}", swathName, ncfile.getLocation());
        }
      }
    }

    // GRID
    Element gridStructure = root.getChild("GridStructure");
    if (gridStructure != null) {
      List<Element> grids = gridStructure.getChildren();
      for (Element elemGrid : grids) {
        Element gridNameElem = elemGrid.getChild("GridName");
        if (gridNameElem == null) {
          log.warn("No GridName element in {} {} ", elemGrid.getName(), ncfile.getLocation());
          continue;
        }
        String gridName = NetcdfFile.makeValidCdmObjectName(gridNameElem.getText().trim());
        Group gridGroup = findGroupNested(rootg, gridName);
        // if (gridGroup == null)
        //  gridGroup = findGroupNested(rootg, H4header.createValidObjectName(gridName));
        if (gridGroup != null) {
          featureType = amendGrid(elemGrid, ncfile, gridGroup, ncfile.getLocation());
        } else {
          log.warn("Cant find Grid group {} {}", gridName, ncfile.getLocation());
        }
      }
    }

    // POINT - NOT DONE YET
    Element pointStructure = root.getChild("PointStructure");
    if (pointStructure != null) {
      List<Element> pts = pointStructure.getChildren();
      for (Element elem : pts) {
        Element nameElem = elem.getChild("PointName");
        if (nameElem == null) {
          log.warn("No PointName element in {} {}", elem.getName(), ncfile.getLocation());
          continue;
        }
        String name = nameElem.getText().trim();
        Group ptGroup = findGroupNested(rootg, name);
        // if (ptGroup == null)
        //  ptGroup = findGroupNested(rootg, H4header.createValidObjectName(name));
        if (ptGroup != null) {
          featureType = FeatureType.POINT;
        } else {
          log.warn("Cant find Point group {} {}", name, ncfile.getLocation());
        }
      }
    }

    if (featureType != null) {
      if (showWork) System.out.println("***EOS featureType= " + featureType.toString());
      rootg.addAttribute(new Attribute(CF.FEATURE_TYPE, featureType.toString()));
      // rootg.addAttribute(new Attribute(CDM.CONVENTIONS, "HDFEOS"));
    }
  }
Example #8
0
  public DimensionInformation(String name, DimensionDescriptor descriptor, ByteBuf buf) {
    this.name = name;
    this.descriptor = descriptor;

    terrainType = NetworkTools.readEnum(buf, TerrainType.values());
    NetworkTools.readEnumCollection(buf, featureTypes, FeatureType.values());
    NetworkTools.readEnumCollection(buf, structureTypes, StructureType.values());
    NetworkTools.readEnumCollection(buf, effectTypes, EffectType.values());

    biomes.clear();
    int size = buf.readInt();
    for (int i = 0; i < size; i++) {
      BiomeGenBase biome = BiomeGenBase.getBiome(buf.readInt());
      if (biome != null) {
        biomes.add(biome);
      } else {
        biomes.add(BiomeGenBase.plains);
      }
    }
    controllerType = NetworkTools.readEnum(buf, ControllerType.values());
    digitString = NetworkTools.readString(buf);

    forcedDimensionSeed = buf.readLong();
    baseSeed = buf.readLong();
    worldVersion = buf.readInt();

    Block block = (Block) Block.blockRegistry.getObjectById(buf.readInt());
    int meta = buf.readInt();
    baseBlockForTerrain = new BlockMeta(block, meta);
    block = (Block) Block.blockRegistry.getObjectById(buf.readInt());
    meta = buf.readInt();
    tendrilBlock = new BlockMeta(block, meta);

    pyramidBlocks = readBlockArrayFromBuf(buf);
    sphereBlocks = readBlockArrayFromBuf(buf);
    hugeSphereBlocks = readBlockArrayFromBuf(buf);
    liquidSphereBlocks = readBlockArrayFromBuf(buf);
    liquidSphereFluids = readFluidArrayFromBuf(buf);
    hugeLiquidSphereBlocks = readBlockArrayFromBuf(buf);
    hugeLiquidSphereFluids = readFluidArrayFromBuf(buf);

    block = (Block) Block.blockRegistry.getObjectById(buf.readInt());
    meta = buf.readInt();
    canyonBlock = new BlockMeta(block, meta);
    fluidForTerrain = (Block) Block.blockRegistry.getObjectById(buf.readInt());

    extraOregen = readBlockArrayFromBuf(buf);

    fluidsForLakes = readFluidArrayFromBuf(buf);

    peaceful = buf.readBoolean();
    noanimals = buf.readBoolean();
    shelter = buf.readBoolean();
    respawnHere = buf.readBoolean();

    celestialAngle = NetworkTools.readFloat(buf);
    timeSpeed = NetworkTools.readFloat(buf);

    probeCounter = buf.readInt();
    actualRfCost = buf.readInt();

    skyDescriptor = new SkyDescriptor.Builder().fromBytes(buf).build();
    calculateCelestialBodyDescriptors();

    weatherDescriptor = new WeatherDescriptor.Builder().fromBytes(buf).build();

    patreon1 = buf.readLong();

    extraMobs.clear();
    size = buf.readInt();
    for (int i = 0; i < size; i++) {
      String className = NetworkTools.readString(buf);
      try {
        Class<? extends EntityLiving> c = (Class<? extends EntityLiving>) Class.forName(className);
        int chance = buf.readInt();
        int minGroup = buf.readInt();
        int maxGroup = buf.readInt();
        int maxLoaded = buf.readInt();
        MobDescriptor mob = new MobDescriptor(null, c, chance, minGroup, maxGroup, maxLoaded);
        extraMobs.add(mob);
      } catch (ClassNotFoundException e) {
        e.printStackTrace();
      }
    }

    size = buf.readInt();
    dimensionTypes = new String[size];
    for (int i = 0; i < size; i++) {
      dimensionTypes[i] = NetworkTools.readString(buf);
    }

    setupBiomeMapping();
  }
Example #9
0
  public void dump(EntityPlayer player) {
    String digits = getDigitString();
    if (!digits.isEmpty()) {
      logDebug(player, "    Digits: " + digits);
    }
    if (forcedDimensionSeed != 0) {
      logDebug(player, "    Forced seed: " + forcedDimensionSeed);
    }
    if (baseSeed != 0) {
      logDebug(player, "    Base seed: " + baseSeed);
    }
    logDebug(player, "    World version: " + worldVersion);
    TerrainType terrainType = getTerrainType();
    logDebug(player, "    Terrain: " + terrainType.toString());
    logDebug(
        player,
        "        Base block: "
            + new ItemStack(baseBlockForTerrain.getBlock(), 1, baseBlockForTerrain.getMeta())
                .getDisplayName());
    if (featureTypes.contains(FeatureType.FEATURE_TENDRILS)) {
      logDebug(
          player,
          "        Tendril block: "
              + new ItemStack(tendrilBlock.getBlock(), 1, tendrilBlock.getMeta()).getDisplayName());
    }
    if (featureTypes.contains(FeatureType.FEATURE_PYRAMIDS)) {
      for (BlockMeta block : pyramidBlocks) {
        if (block != null) {
          logDebug(
              player,
              "        Pyramid blocks: "
                  + new ItemStack(block.getBlock(), 1, block.getMeta()).getDisplayName());
        }
      }
    }
    if (featureTypes.contains(FeatureType.FEATURE_ORBS)) {
      for (BlockMeta block : sphereBlocks) {
        if (block != null) {
          logDebug(
              player,
              "        Orb blocks: "
                  + new ItemStack(block.getBlock(), 1, block.getMeta()).getDisplayName());
        }
      }
    }
    if (featureTypes.contains(FeatureType.FEATURE_HUGEORBS)) {
      for (BlockMeta block : hugeSphereBlocks) {
        if (block != null) {
          logDebug(
              player,
              "        Huge Orb blocks: "
                  + new ItemStack(block.getBlock(), 1, block.getMeta()).getDisplayName());
        }
      }
    }
    if (featureTypes.contains(FeatureType.FEATURE_LIQUIDORBS)) {
      for (BlockMeta block : liquidSphereBlocks) {
        if (block != null) {
          logDebug(
              player,
              "        Liquid Orb blocks: "
                  + new ItemStack(block.getBlock(), 1, block.getMeta()).getDisplayName());
        }
      }
    }
    if (featureTypes.contains(FeatureType.FEATURE_HUGELIQUIDORBS)) {
      for (BlockMeta block : hugeLiquidSphereBlocks) {
        if (block != null) {
          logDebug(
              player,
              "        Huge Liquid Orb blocks: "
                  + new ItemStack(block.getBlock(), 1, block.getMeta()).getDisplayName());
        }
      }
    }
    if (featureTypes.contains(FeatureType.FEATURE_CANYONS)) {
      logDebug(
          player,
          "        Canyon block: "
              + new ItemStack(canyonBlock.getBlock(), 1, canyonBlock.getMeta()).getDisplayName());
    }
    logDebug(player, "        Base fluid: " + new ItemStack(fluidForTerrain).getDisplayName());
    logDebug(
        player,
        "    Biome controller: " + (controllerType == null ? "<null>" : controllerType.name()));
    for (BiomeGenBase biome : getBiomes()) {
      if (biome != null) {
        logDebug(player, "    Biome: " + biome.biomeName);
      }
    }
    for (FeatureType featureType : getFeatureTypes()) {
      logDebug(player, "    Feature: " + featureType.toString());
    }
    for (BlockMeta block : extraOregen) {
      if (block != null) {
        logDebug(
            player,
            "        Extra ore: "
                + new ItemStack(block.getBlock(), 1, block.getMeta()).getDisplayName());
      }
    }
    for (Block block : fluidsForLakes) {
      logDebug(player, "        Lake fluid: " + new ItemStack(block).getDisplayName());
    }
    if (featureTypes.contains(FeatureType.FEATURE_LIQUIDORBS)) {
      for (Block fluid : liquidSphereFluids) {
        logDebug(player, "        Liquid orb fluids: " + new ItemStack(fluid).getDisplayName());
      }
    }
    if (featureTypes.contains(FeatureType.FEATURE_HUGELIQUIDORBS)) {
      for (Block fluid : hugeLiquidSphereFluids) {
        logDebug(
            player, "        Huge Liquid orb fluids: " + new ItemStack(fluid).getDisplayName());
      }
    }
    for (StructureType structureType : getStructureTypes()) {
      logDebug(player, "    Structure: " + structureType.toString());
    }
    if (structureTypes.contains(StructureType.STRUCTURE_RECURRENTCOMPLEX)) {
      for (String type : dimensionTypes) {
        logDebug(player, "    RR DimensionType: " + type);
      }
    }
    for (EffectType effectType : getEffectTypes()) {
      logDebug(player, "    Effect: " + effectType.toString());
    }
    logDebug(player, "    Sun brightness: " + skyDescriptor.getSunBrightnessFactor());
    logDebug(player, "    Star brightness: " + skyDescriptor.getStarBrightnessFactor());
    float r = skyDescriptor.getSkyColorFactorR();
    float g = skyDescriptor.getSkyColorFactorG();
    float b = skyDescriptor.getSkyColorFactorB();
    logDebug(player, "    Sky color: " + r + ", " + g + ", " + b);
    r = skyDescriptor.getFogColorFactorR();
    g = skyDescriptor.getFogColorFactorG();
    b = skyDescriptor.getFogColorFactorB();
    logDebug(player, "    Fog color: " + r + ", " + g + ", " + b);
    SkyType skyType = skyDescriptor.getSkyType();
    if (skyType != SkyType.SKY_NORMAL) {
      logDebug(player, "    Sky type: " + skyType.toString());
    }
    for (CelestialBodyType bodyType : skyDescriptor.getCelestialBodies()) {
      logDebug(player, "    Sky body: " + bodyType.name());
    }

    if (weatherDescriptor.getRainStrength() > -0.5f) {
      logDebug(player, "    Weather rain: " + weatherDescriptor.getRainStrength());
    }
    if (weatherDescriptor.getThunderStrength() > -0.5f) {
      logDebug(player, "    Weather thunder " + weatherDescriptor.getThunderStrength());
    }

    for (MobDescriptor mob : extraMobs) {
      if (mob != null) {
        if (mob.getEntityClass() == null) {
          logDebug(player, "    Mob: " + mob);
        } else {
          logDebug(player, "    Mob: " + mob.getEntityClass().getName());
        }
      }
    }
    if (peaceful) {
      logDebug(player, "    Peaceful mode");
    }
    if (noanimals) {
      logDebug(player, "    No animals mode");
    }
    if (shelter) {
      logDebug(player, "    Safe shelter");
    }
    if (respawnHere) {
      logDebug(player, "    Respawn local");
    }
    if (celestialAngle != null) {
      logDebug(player, "    Celestial angle: " + celestialAngle);
    }
    if (timeSpeed != null) {
      logDebug(player, "    Time speed: " + timeSpeed);
    }
    if (probeCounter > 0) {
      logDebug(player, "    Probes: " + probeCounter);
    }
    if (patreon1 != 0) {
      logDebug(player, "    Patreon: " + patreon1);
    }
  }
Example #10
0
  private void setupFromNBT(NBTTagCompound tagCompound) {
    terrainType = TerrainType.values()[tagCompound.getInteger("terrain")];
    featureTypes = toEnumSet(getIntArraySafe(tagCompound, "features"), FeatureType.values());
    structureTypes = toEnumSet(getIntArraySafe(tagCompound, "structures"), StructureType.values());
    effectTypes = toEnumSet(getIntArraySafe(tagCompound, "effects"), EffectType.values());

    biomes.clear();
    for (int a : getIntArraySafe(tagCompound, "biomes")) {
      BiomeGenBase biome = BiomeGenBase.getBiome(a);
      if (biome != null) {
        biomes.add(biome);
      } else {
        // Protect against deleted biomes (i.e. a mod with biomes gets removed and this dimension
        // still uses it).
        // We will pick a replacement biome here.
        biomes.add(BiomeGenBase.plains);
      }
    }
    if (tagCompound.hasKey("controller")) {
      controllerType = ControllerType.values()[tagCompound.getInteger("controller")];
    } else {
      // Support for old type.
      if (biomes.isEmpty()) {
        controllerType = ControllerType.CONTROLLER_DEFAULT;
      } else {
        controllerType = ControllerType.CONTROLLER_SINGLE;
      }
    }

    digitString = tagCompound.getString("digits");

    forcedDimensionSeed = tagCompound.getLong("forcedSeed");
    baseSeed = tagCompound.getLong("baseSeed");
    worldVersion = tagCompound.getInteger("worldVersion");

    baseBlockForTerrain = getBlockMeta(tagCompound, "baseBlock");
    tendrilBlock = getBlockMeta(tagCompound, "tendrilBlock");
    canyonBlock = getBlockMeta(tagCompound, "canyonBlock");
    fluidForTerrain =
        (Block) Block.blockRegistry.getObjectById(tagCompound.getInteger("fluidBlock"));

    hugeLiquidSphereFluids = readFluidsFromNBT(tagCompound, "hugeLiquidSphereFluids");
    hugeLiquidSphereBlocks = readBlockArrayFromNBT(tagCompound, "hugeLiquidSphereBlocks");

    // Support for the old format with only one liquid block.
    Block oldLiquidSphereFluid =
        (Block) Block.blockRegistry.getObjectById(tagCompound.getInteger("liquidSphereFluid"));
    liquidSphereFluids = readFluidsFromNBT(tagCompound, "liquidSphereFluids");
    if (liquidSphereFluids.length == 0) {
      liquidSphereFluids = new Block[] {oldLiquidSphereFluid};
    }

    // Support for the old format with only one sphere block.
    BlockMeta oldLiquidSphereBlock = getBlockMeta(tagCompound, "liquidSphereBlock");
    liquidSphereBlocks = readBlockArrayFromNBT(tagCompound, "liquidSphereBlocks");
    if (liquidSphereBlocks.length == 0) {
      liquidSphereBlocks = new BlockMeta[] {oldLiquidSphereBlock};
    }

    pyramidBlocks = readBlockArrayFromNBT(tagCompound, "pyramidBlocks");
    if (pyramidBlocks.length == 0) {
      pyramidBlocks = new BlockMeta[] {BlockMeta.STONE};
    }

    // Support for the old format with only one sphere block.
    BlockMeta oldSphereBlock = getBlockMeta(tagCompound, "sphereBlock");
    sphereBlocks = readBlockArrayFromNBT(tagCompound, "sphereBlocks");
    if (sphereBlocks.length == 0) {
      sphereBlocks = new BlockMeta[] {oldSphereBlock};
    }

    hugeSphereBlocks = readBlockArrayFromNBT(tagCompound, "hugeSphereBlocks");

    extraOregen = readBlockArrayFromNBT(tagCompound, "extraOregen");
    fluidsForLakes = readFluidsFromNBT(tagCompound, "lakeFluids");

    peaceful = tagCompound.getBoolean("peaceful");
    noanimals = tagCompound.getBoolean("noanimals");
    shelter = tagCompound.getBoolean("shelter");
    respawnHere = tagCompound.getBoolean("respawnHere");
    if (tagCompound.hasKey("celestialAngle")) {
      celestialAngle = tagCompound.getFloat("celestialAngle");
    } else {
      celestialAngle = null;
    }
    if (tagCompound.hasKey("timeSpeed")) {
      timeSpeed = tagCompound.getFloat("timeSpeed");
    } else {
      timeSpeed = null;
    }
    probeCounter = tagCompound.getInteger("probes");
    actualRfCost = tagCompound.getInteger("actualCost");

    skyDescriptor = new SkyDescriptor.Builder().fromNBT(tagCompound).build();
    calculateCelestialBodyDescriptors();

    patreon1 = tagCompound.getLong("patreon1");

    weatherDescriptor = new WeatherDescriptor.Builder().fromNBT(tagCompound).build();

    extraMobs.clear();
    NBTTagList list = tagCompound.getTagList("mobs", Constants.NBT.TAG_COMPOUND);
    for (int i = 0; i < list.tagCount(); i++) {
      NBTTagCompound tc = list.getCompoundTagAt(i);
      String className = tc.getString("class");
      int chance = tc.getInteger("chance");
      int minGroup = tc.getInteger("minGroup");
      int maxGroup = tc.getInteger("maxGroup");
      int maxLoaded = tc.getInteger("maxLoaded");
      Class<? extends EntityLiving> c = null;
      try {
        c = (Class<? extends EntityLiving>) Class.forName(className);
      } catch (ClassNotFoundException e) {
        throw new RuntimeException(e);
      }
      MobDescriptor mob = new MobDescriptor(null, c, chance, minGroup, maxGroup, maxLoaded);
      extraMobs.add(mob);
    }

    String ds = tagCompound.getString("dimensionTypes");
    dimensionTypes = StringUtils.split(ds, ",");
    if (dimensionTypes == null) {
      dimensionTypes = new String[0];
    }
  }
Example #11
0
 @Deserialize
 public Feature(SerializationInputStream in) throws IOException, SerializationException {
   setName(in.readString());
   FeatureType type = FeatureType.fromInt(in.readInt());
   data = Serializer.deserializeFromStream(type.toClass(), in);
 }
Example #12
0
 @Deserialize
 public Feature(String name, FeatureType type, SerializationInputStream in)
     throws IOException, SerializationException {
   setName(name);
   data = Serializer.deserializeFromStream(type.toClass(), in);
 }
Example #13
0
/**
 * ProfileData acts as a data store facility for the results of the test performed by the Profile
 * object. This data includes the number of trials and number of successes among those trials (i.e.,
 * the number of times the correct answer was selected) broken down by algorithm type and question
 * profile (i.e., by combination of features).
 *
 * @author jjohnson346
 */
public class ProfileData {

  private int[][] successCounts; // stores the number of successes for each
  // question profile,
  // for each algo.

  public final int[] trialCounts; // stores the number of trials for each
  // question profile.

  public final double[][] successProbs; // the prob of success for each algo,
  // for each question profile
  // IMPORTANT: note that it is PUBLIC

  private final int NUM_ALGOS = AlgorithmType.values().length; // the number
  // of algos
  // to store
  // data for

  private final int NUM_FEATURES = FeatureType.values().length; // the number
  // of
  // features
  // identified

  private final int NUM_FEATURE_COMBOS = (int) Math.pow(2.0, NUM_FEATURES); // the
  // number
  // of
  // combos
  // of
  // features,
  // assume
  // true/false
  // value
  // for
  // each.

  /**
   * constructor initializes the successCounts, trialCounts and successProbs arrays according to the
   * number of algos, number of features, and the consequent number of feature combinations.
   */
  public ProfileData() {
    successCounts = new int[NUM_FEATURE_COMBOS][NUM_ALGOS];
    trialCounts = new int[NUM_FEATURE_COMBOS];
    successProbs = new double[NUM_FEATURE_COMBOS][NUM_ALGOS];
  }

  /**
   * inserts the results data for a question into the data store. That is, this function inserts for
   * each algorithm, the results of applying that algorithm on the question, as given by the array,
   * results, passed in as an input argument. This data is inserted the location of the data store
   * corresponding to the profile for the given question.
   *
   * @param question the question for which to insert the data, the profile is the pertinent info,
   *     here.
   * @param results an array of booleans giving whether the corresponding algo was successful on the
   *     question.
   */
  public void insert(CFEExamQuestion question, boolean[] results) {
    // get the profile for the question passed in as an input parm.
    int profileIndex = question.getProfile().getProfileIndex();

    // increment the number of trials for the index corresponding to the
    // question's profile.
    trialCounts[profileIndex]++;

    // increment the success count in the successCounts array for those
    // algos that were successful.
    for (int j = 0; j < successCounts[profileIndex].length; j++) {
      if (results[j]) successCounts[profileIndex][j]++;
    }
  }

  /**
   * calculates the probability of success for a each algorithm on each question profile and stores
   * the results in a public array, successProbs, which is used by the CFEExamAgent to determine on
   * each question it confronts which algo to use. That is, it picks the algo with highest
   * probability of success given the profile of the current question.
   */
  public void calculate() {
    for (int i = 0; i < NUM_FEATURE_COMBOS; i++) {
      for (int j = 0; j < NUM_ALGOS; j++) {
        if (trialCounts[i] != 0) successProbs[i][j] = (double) successCounts[i][j] / trialCounts[i];
        else successProbs[i][j] = 0.0;
      }
    }
  }

  /**
   * loads profile data from file, profile data.txt, and stores the contents in the public array,
   * successProbs. successProbs is the critical array used by the CFEExamAgent for selecting the
   * algo to use on each question it confronts.
   */
  public void load() throws FileNotFoundException {
    // change backslashes to forward slashes for mac version.
    // Scanner scanner = new Scanner(new
    // File("profile data\\profile data.txt"));
    Scanner scanner = new Scanner(new File("profile data//profile data.txt"));

    // skip first 2 header lines.
    scanner.nextLine();
    scanner.nextLine();

    for (int i = 0; i < NUM_FEATURE_COMBOS; i++) {

      // skip first column showing the index.
      scanner.nextInt();

      trialCounts[i] = scanner.nextInt();

      for (int j = 0; j < NUM_ALGOS; j++) {
        successProbs[i][j] = scanner.nextDouble();
      }
    }
    scanner.close();
  }

  /**
   * returns a pretty formatted version of the contents of number of trials and successProb for each
   * question profile.
   */
  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder();
    sb.append(toStringTrueFalse());
    sb.append("\n\n");
    sb.append(toStringMultipleChoice());
    return new String(sb);
    //		StringBuilder sb = new StringBuilder();
    //
    //		final int COLUMN_WIDTH = 14;
    //		String formatString = "%" + COLUMN_WIDTH + "s";
    //
    //		// make header.
    //		sb.append(String.format(formatString, "Index"));
    //		sb.append(String.format(formatString, "Trials"));
    //
    //		for (AlgorithmType t : AlgorithmType.values()) {
    //			sb.append(String.format(formatString, t));
    //		}
    //		sb.append(String.format(formatString, "Agent"));
    //		sb.append(String.format(formatString, "Description"));
    //		sb.append("\n");
    //		for (int i = 0; i < AlgorithmType.values().length + 4; i++)
    //			sb.append(String.format(formatString, "-------------"));
    //		sb.append("\n");
    //
    //		// display values.
    //		for (int i = 0; i < NUM_FEATURE_COMBOS; i++) {
    //			// 2016/01/05 - version 2.0.0 - added condition for
    //			// trial counts > 0 in order to remove the "zero" rows,
    //			// i.e., rows showing profile indices where there are no
    //			// trials.
    //			if (trialCounts[i] > 0) {
    //				sb.append(String.format(formatString, i));
    //				sb.append(String.format(formatString, trialCounts[i]));
    //
    //				for (int j = 0; j < AlgorithmType.values().length; j++) {
    //					sb.append(String.format("%" + COLUMN_WIDTH + ".3f", successProbs[i][j]));
    //				}
    //				sb.append(String.format("%" + COLUMN_WIDTH + ".3f", maxSuccessProb(successProbs[i])));
    //				sb.append(Profile.getDescription(i));
    //				sb.append("\n");
    //			}
    //		}
    //
    //		// display total trial count
    //		int totalCount = 0;
    //		for (int i = 0; i < trialCounts.length; i++) {
    //			totalCount += trialCounts[i];
    //		}
    //		sb.append(String.format("%" + COLUMN_WIDTH + "s%" + COLUMN_WIDTH
    //				+ "d\n", "Total Count:", totalCount));
    //
    //		return new String(sb);
  }

  private String toStringMultipleChoice() {
    StringBuilder sb = new StringBuilder();

    final int COLUMN_WIDTH = 14;
    String formatString = "%" + COLUMN_WIDTH + "s";

    // make header.
    sb.append("Multiple Choice:\n----------------\n");
    sb.append(String.format(formatString, "Index"));
    sb.append(String.format(formatString, "Trials"));

    for (AlgorithmType t : AlgorithmType.values()) {
      sb.append(String.format(formatString, t));
    }
    sb.append(String.format(formatString, "Agent"));
    sb.append(String.format(formatString, "Description"));
    sb.append("\n");
    for (int i = 0; i < AlgorithmType.values().length + 4; i++)
      sb.append(String.format(formatString, "-------------"));
    sb.append("\n");

    int totalCount = 0; // for displaying the total count at the bottom.
    double weightedAgentAccuracy =
        0; // for calculating weighted accuracy rate across all question profiles.

    // display values.
    for (int i = 0; i < NUM_FEATURE_COMBOS; i++) {
      // 2016/01/05 - version 2.0.0 - added condition for
      // trial counts > 0 in order to remove the "zero" rows,
      // i.e., rows showing profile indices where there are no
      // trials.
      // Also, added the !hasFeature(truefalse) condition.
      if (trialCounts[i] > 0 && !Profile.hasFeature(i, FeatureType.TRUE_FALSE.ordinal())) {
        sb.append(String.format(formatString, i));
        sb.append(String.format(formatString, trialCounts[i]));

        for (int j = 0; j < AlgorithmType.values().length; j++) {
          sb.append(String.format("%" + COLUMN_WIDTH + ".3f", successProbs[i][j]));
        }
        double agentAccuracy = maxSuccessProb(successProbs[i]);
        sb.append(String.format("%" + COLUMN_WIDTH + ".3f", maxSuccessProb(successProbs[i])));
        sb.append(Profile.getDescription(i));
        sb.append("\n");
        totalCount += trialCounts[i];
        weightedAgentAccuracy += trialCounts[i] * agentAccuracy;
      }
    }
    weightedAgentAccuracy /= totalCount;

    // display total trial count
    sb.append(
        String.format(
            "%"
                + COLUMN_WIDTH
                + "s%"
                + COLUMN_WIDTH
                + "d%"
                + COLUMN_WIDTH * 9
                + "s%"
                + COLUMN_WIDTH
                + ".3f\n",
            "Total Count:",
            totalCount,
            " ",
            weightedAgentAccuracy));

    return new String(sb);
  }

  private String toStringTrueFalse() {
    StringBuilder sb = new StringBuilder();

    final int COLUMN_WIDTH = 14;
    String formatString = "%" + COLUMN_WIDTH + "s";

    // make header.
    sb.append("True-False: \n-----------\n");
    sb.append(String.format(formatString, "Index"));
    sb.append(String.format(formatString, "Trials"));

    for (AlgorithmType t : AlgorithmType.values()) {
      sb.append(String.format(formatString, t));
    }
    sb.append(String.format(formatString, "Agent"));
    sb.append(String.format(formatString, "Description"));
    sb.append("\n");
    for (int i = 0; i < AlgorithmType.values().length + 4; i++)
      sb.append(String.format(formatString, "-------------"));
    sb.append("\n");

    int totalCount = 0; // for displaying the total count at the bottom.
    double weightedAgentAccuracy =
        0; // for calculating weighted accuracy rate across all question profiles.

    // display values.
    for (int i = 0; i < NUM_FEATURE_COMBOS; i++) {
      // 2016/01/05 - version 2.0.0 - added condition for
      // trial counts > 0 in order to remove the "zero" rows,
      // i.e., rows showing profile indices where there are no
      // trials.
      // Also, added the hasFeature(truefalse) condition.
      if (trialCounts[i] > 0 && Profile.hasFeature(i, FeatureType.TRUE_FALSE.ordinal())) {
        sb.append(String.format(formatString, i));
        sb.append(String.format(formatString, trialCounts[i]));

        for (int j = 0; j < AlgorithmType.values().length; j++) {
          sb.append(String.format("%" + COLUMN_WIDTH + ".3f", successProbs[i][j]));
        }
        double agentAccuracy = maxSuccessProb(successProbs[i]);
        sb.append(String.format("%" + COLUMN_WIDTH + ".3f", agentAccuracy));
        sb.append(Profile.getDescription(i));
        sb.append("\n");
        totalCount += trialCounts[i];
        weightedAgentAccuracy += trialCounts[i] * agentAccuracy;
      }
    }
    weightedAgentAccuracy /= totalCount;

    // display total trial count
    //		sb.append(String.format("%" + COLUMN_WIDTH + "s%" + COLUMN_WIDTH
    //				+ "d\n", "Total Count:", totalCount));
    sb.append(
        String.format(
            "%"
                + COLUMN_WIDTH
                + "s%"
                + COLUMN_WIDTH
                + "d%"
                + COLUMN_WIDTH * 9
                + "s%"
                + COLUMN_WIDTH
                + ".3f\n",
            "Total Count:",
            totalCount,
            " ",
            weightedAgentAccuracy));

    return new String(sb);
  }

  private double maxSuccessProb(double[] successProbs) {
    double max = successProbs[0];
    for (int i = 1; i < successProbs.length; i++) {
      if (successProbs[i] > max) max = successProbs[i];
    }
    return max;
  }
}