示例#1
0
 private boolean matches(
     BEASTInterface plugin2, String sConditionalAttribute, String sConditionalValue) {
   if (sConditionalAttribute.equals("id") && plugin2.getID().equals(sConditionalValue))
     return true;
   if (sConditionalAttribute.equals("type")
       && plugin2.getClass().getName().equals(sConditionalValue)) return true;
   if (sConditionalAttribute.equals("type!")
       && !plugin2.getClass().getName().equals(sConditionalValue)) return true;
   return false;
 }
示例#2
0
 private void findPriorityBeastObjects(
     BEASTInterface beastObject, List<BEASTInterface> priorityBeastObjects)
     throws IllegalArgumentException, IllegalAccessException {
   if (beastObject.getClass().equals(Alignment.class)) {
     priorityBeastObjects.add(beastObject);
   }
   if (beastObject instanceof TraitSet) {
     priorityBeastObjects.add(beastObject);
   }
   for (BEASTInterface beastObject2 : beastObject.listActiveBEASTObjects()) {
     findPriorityBeastObjects(beastObject2, priorityBeastObjects);
   }
 }
示例#3
0
 @SuppressWarnings("unchecked")
 public void sync(int iPartition) {
   if (parentInputs.size() > 0 && _input.get() != null) {
     Input<?> input = parentInputs.get(iPartition);
     if (bIsList) {
       List<Object> list = (List<Object>) _input.get();
       List<Object> targetList = ((List<Object>) input.get());
       // targetList.clear();
       // only clear former members
       for (BEASTInterface plugin : startInputs) {
         targetList.remove(plugin);
       }
       targetList.addAll(list);
       // sync outputs of items in list
       for (Object o : list) {
         if (o instanceof BEASTInterface) {
           ((BEASTInterface) o).getOutputs().add(parentPlugins.get(iPartition));
         }
       }
     } else {
       try {
         // System.err.println("sync " + parentPlugins.get(iPartition) + "[" + input.getName() + "]
         // = " + _input.get());
         input.setValue(_input.get(), parentPlugins.get(iPartition));
       } catch (Exception e) {
         e.printStackTrace();
       }
     }
   }
 }
 /**
  * create new instance of src object, connecting all inputs from src object Note if input is a
  * SubstModel, it is duplicated as well.
  *
  * @param src object to be copied
  * @param i index used to extend ID with.
  * @return copy of src object
  */
 private Object duplicate(BEASTInterface src, int i) {
   if (src == null) {
     return null;
   }
   BEASTInterface copy;
   try {
     copy = src.getClass().newInstance();
     copy.setID(src.getID() + "_" + i);
   } catch (InstantiationException | IllegalAccessException e) {
     e.printStackTrace();
     throw new RuntimeException(
         "Programmer error: every object in the model should have a default constructor that is publicly accessible: "
             + src.getClass().getName());
   }
   for (Input<?> input : src.listInputs()) {
     if (input.get() != null) {
       if (input.get() instanceof List) {
         // handle lists
         // ((List)copy.getInput(input.getName())).clear();
         for (Object o : (List<?>) input.get()) {
           if (o instanceof BEASTInterface) {
             // make sure it is not already in the list
             copy.setInputValue(input.getName(), o);
           }
         }
       } else if (input.get() instanceof SubstitutionModel) {
         // duplicate subst models
         BEASTInterface substModel = (BEASTInterface) duplicate((BEASTInterface) input.get(), i);
         copy.setInputValue(input.getName(), substModel);
       } else {
         // it is some other value
         copy.setInputValue(input.getName(), input.get());
       }
     }
   }
   copy.initAndValidate();
   return copy;
 }
