<commit_before>/*******************************************************************************
 *  
 * This file is part of iBioSim. Please visit <http://www.async.ece.utah.edu/ibiosim>
 * for the latest version of iBioSim.
 *
 * Copyright (C) 2017 University of Utah
 *
 * This library is free software; you can redistribute it and/or modify it
 * under the terms of the Apache License. A copy of the license agreement is provided
 * in the file named "LICENSE.txt" included with this software distribution
 * and also available online at <http://www.async.ece.utah.edu/ibiosim/License>.
 *  
 *******************************************************************************/
package edu.utah.ece.async.ibiosim.analysis;

import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.prefs.Preferences;

import javax.xml.stream.XMLStreamException;

import org.sbml.jsbml.Model;

import edu.utah.ece.async.ibiosim.analysis.fba.FluxBalanceAnalysis;
import edu.utah.ece.async.ibiosim.analysis.markov.BuildStateGraphThread;
import edu.utah.ece.async.ibiosim.analysis.markov.PerformSteadyStateMarkovAnalysisThread;
import edu.utah.ece.async.ibiosim.analysis.markov.PerformTransientMarkovAnalysisThread;
import edu.utah.ece.async.ibiosim.analysis.markov.StateGraph;
import edu.utah.ece.async.ibiosim.analysis.markov.StateGraph.Property;
import edu.utah.ece.async.ibiosim.analysis.properties.AdvancedProperties;
import edu.utah.ece.async.ibiosim.analysis.properties.AnalysisProperties;
import edu.utah.ece.async.ibiosim.analysis.simulation.DynamicSimulation;
import edu.utah.ece.async.ibiosim.analysis.simulation.DynamicSimulation.SimulationType;
import edu.utah.ece.async.ibiosim.analysis.simulation.flattened.Simulator;
import edu.utah.ece.async.ibiosim.dataModels.biomodel.parser.BioModel;
import edu.utah.ece.async.ibiosim.dataModels.biomodel.util.SBMLutilities;
import edu.utah.ece.async.ibiosim.dataModels.biomodel.util.Utility;
import edu.utah.ece.async.ibiosim.dataModels.util.Executables;
import edu.utah.ece.async.ibiosim.dataModels.util.Message;
import edu.utah.ece.async.ibiosim.dataModels.util.MutableString;
import edu.utah.ece.async.ibiosim.dataModels.util.exceptions.BioSimException;
import edu.utah.ece.async.ibiosim.dataModels.util.observe.CoreObservable;
import edu.utah.ece.async.lema.verification.lpn.Abstraction;
import edu.utah.ece.async.lema.verification.lpn.LPN;
import edu.utah.ece.async.lema.verification.lpn.Translator;

public class Run extends CoreObservable implements ActionListener
{

  private final AnalysisProperties properties;
  private FileWriter logFile;

  private final Message message = new Message();
  private final Runtime exec = Runtime.getRuntime();

  private Process reb2sac;
  private StateGraph sg;
  private DynamicSimulation dynSim;

  private File work;

  public Run(AnalysisProperties properties)
  {
    this.properties = properties;
  }

  public int execute() throws IOException, XMLStreamException, InterruptedException, BioSimException
  {
    Runtime exec = Runtime.getRuntime();
    int exitValue = 255;
    long time1, time2;

    String modelFile = properties.getModelFile();
    String filename = properties.getFilename();
    
    work = new File(properties.getDirectory());
    
    if (properties.isNary() && properties.isGui() && (properties.isSsa() || properties.isXhtml() || properties.isDot()))
    {
      exitValue =  executeNary();
    }

    if (properties.isNary() && !properties.isGui() && !properties.getSim().contains("markov-chain-analysis") && properties.getSimulationProperties().getRun() == 1)
    {
      message.setLog("Executing:\n" + Executables.reb2sacExecutable + " --target.encoding=nary-level " + filename);
      this.notifyObservers(message);
      time1 = System.nanoTime();
      reb2sac = exec.exec(Executables.reb2sacExecutable + " --target.encoding=nary-level " + modelFile, Executables.envp, work);
    }
    else if (properties.isFba())
    {
      time1 = System.nanoTime();
      exitValue =  executeFBA( );
    }
    else if (properties.isSbml())
    {
      time1 = System.nanoTime();
      exitValue = executeSBML();
    }
    else if (properties.isDot())
    {
      time1 = System.nanoTime();
      exitValue =  executeDot();
    }
    else if (properties.isXhtml())
    {
      time1 = System.nanoTime();
      exitValue = executeXhtml( );
    }
    else if (properties.getSim().equals("atacs"))
    {
      time1 = System.nanoTime();
      exitValue = executeAtacs( );
    }
    else if (properties.getSim().equals("prism"))
    {
      time1 = System.nanoTime();
      exitValue = executePrism( );
    }
    else if (properties.getSim().contains("markov-chain-analysis") || properties.getSim().equals("reachability-analysis"))
    {
      time1 = System.nanoTime();
      exitValue = executeMarkov();
    }
    else
    {
      time1 = System.nanoTime();
      exitValue = executeSimulation();

    }

    //updateReb2SacProgress();
    time2 = System.nanoTime();
    displayError(exitValue);


    String time = SBMLutilities.createTimeString(time1, time2);


    message.setLog("Total Simulation Time: " + time + "\n\n");
    this.notifyObservers(message);
    return exitValue;
  }

