Search in sources :

Example 11 with ExecutableException

use of org.vcell.util.exe.ExecutableException in project vcell by virtualcell.

the class VisitSupport method launchVisTool.

public static void launchVisTool(File visitExecutable, SimulationDataSetRef simulationDataSetRef) throws IOException, ExecutableException, URISyntaxException, InterruptedException {
    if (OperatingSystemInfo.getInstance().isMac()) {
        launchVisToolMac(visitExecutable);
        return;
    } else if (OperatingSystemInfo.getInstance().isLinux()) {
        launchVisToolLinux(visitExecutable);
        return;
    }
    // MSWindows
    if (visitExecutable == null) {
        visitExecutable = ResourceUtil.getExecutable(VISIT_EXEC_NAME, false);
        if (visitExecutable == null || !visitExecutable.exists() || !visitExecutable.isFile()) {
            throw new IOException("visit executable not found, " + visitExecutable.getAbsolutePath());
        }
    }
    VCellConfiguration.setFileProperty(PropertyLoader.visitExe, visitExecutable);
    File visMainCLI = getVisToolPythonScript();
    if (!visMainCLI.exists() || !visMainCLI.isFile()) {
        throw new IOException("vcell/visit main python file not found, " + visMainCLI.getAbsolutePath());
    }
    if (lg.isInfoEnabled()) {
        lg.info("Starting VCellVisIt as a sub-process");
    }
    // 
    // get existing environment variables and add visit command and python script to it.
    // 
    Map<String, String> envVariables = System.getenv();
    ArrayList<String> envVarList = new ArrayList<String>();
    for (String varname : envVariables.keySet()) {
        String value = envVariables.get(varname);
        envVarList.add(varname + "=" + value);
    }
    String siteName = ResourceUtil.getSiteName();
    File vcellHomeVisFolder = new File(new File(ResourceUtil.getVcellHome(), "Vis"), siteName);
    if (!vcellHomeVisFolder.exists()) {
        if (!vcellHomeVisFolder.mkdirs()) {
            throw new IOException("Cannot create directory " + vcellHomeVisFolder.getCanonicalPath());
        }
    }
    // FileUtils.copyDirectoryShallow(visMainCLI.getParentFile(), vcellHomeVisFolder);
    FileUtils.copyDirectory(visMainCLI.getParentFile(), vcellHomeVisFolder, true, new VisitFolderFileFilter());
    File vcellHomeVisMainCLI = new File(vcellHomeVisFolder, visMainCLI.getName());
    vcellHomeVisMainCLI.setExecutable(true);
    envVarList.add("visitcmd=" + /*"\""+*/
    visitExecutable.getPath());
    envVarList.add("pythonscript=" + vcellHomeVisMainCLI.getPath().replace("\\", "/"));
    // envVarList.add("pythonscript="+visMainCLI.toURI().toASCIIString());
    final String[] cmdStringArray = new String[] { "cmd", "/K", "start", "\"\"", visitExecutable.getPath(), "-cli", "-uifile", vcellHomeVisMainCLI.getPath().replace("\\", "/") };
    if (simulationDataSetRef != null) {
        File simDataSetRefFile = new File(ResourceUtil.getLocalVisDataDir(), "SimID_" + simulationDataSetRef.getSimId() + "_" + simulationDataSetRef.getJobIndex() + "_.simref");
        VisMeshUtils.writeSimulationDataSetRef(simDataSetRefFile, simulationDataSetRef);
        envVarList.add("INITIALSIMDATAREFFILE=" + simDataSetRefFile.getPath().replace("\\", "/"));
    }
    // @SuppressWarnings("unused")
    new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                Executable exec = new Executable(cmdStringArray);
                // Executable exec = new Executable(new String[] {st});
                for (String var : envVarList) {
                    StringTokenizer st2 = new StringTokenizer(var, "=");
                    exec.addEnvironmentVariable(st2.nextToken(), st2.nextToken());
                }
                exec.start();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }).start();
    if (lg.isInfoEnabled()) {
        lg.info("Started VCellVisIt");
    }
/*
			List<String> cmds = new ArrayList<String>();
			cmds.add(visitExecutable.getAbsolutePath());
			cmds.add("-cli");
			cmds.add("-ufile");
			cmds.add(script.getAbsolutePath());
			ProcessBuilder pb = new ProcessBuilder(cmds);
			final Process p = pb.start();
			Runnable mon = new Runnable() {
				
				@Override
				public void run() {
					try {
						System.err.println("waiting for visit");
						p.waitFor();
						int rcode = p.exitValue();
						System.err.println("visit exit code " + rcode);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			};
			new Thread(mon).start();
			*/
}
Also used : ArrayList(java.util.ArrayList) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) ExecutableException(org.vcell.util.exe.ExecutableException) StringTokenizer(java.util.StringTokenizer) Executable(org.vcell.util.exe.Executable) File(java.io.File)