示例#5
0
  /** Find the input associated with this panel based on the path Input. */
  @SuppressWarnings("unchecked")
  public Input<?> resolveInput(BeautiDoc doc, int iPartition) {
    try {
      //            if (parentPlugins != null && parentPlugins.size() > 0 && _input != null)
      //                System.err.println("sync " + parentPlugins.get(iPartition) + "[?] = " +
      // _input.get());

      List<BEASTInterface> plugins;
      if (bHasPartitionsInput.get() == Partition.none) {
        plugins = new ArrayList<BEASTInterface>();
        plugins.add(doc.mcmc.get());
      } else {
        plugins = doc.getPartitions(bHasPartitionsInput.get().toString());
      }
      parentPlugins = new ArrayList<BEASTInterface>();
      parentInputs = new ArrayList<Input<?>>();

      parentPlugins.add(doc);
      parentInputs.add(doc.mcmc);
      type = doc.mcmc.getType();
      bIsList = false;
      for (int i = 0; i < sPathComponents.length; i++) {
        List<BEASTInterface> oldPlugins = plugins;
        plugins = new ArrayList<BEASTInterface>();
        parentPlugins = new ArrayList<BEASTInterface>();
        parentInputs = new ArrayList<Input<?>>();
        for (BEASTInterface plugin : oldPlugins) {
          Input<?> namedInput = plugin.getInput(sPathComponents[i]);
          type = namedInput.getType();
          if (namedInput.get() instanceof List<?>) {
            bIsList = true;
            List<?> list = (List<?>) namedInput.get();
            if (sConditionalAttribute[i] == null) {
              for (Object o : list) {
                BEASTInterface plugin2 = (BEASTInterface) o;
                plugins.add(plugin2);
                parentPlugins.add(plugin);
                parentInputs.add(namedInput);
              }
              // throw new Exception ("Don't know which element to pick from the list. List
              // component should come with a condition. " + m_sPathComponents[i]);
            } else {
              int nMatches = 0;
              for (int j = 0; j < list.size(); j++) {
                BEASTInterface plugin2 = (BEASTInterface) list.get(j);
                if (matches(plugin2, sConditionalAttribute[i], sConditionalValue[i])) {
                  plugins.add(plugin2);
                  parentPlugins.add(plugin);
                  parentInputs.add(namedInput);
                  nMatches++;
                  break;
                }
              }
              if (nMatches == 0) {
                parentInputs.add(namedInput);
                parentPlugins.add(plugin);
              }
            }
          } else if (namedInput.get() instanceof BEASTInterface) {
            bIsList = false;
            if (sConditionalAttribute[i] == null) {
              plugins.add((BEASTInterface) namedInput.get());
              parentPlugins.add(plugin);
              parentInputs.add(namedInput);
            } else {
              if (matches(plugin, sConditionalAttribute[i], sConditionalValue[i])) {
                //							if ((m_sConditionalAttribute[i].equals("id") &&
                // plugin.getID().equals(m_sConditionalValue[i])) ||
                //							    (m_sConditionalAttribute[i].equals("type") &&
                // plugin.getClass().getName().equals(m_sConditionalValue[i]))) {
                plugins.add(plugin);
                parentPlugins.add(plugin);
                parentInputs.add(namedInput);
              }
            }
          } else {
            throw new Exception("input " + sPathComponents[i] + "  is not a plugin or list");
          }
        }
      }
      if (sTypeInput.get() != null) {
        type = Class.forName(sTypeInput.get());
      }
      // sanity check
      if (!bIsList && (bHasPartitionsInput.get() == Partition.none) && plugins.size() > 1) {
        System.err.println("WARNING: multiple plugins match, but hasPartitions=none");
        // this makes sure that all mathing plugins are available in one go
        bIsList = true;
        // this suppresses syncing
        parentInputs.clear();
      }
      inputs.clear();
      startInputs.clear();
      for (BEASTInterface plugin : plugins) {
        inputs.add(plugin);
        startInputs.add(plugin);
      }

      if (!bIsList) {
        _input = new FlexibleInput<BEASTInterface>();
      } else {
        _input = new FlexibleInput<ArrayList<BEASTInterface>>(new ArrayList<BEASTInterface>());
      }
      _input.setRule(Validate.REQUIRED);
      syncTo(iPartition);
      //            if (parentPlugins != null && parentPlugins.size() > 0)
      //                System.err.println("sync " + parentPlugins.get(iPartition) + "[?] = " +
      // _input.get());

      if (bIsList) {
        checkForDups((List<Object>) _input.get());
      }

      return _input;
    } catch (Exception e) {
      System.err.println(
          "Warning: could not find objects in path " + Arrays.toString(sPathComponents));
    }
    return null;
  } // resolveInputs
