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

net.maizegenetics.pangenome.api.GraphIO Maven / Gradle / Ivy

There is a newer version: 1.10
Show newest version
package net.maizegenetics.pangenome.api;

import net.maizegenetics.util.Utils;
import org.apache.log4j.Logger;

import java.io.BufferedWriter;

/**
 * @author Terry Casstevens Created August 29, 2017
 */
public class GraphIO {

    private static final Logger myLogger = Logger.getLogger(GraphIO.class);

    private GraphIO() {
        // utility
    }

    /**
     * Writes given graph to fasta format. The information line for
     * each sequence is the haplotypes.haplotypes_id
     *
     * @param graph graph
     * @param filename output filename
     *
     * @return name of file written (adds .fa if needed)
     */
    public static String writeFasta(HaplotypeGraph graph, String filename) {

        String file = Utils.addSuffixIfNeeded(filename, ".fa");

        try (BufferedWriter writer = Utils.getBufferedWriter(file)) {

            graph.nodeStream()
                    .forEach(node -> {
                        try {
                            writer.write(">");
                            writer.write(String.valueOf(node.id()));
                            writer.write("\n");
                            writer.write(node.haplotypeSequence().sequence());
                            writer.write("\n");
                        } catch (Exception e) {
                            myLogger.debug(e.getMessage(), e);
                            throw new IllegalStateException("GraphIO: writeFasta: problem writing: " + file + "\n" + e.getMessage());
                        }
                    });

            myLogger.info("writeFasta: wrote file: " + file);

            return file;

        } catch (Exception e) {
            myLogger.debug(e.getMessage(), e);
            throw new IllegalStateException("GraphIO: writeFasta: problem writing: " + file + "\n" + e.getMessage());
        }

    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy