ANN.java [src/csip/utils] Revision: default  Date:
/*
 * $Id$
 *
 * This file is part of the Cloud Services Integration Platform (CSIP),
 * a Model-as-a-Service framework, API and application suite.
 *
 * 2012-2022, Olaf David and others, OMSLab, Colorado State University.
 *
 * OMSLab licenses this file to you under the MIT license.
 * See the LICENSE file in the project root for more information.
 */
package csip.utils;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.WildcardFileFilter;
import org.apache.commons.lang3.SerializationUtils;

/**
 * ANN ensemble file management.
 *
 * @author od
 */
public class ANN {

  public static final String ANN_EXT = ".ann";


  /**
   * Write a set of ANNs to file.
   *
   * usage: File zipAnn = writeAnns(new File("/tmp/anns"), selANNs.getANNs());
   *
   * @param annDir the directory to write them to.
   * @param anns the list of ann serializable objects
   * @return the zip file
   * @throws IOException
   */
  public static File writeAnns(File annDir, List<? extends Serializable> anns)
      throws IOException {
    if (anns.isEmpty()) {
      throw new IllegalArgumentException("Empty ann list.");
    }
    if (!annDir.exists()) {
      annDir.mkdirs();
    }
    if (!annDir.isDirectory()) {
      throw new IllegalArgumentException("Not a directory:: " + annDir);
    }
    if (annDir.list().length > 0) {
      throw new IllegalArgumentException("Not empty: " + annDir);
    }
    int i = 0;
    for (Serializable selAnn : anns) {
      byte[] ser = SerializationUtils.serialize(selAnn);
      FileUtils.writeByteArrayToFile(new File(annDir, Integer.toString(i++) + ANN_EXT), ser);
    }
    return ZipFiles.zip(annDir);
  }


  /**
   * Read ANNs from file/dir.
   *
   * usage: <code> List&gt;NEATNetwork&lt; nn = (List&gt;NEATNetwork&lt;) readANNs(new
   * File("/tmp/anns.zip")); </code>
   *
   * @param ens the zip file or directory
   * @return the list of serializable objects
   * @throws IOException
   */
  public static List<? extends Serializable> readANNs(File ens)
      throws IOException {
    if (ens.isFile() && ens.getName().endsWith("zip")) {
      ens = ZipFiles.unzip(ens);
    }
    if (ens.isDirectory()) {
      File[] files = ens.listFiles((FilenameFilter) new WildcardFileFilter("*" + ANN_EXT));
      if (files.length == 0) {
        throw new IllegalArgumentException("No ANNs found for ensemble: " + ens);
      }
      List<Serializable> l = new ArrayList<>();
      for (File file : files) {
        byte[] ann = FileUtils.readFileToByteArray(file);
        l.add((Serializable) SerializationUtils.deserialize(ann));
      }
      return l;
    }
    throw new IllegalArgumentException("Not a valid ANN resource: " + ens);
  }
}