All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.jamesii.mlrules.parser.nodes.SpeciesAttributeNode Maven / Gradle / Ivy

/*
 *   Copyright 2015 University of Rostock
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

package org.jamesii.mlrules.parser.nodes;

import org.jamesii.core.math.parsetree.INode;
import org.jamesii.core.math.parsetree.Node;
import org.jamesii.core.math.parsetree.ValueNode;
import org.jamesii.core.math.parsetree.variables.IEnvironment;
import org.jamesii.mlrules.model.species.Species;
import org.jamesii.mlrules.parser.types.Tuple;
import org.jamesii.mlrules.util.MLEnvironment;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Return the attribute {@link Tuple} of the given species.
 * 
 * @author Tobias Helms
 *
 */
public class SpeciesAttributeNode extends Node {

  private static final long serialVersionUID = 1L;

  public static final String NAME = "§species";

  @SuppressWarnings("unchecked")
  @Override
  public  N calc(IEnvironment cEnv) {
    if (cEnv instanceof MLEnvironment) {
      MLEnvironment env = (MLEnvironment) cEnv;
      Object n = env.getValue(NAME);
      if (n instanceof Map) {
        Map species = (Map) n;
        if (species.size() != 1) {
          throw new IllegalArgumentException(String.format(
              "The name function is only applicable for one species and not for %s.",
              species));
        }
        Object o = species.entrySet().iterator().next().getKey();
        if (o instanceof Species) {
          List attributes = new ArrayList<>();
          Species s = (Species) o;
          for (int i = 0; i < s.getType().getAttributesSize(); ++i) {
            attributes.add(s.getAttribute(i));
          }
          return (N) new ValueNode(new Tuple(attributes));
        }
      }
    }
    throw new IllegalArgumentException(String.format(
        "Could not compute the attributes of the species bound to %s", NAME));
  }

  @Override
  public String toString() {
    return "att()";
  }

}