Example 12 with ExecutableException

use of org.vcell.util.exe.ExecutableException in project vcell by virtualcell.

the class SBMLStandaloneImporter method attemptImport.

private BioModel attemptImport(File sbmlFile) throws ExecutableException, IOException, ClassNotFoundException, XmlParseException {
    if (subProcess == null || subProcess.getStatus() != LiveProcessStatus.RUNNING) {
        subProcess = createProcess();
    }
    toChildProcess.writeObject(sbmlFile);
    Object back = fromChildProcess.readObject();
    if (back instanceof String) {
        String xml = (String) back;
        if (lg.isDebugEnabled()) {
            try (FileWriter fw = new FileWriter(sbmlFile.getAbsolutePath() + ".dump")) {
                fw.append(xml);
            }
        }
        XMLSource source = new XMLSource(xml);
        return XmlHelper.XMLToBioModel(source);
    }
    if (back instanceof Exception) {
        try {
            throw (Exception) back;
        } catch (SBMLImportException sie) {
            throw sie;
        } catch (Exception e) {
            throw new ExecutableException("child process exception", e);
        }
    }
    throw new ExecutableException("unexpected object from child process:  " + back.getClass().getName() + " " + back.toString());
}
Also used : ExecutableException(org.vcell.util.exe.ExecutableException) FileWriter(java.io.FileWriter) XMLSource(cbit.vcell.xml.XMLSource) ExecutableException(org.vcell.util.exe.ExecutableException) SocketException(java.net.SocketException) SocketTimeoutException(java.net.SocketTimeoutException) XmlParseException(cbit.vcell.xml.XmlParseException) IOException(java.io.IOException)

Example 13 with ExecutableException

use of org.vcell.util.exe.ExecutableException in project vcell by virtualcell.

the class SBMLStandaloneImporter method createProcess.

private LiveProcess<ClosedInput, InheritOutput, InheritOutput> createProcess() throws ExecutableException, IOException {
    @SuppressWarnings("resource") ServerSocket ss = new ServerSocket(0);
    InetSocketAddress isa = (InetSocketAddress) ss.getLocalSocketAddress();
    String home = System.getProperty("java.home");
    String exe = home + "/bin/java";
    String classpath = System.getProperty("java.class.path");
    String us = getClass().getName();
    ArrayList<String> cmdArgs = new ArrayList<String>();
    cmdArgs.add(exe);
    cmdArgs.addAll(jvmArgs());
    String[] invokeArgs = { "-classpath", classpath, us };
    cmdArgs.addAll(Arrays.asList(invokeArgs));
    InheritOutput i = new InheritOutput();
    LiveProcess<ClosedInput, InheritOutput, InheritOutput> lp = new LiveProcess<ClosedInput, InheritOutput, InheritOutput>(new ClosedInput(), i, i, cmdArgs.toArray(new String[cmdArgs.size()]));
    lp.setEnvironment(PORT_KEY, Integer.toString(isa.getPort()));
    lp.setEnvironment(HOST_KEY, isa.getHostName());
    lp.begin(OUR_LABEL);
    ss.setSoTimeout(START_TIMEOUT_SECONDS * 1000);
    try {
        channel = ss.accept();
    } catch (SocketTimeoutException sto) {
        throw new ExecutableException("Standalone client failed to communicate in " + START_TIMEOUT_SECONDS + " seconds");
    }
    toChildProcess = new ObjectOutputStream(channel.getOutputStream());
    fromChildProcess = new ObjectInputStream(channel.getInputStream());
    return lp;
}
Also used : ClosedInput(org.vcell.util.executable.ClosedInput) ExecutableException(org.vcell.util.exe.ExecutableException) InetSocketAddress(java.net.InetSocketAddress) ArrayList(java.util.ArrayList) ServerSocket(java.net.ServerSocket) ObjectOutputStream(java.io.ObjectOutputStream) InheritOutput(org.vcell.util.executable.InheritOutput) LiveProcess(org.vcell.util.executable.LiveProcess) SocketTimeoutException(java.net.SocketTimeoutException) ObjectInputStream(java.io.ObjectInputStream)

Example 14 with ExecutableException

use of org.vcell.util.exe.ExecutableException in project vcell by virtualcell.

the class NFSimSolver method main.