  private void displayError(int exitValue)
  {
    if (exitValue == 143)
    {
      message.setErrorDialog("The simulation was" + " canceled by the user.", "Canceled Simulation");
      this.notifyObservers(message);
    }
    else if (exitValue == 139)
    {
      message.setErrorDialog("The selected model is not a valid sbml file." + "\nYou must select an sbml file.", "Not An SBML File");
      this.notifyObservers(message);
    }
    else if(exitValue != 0)
    {
      message.setErrorDialog( "Error In Execution!\n" + "Bad Return Value!\n" + "The reb2sac program returned " + exitValue + " as an exit value.", "Error");
      this.notifyObservers(message);
    }
  }

  private int executeFBA() throws XMLStreamException, IOException
  {
    int exitValue = 255;

    FluxBalanceAnalysis fluxBalanceAnalysis = new FluxBalanceAnalysis(properties.getRoot() + File.separator, properties.getFilename(), properties.getSimulationProperties().getAbsError());
    exitValue = fluxBalanceAnalysis.PerformFluxBalanceAnalysis();

    if (exitValue == 1)
    {
      message.setErrorDialog("Error", "Flux balance analysis did not converge.");
    }
    else if (exitValue == 2)
    {
      message.setErrorDialog("Error", "Flux balance analysis failed.");
    }
    else if (exitValue == -1)
    {
      message.setErrorDialog("Error", "No flux balance constraints.");
    }
    else if (exitValue == -2)
    {
      message.setErrorDialog("Error", "Initial point must be strictly feasible.");
    }
    else if (exitValue == -3)<commit_msg>Fixed bug when running FBA.<commit_after>/*******************************************************************************
 *  
 * This file is part of iBioSim. Please visit <http://www.async.ece.utah.edu/ibiosim>
 * for the latest version of iBioSim.
 *
 * Copyright (C) 2017 University of Utah
 *
 * This library is free software; you can redistribute it and/or modify it
 * under the terms of the Apache License. A copy of the license agreement is provided
 * in the file named "LICENSE.txt" included with this software distribution
 * and also available online at <http://www.async.ece.utah.edu/ibiosim/License>.
 *  
 *******************************************************************************/
package edu.utah.ece.async.ibiosim.analysis;

import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.prefs.Preferences;

import javax.xml.stream.XMLStreamException;

import org.sbml.jsbml.Model;

import edu.utah.ece.async.ibiosim.analysis.fba.FluxBalanceAnalysis;
import edu.utah.ece.async.ibiosim.analysis.markov.BuildStateGraphThread;
import edu.utah.ece.async.ibiosim.analysis.markov.PerformSteadyStateMarkovAnalysisThread;
import edu.utah.ece.async.ibiosim.analysis.markov.PerformTransientMarkovAnalysisThread;
import edu.utah.ece.async.ibiosim.analysis.markov.StateGraph;
import edu.utah.ece.async.ibiosim.analysis.markov.StateGraph.Property;
import edu.utah.ece.async.ibiosim.analysis.properties.AdvancedProperties;
import edu.utah.ece.async.ibiosim.analysis.properties.AnalysisProperties;
import edu.utah.ece.async.ibiosim.analysis.simulation.DynamicSimulation;
import edu.utah.ece.async.ibiosim.analysis.simulation.DynamicSimulation.SimulationType;
import edu.utah.ece.async.ibiosim.analysis.simulation.flattened.Simulator;
import edu.utah.ece.async.ibiosim.dataModels.biomodel.parser.BioModel;
import edu.utah.ece.async.ibiosim.dataModels.biomodel.util.SBMLutilities;
import edu.utah.ece.async.ibiosim.dataModels.biomodel.util.Utility;
import edu.utah.ece.async.ibiosim.dataModels.util.Executables;
import edu.utah.ece.async.ibiosim.dataModels.util.Message;
import edu.utah.ece.async.ibiosim.dataModels.util.MutableString;
import edu.utah.ece.async.ibiosim.dataModels.util.exceptions.BioSimException;
import edu.utah.ece.async.ibiosim.dataModels.util.observe.CoreObservable;
import edu.utah.ece.async.lema.verification.lpn.Abstraction;
import edu.utah.ece.async.lema.verification.lpn.LPN;
import edu.utah.ece.async.lema.verification.lpn.Translator;

public class Run extends CoreObservable implements ActionListener
{

  private final AnalysisProperties properties;
  private FileWriter logFile;

  private final Message message = new Message();
  private final Runtime exec = Runtime.getRuntime();

  private Process reb2sac;
  private StateGraph sg;
  private DynamicSimulation dynSim;

  private File work;

  public Run(AnalysisProperties properties)
  {
    this.properties = properties;
  }

  public int execute() throws IOException, XMLStreamException, InterruptedException, BioSimException
  {
    Runtime exec = Runtime.getRuntime();
    int exitValue = 255;
    long time1, time2;

    String modelFile = properties.getModelFile();
    String filename = properties.getFilename();
    
    work = new File(properties.getDirectory());
    
    if (properties.isNary() && properties.isGui() && (properties.isSsa() || properties.isXhtml() || properties.isDot()))
    {
      exitValue =  executeNary();
    }

    if (properties.isNary() && !properties.isGui() && !properties.getSim().contains("markov-chain-analysis") && properties.getSimulationProperties().getRun() == 1)
    {
      message.setLog("Executing:\n" + Executables.reb2sacExecutable + " --target.encoding=nary-level " + filename);
      this.notifyObservers(message);
      time1 = System.nanoTime();
      reb2sac = exec.exec(Executables.reb2sacExecutable + " --target.encoding=nary-level " + modelFile, Executables.envp, work);
    }
    else if (properties.isFba())
    {
      time1 = System.nanoTime();
      exitValue =  executeFBA( );
    }
    else if (properties.isSbml())
    {
      time1 = System.nanoTime();
      exitValue = executeSBML();
    }
    else if (properties.isDot())
    {
      time1 = System.nanoTime();
      exitValue =  executeDot();
    }
    else if (properties.isXhtml())
    {
      time1 = System.nanoTime();
      exitValue = executeXhtml( );
    }
    else if (properties.getSim().equals("atacs"))
    {
      time1 = System.nanoTime();
      exitValue = executeAtacs( );
    }
    else if (properties.getSim().equals("prism"))
    {
      time1 = System.nanoTime();
      exitValue = executePrism( );
    }
    else if (properties.getSim().contains("markov-chain-analysis") || properties.getSim().equals("reachability-analysis"))
    {
      time1 = System.nanoTime();
      exitValue = executeMarkov();
    }
    else
    {
      time1 = System.nanoTime();
      exitValue = executeSimulation();

    }

    //updateReb2SacProgress();
    time2 = System.nanoTime();
    displayError(exitValue);


    String time = SBMLutilities.createTimeString(time1, time2);


    message.setLog("Total Simulation Time: " + time + "\n\n");
    this.notifyObservers(message);
    return exitValue;
  }

  private void displayError(int exitValue)
  {
    if (exitValue == 143)
    {
      message.setErrorDialog("The simulation was" + " canceled by the user.", "Canceled Simulation");
      this.notifyObservers(message);
    }
    else if (exitValue == 139)
    {
      message.setErrorDialog("The selected model is not a valid sbml file." + "\nYou must select an sbml file.", "Not An SBML File");
      this.notifyObservers(message);
    }
    else if(exitValue != 0)
    {
      message.setErrorDialog( "Error In Execution!\n" + "Bad Return Value!\n" + "The reb2sac program returned " + exitValue + " as an exit value.", "Error");
      this.notifyObservers(message);
    }
  }

  private int executeFBA() throws XMLStreamException, IOException
  {
    int exitValue = 255;

    FluxBalanceAnalysis fluxBalanceAnalysis = new FluxBalanceAnalysis(properties.getDirectory()+File.separator, properties.getModelFile(), properties.getSimulationProperties().getAbsError());
    exitValue = fluxBalanceAnalysis.PerformFluxBalanceAnalysis();

    if (exitValue == 1)
    {
      message.setErrorDialog("Error", "Flux balance analysis did not converge.");
    }
    else if (exitValue == 2)
    {
      message.setErrorDialog("Error", "Flux balance analysis failed.");
    }
    else if (exitValue == -1)
    {
      message.setErrorDialog("Error", "No flux balance constraints.");
    }
    else if (exitValue == -2)
    {
      message.setErrorDialog("Error", "Initial point must be strictly feasible.");
    }
    else if (exitValue == -3)
{'fraction_non_alphanumeric': 0.14056989702355763, 'fraction_numerical': 0.0060657356467766965, 'mean_word_length': 3.9335421016005565, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 4, 'xml': 2}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6440346', 'n_tokens_mistral': 4483, 'n_tokens_neox': 4329, 'n_words': 866}