示例#6
0
  public String toXML(BEASTInterface beastObject, Collection<BEASTInterface> others) {
    try {
      StringBuffer buf = new StringBuffer();
      buf.append(
          "<"
              + XMLParser.BEAST_ELEMENT
              + " version='2.0' namespace='"
              + DEFAULT_NAMESPACE
              + "'>\n");
      for (String element : element2ClassMap.keySet()) {
        if (!reservedElements.contains(element)) {
          buf.append("<map name='" + element + "'>" + element2ClassMap.get(element) + "</map>\n");
        }
      }
      buf.append("\n\n");
      isDone = new HashSet<>();
      isInputsDone = new HashMap<>();
      IDs = new HashSet<>();
      indent = 0;
      beastObjectToXML(beastObject, buf, null, true);
      String endBeastString = "</" + XMLParser.BEAST_ELEMENT + ">";
      buf.append(endBeastString);
      // return buf.toString();
      // beautify XML hierarchy
      String xml = cleanUpXML(buf.toString(), m_sXMLBeuatifyXSL);
      // TODO: fix m_sIDRefReplacementXSL script to deal with nested taxon sets
      // String xml2 = cleanUpXML(xml, m_sIDRefReplacementXSL);
      String xml2 = xml;
      xml = findPlates(xml2);
      // beatify by applying name spaces to spec attributes
      String[] nameSpaces = DEFAULT_NAMESPACE.split(":");
      for (String nameSpace : nameSpaces) {
        xml = xml.replaceAll("spec=\"" + nameSpace + ".", "spec=\"");
      }

      buf = new StringBuffer();
      if (others.size() > 0) {
        for (BEASTInterface beastObject2 : others) {
          if (!IDs.contains(beastObject2.getID())) {
            beastObjectToXML(beastObject2, buf, null, false);
          }
        }
      }
      int endIndex = xml.indexOf(endBeastString);
      String extras = buf.toString();
      // prevent double -- inside XML comment, this can happen in sequences
      extras = extras.replaceAll("--", "- - ");
      xml =
          xml.substring(0, endIndex) // + "\n\n<!-- " + DO_NOT_EDIT_WARNING + " \n\n" +
              // extras +  "\n\n-->\n\n"
              + endBeastString;

      xml = xml.replaceAll("xmlns=\"http://www.w3.org/TR/xhtml1/strict\"", "");

      xml = dedupName(xml);
      xml = sortTags(xml);

      // insert newlines in alignments
      int k = xml.indexOf("<data ");
      StringBuffer buf2 = new StringBuffer(xml);
      while (k > 0) {
        while (xml.charAt(k) != '>') {
          if (xml.charAt(k) == ' ' && !xml.startsWith("idref", k + 1)) {
            buf2.setCharAt(k, '\n');
          }
          k++;
        }
        k = xml.indexOf("<data ", k + 1);
      }

      return buf2.toString();
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  } // toXML
示例#7
0
  /**
   * produce elements for a beast object with name name, putting results in buf. It tries to create
   * XML conforming to the XML transformation rules (see XMLParser) that is moderately readable.
   */
  @SuppressWarnings("rawtypes")
  void beastObjectToXML(
      BEASTInterface beastObject, StringBuffer buf, String name, boolean isTopLevel)
      throws Exception {
    // determine element name, default is input, otherswise find one of the defaults
    String elementName = "input";
    for (String key : element2ClassMap.keySet()) {
      String className = element2ClassMap.get(key);
      Class _class = Class.forName(className);
      if (_class.equals(beastObject.getClass())) {
        elementName = key;
      }
    }

    //        if (beastObject instanceof Alignment) {
    //            elementName = XMLParser.DATA_ELEMENT;
    //        }
    //        if (beastObject instanceof Sequence) {
    //            elementName = XMLParser.SEQUENCE_ELEMENT;
    //        }
    //        if (beastObject instanceof State) {
    //            elementName = XMLParser.STATE_ELEMENT;
    //        }
    //        if (beastObject instanceof Distribution) {
    //            elementName = XMLParser.DISTRIBUTION_ELEMENT;
    //        }
    //        if (beastObject instanceof Logger) {
    //            elementName = XMLParser.LOG_ELEMENT;
    //        }
    //        if (beastObject instanceof Operator) {
    //            elementName = XMLParser.OPERATOR_ELEMENT;
    //        }
    //        if (beastObject instanceof RealParameter) {
    //            elementName = XMLParser.REAL_PARAMETER_ELEMENT;
    //        }
    //        if (beastObject instanceof Tree) {
    //            elementName = XMLParser.TREE_ELEMENT;
    //        }

    if (isTopLevel) {
      elementName = XMLParser.RUN_ELEMENT;
    }
    for (int i = 0; i < indent; i++) {
      buf.append("    ");
    }
    indent++;

    // open element
    buf.append("<").append(elementName);

    boolean skipInputs = false;
    if (isDone.stream().anyMatch(x -> x == beastObject)) {
      // XML is already produced, we can idref it
      buf.append(" idref='" + normalise(beastObject.getID()) + "'");
      skipInputs = true;
    } else {
      // see whether a reasonable id can be generated
      if (beastObject.getID() != null && !beastObject.getID().equals("")) {
        String id = beastObject.getID();
        // ensure ID is unique
        if (IDs.contains(id)) {
          int k = 1;
          while (IDs.contains(id + k)) {
            k++;
          }
          id = id + k;
        }
        buf.append(" id='" + normalise(id) + "'");
        IDs.add(id);
      }
      isDone.add(beastObject);
    }
    String className = beastObject.getClass().getName();
    if (skipInputs == false
        && (!element2ClassMap.containsKey(elementName)
            || !element2ClassMap.get(elementName).equals(className))) {
      // only add spec element if it cannot be deduced otherwise (i.e., by idref or default mapping
      buf.append(" spec='" + className + "'");
    }
    if (name != null && !name.equals(elementName)) {
      // only add name element if it differs from element = default name
      buf.append(" name='" + name + "'");
    }

    if (!skipInputs) {
      // process inputs of this beast object
      // first, collect values as attributes
      List<Input<?>> inputs = beastObject.listInputs();
      for (Input<?> input : inputs) {
        Object value = input.get();
        inputToXML(input, value, beastObject, buf, true);
      }
      // next, collect values as input elements
      StringBuffer buf2 = new StringBuffer();
      for (Input input : inputs) {
        Object value = input.get();
        inputToXML(input, value, beastObject, buf2, false);
      }
      if (buf2.length() == 0) {
        // if nothing was added by the inputs, close element
        indent--;
        buf.append("/>\n");
      } else {
        // add contribution of inputs
        if (buf2.indexOf("<") >= 0) {
          buf.append(">\n");
          buf.append(buf2);
          indent--;
          for (int i = 0; i < indent; i++) {
            buf.append("    ");
          }
        } else {
          buf.append(">");
          buf.append(buf2.toString().trim());
          indent--;
        }
        // add closing element
        buf.append("</" + elementName + ">\n");
      }
    } else {
      // close element
      indent--;
      buf.append("/>\n");
    }
    if (indent < 2) {
      buf.append("\n");
    }
  } // pluginToXML
示例#8
0
  /**
   * Produce JSON fragment for a beast object with given name, putting results in buf. It tries to
   * create JSON conforming to the JSON transformation rules (see JSONParser) that is moderately
   * readable.
   */
  void beastObjectToJSON(
      BEASTInterface beastObject,
      Class<?> defaultType,
      StringBuffer buf,
      String name,
      boolean isTopLevel)
      throws Exception {
    // determine element name, default is input, otherwise find one of the defaults

    String indent = "";
    for (int i = 0; i < indentCount; i++) {
      indent += "\t";
      // buf.append("    ");
    }
    indentCount++;

    // open element
    boolean needsComma = false;
    if (name != null) {
      // buf.append((indentCount == 1 ? "" : indent.substring(1)) + " \"" + name + "\": {");
      buf.append((indentCount == 1 ? "" : indent.substring(1)) + " " + name + ": {");
    } else {
      buf.append(indent + "{");
    }

    boolean skipInputs = false;
    if (isDone.contains(beastObject)) {
      // JSON is already produced, we can idref it
      buf.append((needsComma == true) ? ",\n" + indent + " " : "");
      buf.append("idref: \"" + beastObject.getID() + "\" ");
      needsComma = true;
      skipInputs = true;
    } else {
      // see whether a reasonable id can be generated
      if (beastObject.getID() != null && !beastObject.getID().equals("")) {
        String id = beastObject.getID();
        // ensure ID is unique
        if (IDs.contains(id)) {
          int k = 1;
          while (IDs.contains(id + k)) {
            k++;
          }
          id = id + k;
        }
        buf.append((needsComma == true) ? ",\n" + indent + " " : "");
        buf.append("id: \"" + normalise(null, id) + "\"");
        needsComma = true;
        IDs.add(id);
      }
      isDone.add(beastObject);
    }
    String className = beastObject.getClass().getName();
    if (skipInputs == false) {
      // only add spec element if it cannot be deduced otherwise (i.e., by idref)
      if (defaultType != null && !defaultType.getName().equals(className)) {
        buf.append((needsComma == true) ? ",\n" + indent + " " : "");
        // buf.append("\"spec\": \"" + className + "\"");
        buf.append("spec: \"" + className + "\"");
        needsComma = true;
      }
    }

    if (!skipInputs) {
      // process inputs of this beastObject
      // first, collect values as attributes
      List<Input<?>> inputs = beastObject.listInputs();
      // List<InputType> inputs = XMLParserUtils.listInputs(beastObject.getClass(), beastObject);
      for (Input<?> input : inputs) {
        StringBuffer buf2 = new StringBuffer();
        Object value = input.get();
        inputToJSON(input, value, beastObject, buf2, true, indent);
        if (buf2.length() > 0) {
          buf.append((needsComma == true) ? "," : "");
          buf.append(buf2);
          needsComma = true;
        }
      }
      // next, collect values as input elements
      StringBuffer buf2 = new StringBuffer();
      for (Input<?> input : inputs) {
        StringBuffer buf3 = new StringBuffer();
        Object value = input.get();
        inputToJSON(input, value, beastObject, buf3, false, indent);
        if (buf3.length() > 0) {
          buf2.append((needsComma == true) ? ",\n" : "\n");
          buf2.append(buf3);
          needsComma = true;
        }
      }
      if (buf2.length() != 0) {
        buf.append(buf2);
      }
      indentCount--;
      if (needsComma) {
        buf.append("\n" + indent);
      }
      needsComma = true;
    } else {
      // close element
      indentCount--;
      buf.append("");
      needsComma = true;
    }
    // if (m_nIndent < 2) {
    // collapse newlines if there are no sub-objects
    String str = buf.toString();
    if (str.indexOf('}') < 0 && str.length() < 1024) {
      str = str.replaceAll("\\s+", " ");
      buf.delete(0, buf.length());
      buf.append(indent);
      buf.append(str);
    }

    buf.append("}");
    // }
  } // beastObjectToJSON