public static void main(String[] args) {
    String baseName = "SimID_";
    String workingDir = "C:\\Users\\jmasison\\.vcell\\simdata\\user\\sub\\";
    String executable = "C:\\Users\\jmasison\\workspace\\VCell_trunk\\localsolvers\\win64\\NFsim_x64.exe";
    String blankDelimiters = " \t";
    String debugfile = "C:\\Users\\jmasison\\.vcell\\simdata\\user\\sub\\debug.txt";
    int seed = 1807259453;
    int steps = 100;
    // unit system is in sec
    double duration = 0.1;
    Map<Integer, Double> timestepMap = new HashMap<>();
    BufferedReader br = null;
    PrintWriter writer = null;
    try {
        writer = new PrintWriter(debugfile, "UTF-8");
        for (int i = 1; i < steps + 1; i++) {
            // print				writer.println("\t\t\t\tentering i loop");
            // C:\\TEMP\\eee\\SimID_000.nfsimInput
            String input = workingDir + baseName + "000" + ".nfsimInput";
            String output = workingDir + baseName + i + ".gdat";
            String species = workingDir + baseName + i + ".species";
            double interval = duration / steps;
            // we start at timepoint 0
            double dur = interval * (i - 1);
            String sdur = "" + dur;
            if (sdur.length() > 6) {
                sdur = sdur.substring(0, 6);
            }
            // average length of patterns at this timepoint, over many simulations
            double averageOfAverage = 0;
            int numSimulations = 50;
            for (int ii = 0; ii < numSimulations; ii++) {
                // print					writer.println("\t\t\t\t\tentering ii loop");
                // calculate a new seed for this simulation (same start seeds will be used for each time point)
                int curSeed = seed + ii * 538297;
                // String command = executable + " -seed " + curSeed + " -vcell -xml " + input + " -o " + output + " -sim " + sdur + " -ss " + species + " -oSteps 1" + " -notf -cb";
                // Process p = Runtime.getRuntime().exec(command);
                // p.waitFor();
                String curspecies = species + "_sim_" + ii;
                String[] commands = new String[] { executable, "-seed", Integer.toString(curSeed), "-vcell", "-xml", input, "-o", output, "-sim", sdur, "-ss", curspecies, "-oSteps", "1", "-notf", "-cb" };
                MathExecutable mathExe = new MathExecutable(commands, new File(workingDir));
                try {
                    mathExe.start();
                } catch (ExecutableException e) {
                    e.printStackTrace();
                    System.out.println("exe failed, exitValue=" + mathExe.getExitValue() + ", \nstderr=" + mathExe.getStderrString() + ", \nstdout=" + mathExe.getStdoutString());
                }
                // command = "cmd.exe /c del " + workingDir + "*.gdat";
                // p = Runtime.getRuntime().exec(command);
                // p.waitFor();
                // delete the intermediate .gdat files
                // MathExecutable mathExeDel = new MathExecutable(new String[] {"cmd.exe", "/c", "del", workingDir, "*.gdat"}, new File(workingDir));
                // try {
                // mathExeDel.start();
                // } catch (ExecutableException e) {
                // e.printStackTrace();
                // }
                Map<Integer, Integer> occurencesMap = new HashMap<>();
                br = new BufferedReader(new FileReader(curspecies));
                // ex: A(s!1,t!2).B(u!1).B(u!2)  5
                String line;
                while ((line = br.readLine()) != null) {
                    if (line.startsWith("#")) {
                        continue;
                    }
                    // how many molecules in the above pattern => 3
                    int numMolecules = 1;
                    // how many instances of this pattern => 5
                    int number;
                    StringTokenizer nextLine = new StringTokenizer(line, blankDelimiters);
                    // A(s!1,t!2).B(u!1).B(u!2)
                    String pattern = nextLine.nextToken();
                    for (int j = 0; j < pattern.length(); j++) {
                        if (pattern.charAt(j) == '.') {
                            // numMolecules equals the number of 'dot' characters in string + 1
                            numMolecules++;
                        }
                    }
                    // 5
                    String s = nextLine.nextToken();
                    number = Integer.parseInt(s);
                    if (occurencesMap.containsKey(numMolecules)) {
                        int currentNumber = occurencesMap.get(numMolecules);
                        currentNumber += number;
                        occurencesMap.put(numMolecules, currentNumber);
                    } else {
                        occurencesMap.put(numMolecules, number);
                    }
                }
                double up = 0;
                double down = 0;
                for (Map.Entry<Integer, Integer> entry : occurencesMap.entrySet()) {
                    Integer key = entry.getKey();
                    if (key == 1) {
                        continue;
                    }
                    Integer value = entry.getValue();
                    up += key * value;
                    down += value;
                // print						writer.println(curspecies+"_"+i+" : "+ up + ", " + down);
                }
                double average;
                if (down > 0) {
                    average = up / down;
                } else {
                    average = 0;
                }
                // print					writer.println("average: "+average);; writer.println();
                averageOfAverage += average;
                // print					writer.println("Avergae_of_average_for_sim_"+ii+"_time_"+i+" : "+average);; writer.println();
                br.close();
            // if uncimmented make sure to use mathexecutable
            // command = "cmd.exe /c del " + workingDir + "*.species";
            // p = Runtime.getRuntime().exec(command);
            // p.waitFor();
            }
            averageOfAverage = averageOfAverage / numSimulations;
            // print				writer.println("Final_average_for_time_"+i+" : "+averageOfAverage); writer.println();
            // save average for time step (i) to map
            timestepMap.put(i, averageOfAverage);
        }
        // exited both loops
        // print		writer.println();
        writer.println("Time\tAverageCLusterSize");
        for (int j = 1; j < steps + 1; j++) {
            writer.println((j - 1) + "\t" + timestepMap.get(j));
        }
        writer.println();
        writer.println("Done");
        writer.close();
        System.out.println("\n\n\n\nDone\n\n");
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (br != null) {
                br.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}
Also used : HashMap(java.util.HashMap) ExecutableException(org.vcell.util.exe.ExecutableException) MathExecutable(cbit.vcell.solvers.MathExecutable) IOException(java.io.IOException) StringTokenizer(java.util.StringTokenizer) BufferedReader(java.io.BufferedReader) FileReader(java.io.FileReader) File(java.io.File) HashMap(java.util.HashMap) Map(java.util.Map) PrintWriter(java.io.PrintWriter)

Example 15 with ExecutableException

use of org.vcell.util.exe.ExecutableException in project vcell by virtualcell.

the class CommandServiceSshNativeTest method test_install_secret_keyfile.

@Test
public void test_install_secret_keyfile() throws IOException, ExecutableException {
    CommandServiceSshNative cmd = null;
    try {
        cmd = new CommandServiceSshNative("vcell-service.cam.uchc.edu", "vcell", new File("/Users/schaff/.ssh/schaff_rsa"), new File("/Users/schaff"));
        System.out.println("after created cmdService");
        CommandOutput output = cmd.command(new String[] { "ls -al | head -4" });
        System.out.println("ls output is: " + output.getStandardOutput());
        output = cmd.command(new String[] { "ls -al | head -9" });
        System.out.println("ls output is: " + output.getStandardOutput());
        output = cmd.command(new String[] { "ls -al | head -4" });
        System.out.println("ls output is: " + output.getStandardOutput());
    } catch (Exception e) {
        e.printStackTrace();
        fail("exception thrown: " + e.getMessage());
    } finally {
        if (cmd != null) {
            cmd.close();
        }
    }
}
Also used : CommandOutput(cbit.vcell.message.server.cmd.CommandService.CommandOutput) File(java.io.File) IOException(java.io.IOException) ExecutableException(org.vcell.util.exe.ExecutableException) Test(org.junit.Test)

Aggregations

ExecutableException (org.vcell.util.exe.ExecutableException)19 File (java.io.File)12 IOException (java.io.IOException)12 CommandOutput (cbit.vcell.message.server.cmd.CommandService.CommandOutput)6 Test (org.junit.Test)5 Executable (org.vcell.util.exe.Executable)5 ArrayList (java.util.ArrayList)4 IExecutable (org.vcell.util.exe.IExecutable)4 InstallStatus (cbit.vcell.resource.PythonSupport.InstallStatus)2 HtcJobID (cbit.vcell.server.HtcJobID)2 FileWriter (java.io.FileWriter)2 PrintWriter (java.io.PrintWriter)2 SocketTimeoutException (java.net.SocketTimeoutException)2 URISyntaxException (java.net.URISyntaxException)2 StringTokenizer (java.util.StringTokenizer)2 CommandServiceSshNative (cbit.vcell.message.server.cmd.CommandServiceSshNative)1 HtcJobNotFoundException (cbit.vcell.message.server.htc.HtcJobNotFoundException)1 HtcJobStatus (cbit.vcell.message.server.htc.HtcJobStatus)1 JobInfoAndStatus (cbit.vcell.message.server.htc.HtcProxy.JobInfoAndStatus)1 OperatingSystemInfo (cbit.vcell.resource.OperatingSystemInfo)1