Search in sources :

Example 1 with BNGExecutorService

use of cbit.vcell.server.bionetgen.BNGExecutorService in project vcell by virtualcell.

the class RulebasedTransformer method generateNetwork.

private void generateNetwork(SimulationContext simContext, Set<ReactionRule> fromReactions, MathMappingCallback mathMappingCallback) throws ClassNotFoundException, IOException {
    TaskCallbackMessage tcm;
    BNGOutputSpec outputSpec;
    speciesEquivalenceMap.clear();
    kineticsParameterMap.clear();
    NetworkGenerationRequirements networkGenerationRequirements = NetworkGenerationRequirements.ComputeFullStandardTimeout;
    String input = convertToBngl(simContext, true, mathMappingCallback, networkGenerationRequirements);
    // System.out.println(input);		// TODO: uncomment to see the xml string
    for (Map.Entry<FakeSeedSpeciesInitialConditionsParameter, Pair<SpeciesContext, Expression>> entry : speciesEquivalenceMap.entrySet()) {
        FakeSeedSpeciesInitialConditionsParameter key = entry.getKey();
        Pair<SpeciesContext, Expression> value = entry.getValue();
        SpeciesContext sc = value.one;
        Expression initial = value.two;
        System.out.println("key: " + key.fakeParameterName + ",   species: " + sc.getName() + ", initial: " + initial.infix());
    }
    BNGInput bngInput = new BNGInput(input);
    BNGOutput bngOutput = null;
    try {
        // for the writeXML command we don't want to run iteration by iteration - it wouldn't even make sense since we don't flatten anything
        // so we run bionetgen the "old" way
        final BNGExecutorService bngService = BNGExecutorService.getInstanceOld(bngInput, networkGenerationRequirements.timeoutDurationMS);
        bngOutput = bngService.executeBNG();
    } catch (RuntimeException ex) {
        ex.printStackTrace(System.out);
        // rethrow without losing context
        throw ex;
    } catch (Exception ex) {
        ex.printStackTrace(System.out);
        throw new RuntimeException(ex.getMessage());
    }
    simContext.setInsufficientIterations(false);
    simContext.setInsufficientMaxMolecules(false);
    String bngConsoleString = bngOutput.getConsoleOutput();
    tcm = new TaskCallbackMessage(TaskCallbackStatus.DetailBatch, bngConsoleString);
    // simContext.appendToConsole(tcm);
    // String bngNetString = bngOutput.getNetFileContent();
    // outputSpec = BNGOutputFileParser.createBngOutputSpec(bngNetString);
    // //BNGOutputFileParser.printBNGNetOutput(outputSpec);			// prints all output to console
    // 
    // if (mathMappingCallback.isInterrupted()){
    // String msg = "Canceled by user.";
    // //			tcm = new TaskCallbackMessage(TaskCallbackStatus.Error, msg);
    // //			simContext.appendToConsole(tcm);
    // //			simContext.setMd5hash(null);					// clean the cache if the user interrupts
    // throw new UserCancelException(msg);
    // }
    // if(outputSpec.getBNGSpecies().length > SimulationConsolePanel.speciesLimit) {
    // String message = SimulationConsolePanel.getSpeciesLimitExceededMessage(outputSpec);
    // //			tcm = new TaskCallbackMessage(TaskCallbackStatus.Error, message);
    // //			simContext.appendToConsole(tcm);
    // //			simContext.setMd5hash(null);
    // throw new RuntimeException(message);
    // }
    // if(outputSpec.getBNGReactions().length > SimulationConsolePanel.reactionsLimit) {
    // String message = SimulationConsolePanel.getReactionsLimitExceededMessage(outputSpec);
    // //			tcm = new TaskCallbackMessage(TaskCallbackStatus.Error, message);
    // //			simContext.appendToConsole(tcm);
    // //			simContext.setMd5hash(null);
    // throw new RuntimeException(message);
    // }
    // TODO: uncomment here to parse the xml file!!!
    parseBngOutput(simContext, fromReactions, bngOutput);
// 
// Saving the observables, as produced by bionetgen
// in debug configurations add to command line   -Ddebug.user=danv
// 
// String debugUser = PropertyLoader.getProperty("debug.user", "not_defined");
// if (debugUser.equals("danv") || debugUser.equals("mblinov")){
// System.out.println("Saving their observables");
// parseObservablesBngOutput(simContext, bngOutput);
// }
// compareOutputs(simContext);
}
Also used : SpeciesContext(cbit.vcell.model.SpeciesContext) BNGExecutorService(cbit.vcell.server.bionetgen.BNGExecutorService) BNGOutput(cbit.vcell.server.bionetgen.BNGOutput) FakeSeedSpeciesInitialConditionsParameter(org.vcell.model.rbm.FakeSeedSpeciesInitialConditionsParameter) BNGOutputSpec(cbit.vcell.bionetgen.BNGOutputSpec) PropertyVetoException(java.beans.PropertyVetoException) ModelException(cbit.vcell.model.ModelException) IOException(java.io.IOException) ExpressionException(cbit.vcell.parser.ExpressionException) Expression(cbit.vcell.parser.Expression) NetworkGenerationRequirements(cbit.vcell.mapping.SimulationContext.NetworkGenerationRequirements) BNGInput(cbit.vcell.server.bionetgen.BNGInput) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) Pair(org.vcell.util.Pair)

Example 2 with BNGExecutorService

use of cbit.vcell.server.bionetgen.BNGExecutorService in project vcell by virtualcell.

the class BNGWindowManager method runBioNetGen.

/**
 * Gets the bngOutputPanel property (cbit.vcell.client.bionetgen.BNGOutputPanel) value.
 * @return The bngOutputPanel property value.
 */
public void runBioNetGen(BNGInput bngInput) {
    // Create a hash and put in the details required to run the ClientTaskDispatcher
    Hashtable<String, Object> hash = new Hashtable<String, Object>();
    hash.put(BNG_OUTPUT_PANEL, getBngOutputPanel());
    final BNGExecutorService bngService = BNGExecutorService.getInstance(bngInput, NetworkGenerationRequirements.NoTimeoutMS);
    // Create the AsynchClientTasks : in this case, running the BioNetGen (non-swing) and then displaying the output (swing) tasks.
    AsynchClientTask[] tasksArray = new AsynchClientTask[2];
    tasksArray[0] = new RunBioNetGen(bngService);
    tasksArray[1] = new DisplayBNGOutput();
    // Dispatch the tasks using the ClientTaskDispatcher.
    ClientTaskDispatcher.dispatch(getBngOutputPanel(), hash, tasksArray, false, true, new ProgressDialogListener() {

        public void cancelButton_actionPerformed(EventObject newEvent) {
            try {
                bngService.stopBNG();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}
Also used : AsynchClientTask(cbit.vcell.client.task.AsynchClientTask) ProgressDialogListener(org.vcell.util.ProgressDialogListener) Hashtable(java.util.Hashtable) DisplayBNGOutput(cbit.vcell.client.task.DisplayBNGOutput) EventObject(java.util.EventObject) BNGExecutorService(cbit.vcell.server.bionetgen.BNGExecutorService) RunBioNetGen(cbit.vcell.client.task.RunBioNetGen) EventObject(java.util.EventObject) IOException(java.io.IOException) UserCancelException(org.vcell.util.UserCancelException)

Example 3 with BNGExecutorService

use of cbit.vcell.server.bionetgen.BNGExecutorService in project vcell by virtualcell.

the class NetworkConstraintsPanel method runBioNetGen.

private void runBioNetGen() {
    EditConstraintsPanel panel = new EditConstraintsPanel(this);
    ChildWindowManager childWindowManager = ChildWindowManager.findChildWindowManager(this);
    ChildWindow childWindow = childWindowManager.addChildWindow(panel, panel, "Edit / Test Constraints");
    Dimension dim = new Dimension(360, 160);
    childWindow.pack();
    panel.setChildWindow(childWindow);
    childWindow.setPreferredSize(dim);
    childWindow.showModal();
    int maxIterations;
    int maxMolecules;
    if (panel.getButtonPushed() == ActionButtons.Run) {
        maxIterations = new Integer(panel.maxIterationTextField.getText());
        maxMolecules = new Integer(panel.maxMolTextField.getText());
        fieldSimulationContext.getNetworkConstraints().setTestConstraints(maxIterations, maxMolecules);
    } else if (panel.getButtonPushed() == ActionButtons.Apply) {
        activateConsole();
        maxIterations = new Integer(panel.maxIterationTextField.getText());
        maxMolecules = new Integer(panel.maxMolTextField.getText());
        fieldSimulationContext.getNetworkConstraints().setTestConstraints(maxIterations, maxMolecules);
        fieldSimulationContext.getNetworkConstraints().updateConstraintsFromTest();
        // apply will invalidate everything: generated species, reactions, console, cache, etc
        updateBioNetGenOutput(null);
        refreshInterface();
        TaskCallbackMessage tcm = new TaskCallbackMessage(TaskCallbackStatus.Clean, "");
        fieldSimulationContext.appendToConsole(tcm);
        String message = "Warning: The current Constraints are not tested / validated.";
        tcm = new TaskCallbackMessage(TaskCallbackStatus.Warning, message);
        fieldSimulationContext.appendToConsole(tcm);
        message = "The Network generation may take a very long time or the generated network may be incomplete. " + "We recommend testing this set of constraints.";
        tcm = new TaskCallbackMessage(TaskCallbackStatus.Notification, message);
        fieldSimulationContext.appendToConsole(tcm);
        return;
    } else {
        return;
    }
    // TODO: do not delete the commented code below
    // uncomment the next 6 lines to keep the data in the dialogs synchronized with the most recent reaction network
    // if(viewSpeciesDialog != null) {
    // viewSpeciesDialog.dispose();
    // }
    // if(viewReactionsDialog != null) {
    // viewReactionsDialog.dispose();
    // }
    activateConsole();
    // previousIterationSpecies = 0;
    synchronized (this) {
        fieldSimulationContext.setMd5hash(null);
        fieldSimulationContext.setMostRecentlyCreatedOutputSpec(null);
    }
    refreshInterface();
    if (!checkBnglRequirements()) {
        return;
    }
    NetworkTransformer transformer = new NetworkTransformer();
    MathMappingCallback dummyCallback = new MathMappingCallback() {

        public void setProgressFraction(float percentDone) {
        }

        public void setMessage(String message) {
        }

        public boolean isInterrupted() {
            return false;
        }
    };
    // we alter the input string to use the test values for max iterations and max molecules per species
    String input = transformer.convertToBngl(fieldSimulationContext, true, dummyCallback, NetworkGenerationRequirements.ComputeFullNoTimeout);
    // get rid of the default generate network command...
    input = input.substring(0, input.indexOf("generate_network({"));
    // ... and replace it with the "fake" one
    StringWriter bnglStringWriter = new StringWriter();
    PrintWriter pw = new PrintWriter(bnglStringWriter);
    RbmNetworkGenerator.generateNetworkEx(maxIterations, maxMolecules, pw, fieldSimulationContext.getModel().getRbmModelContainer(), fieldSimulationContext, NetworkGenerationRequirements.ComputeFullNoTimeout);
    String genNetStr = bnglStringWriter.toString();
    pw.close();
    input += genNetStr;
    BNGInput bngInput = new BNGInput(input);
    final BNGExecutorService bngService = BNGExecutorService.getInstance(bngInput, NetworkGenerationRequirements.NoTimeoutMS);
    bngService.registerBngUpdaterCallback(this);
    Hashtable<String, Object> hash = new Hashtable<String, Object>();
    AsynchClientTask[] tasksArray = new AsynchClientTask[3];
    TaskCallbackMessage message = new TaskCallbackMessage(TaskCallbackStatus.Clean, "");
    fieldSimulationContext.appendToConsole(message);
    tasksArray[0] = new RunBioNetGen(bngService);
    tasksArray[1] = new CreateBNGOutputSpec(bngService);
    tasksArray[2] = new ReturnBNGOutput(bngService, fieldSimulationContext, this);
    ClientTaskDispatcher.dispatch(this, hash, tasksArray, false, true, new ProgressDialogListener() {

        @Override
        public void cancelButton_actionPerformed(EventObject newEvent) {
            try {
                bngService.stopBNG();
                String s = "...user cancelled.";
                TaskCallbackMessage tcm = new TaskCallbackMessage(TaskCallbackStatus.TaskStopped, s);
                // message will be processed in TaskCallbackProcessor::case TaskStopped
                setNewCallbackMessage(tcm);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}
Also used : AsynchClientTask(cbit.vcell.client.task.AsynchClientTask) ReturnBNGOutput(cbit.vcell.client.task.ReturnBNGOutput) StringWriter(java.io.StringWriter) ProgressDialogListener(org.vcell.util.ProgressDialogListener) BNGInput(cbit.vcell.server.bionetgen.BNGInput) RunBioNetGen(cbit.vcell.client.task.RunBioNetGen) PrintWriter(java.io.PrintWriter) TaskCallbackMessage(cbit.vcell.mapping.TaskCallbackMessage) MathMappingCallback(cbit.vcell.mapping.SimulationContext.MathMappingCallback) CreateBNGOutputSpec(cbit.vcell.client.task.CreateBNGOutputSpec) Hashtable(java.util.Hashtable) NetworkTransformer(cbit.vcell.mapping.NetworkTransformer) ChildWindowManager(cbit.vcell.client.ChildWindowManager) Dimension(java.awt.Dimension) BNGExecutorService(cbit.vcell.server.bionetgen.BNGExecutorService) ChildWindow(cbit.vcell.client.ChildWindowManager.ChildWindow) EventObject(java.util.EventObject) EventObject(java.util.EventObject)

Example 4 with BNGExecutorService

use of cbit.vcell.server.bionetgen.BNGExecutorService in project vcell by virtualcell.

the class NetworkTransformer method generateNetwork.

private BNGOutputSpec generateNetwork(SimulationContext simContext, MathMappingCallback mathMappingCallback, NetworkGenerationRequirements networkGenerationRequirements) throws ClassNotFoundException, IOException {
    TaskCallbackMessage tcm;
    BNGOutputSpec outputSpec;
    speciesEquivalenceMap.clear();
    kineticsParameterMap.clear();
    String input = convertToBngl(simContext, true, mathMappingCallback, networkGenerationRequirements);
    for (Map.Entry<FakeSeedSpeciesInitialConditionsParameter, Pair<SpeciesContext, Expression>> entry : speciesEquivalenceMap.entrySet()) {
        FakeSeedSpeciesInitialConditionsParameter key = entry.getKey();
        Pair<SpeciesContext, Expression> value = entry.getValue();
        SpeciesContext sc = value.one;
        Expression initial = value.two;
        System.out.println("key: " + key.fakeParameterName + ",   species: " + sc.getName() + ", initial: " + initial.infix());
    }
    String md5hash = MD5.md5(input);
    if (isBngHashValid(input, md5hash, simContext)) {
        String s = "Previously saved outputSpec is up-to-date, no need to generate network.";
        System.out.println(s);
        // not an error, we just want to show it in red
        tcm = new TaskCallbackMessage(TaskCallbackStatus.Error, s);
        simContext.appendToConsole(tcm);
        if (simContext.isInsufficientIterations()) {
            s = NetworkTransformer.getInsufficientIterationsMessage();
            System.out.println(s);
            tcm = new TaskCallbackMessage(TaskCallbackStatus.Error, s);
            simContext.appendToConsole(tcm);
        }
        if (simContext.isInsufficientMaxMolecules()) {
            s = NetworkTransformer.getInsufficientMaxMoleculesMessage();
            System.out.println(s);
            tcm = new TaskCallbackMessage(TaskCallbackStatus.Error, s);
            simContext.appendToConsole(tcm);
        }
        outputSpec = simContext.getMostRecentlyCreatedOutputSpec();
        return (BNGOutputSpec) BeanUtils.cloneSerializable(outputSpec);
    }
    BNGInput bngInput = new BNGInput(input);
    BNGOutput bngOutput = null;
    try {
        final BNGExecutorService bngService = BNGExecutorService.getInstance(bngInput, networkGenerationRequirements.timeoutDurationMS);
        bngService.registerBngUpdaterCallback(simContext);
        bngOutput = bngService.executeBNG();
    } catch (BNGException ex) {
        ex.printStackTrace(System.out);
        System.out.println("bionetgen exception");
        if (ex.getMessage().contains("was asked to write the network, but no reactions were found")) {
            RuntimeException rex = new RuntimeException("Specified species and reaction rules are not sufficient to define reaction network.");
            throw rex;
        } else {
            // rethrow without losing context
            throw ex;
        }
    } catch (RuntimeException ex) {
        ex.printStackTrace(System.out);
        System.out.println("runtime exception");
        throw ex;
    } catch (Exception ex) {
        ex.printStackTrace(System.out);
        System.out.println("other exception");
        throw new RuntimeException(ex.getMessage());
    }
    // simContext.setInsufficientIterations(false);
    // simContext.setInsufficientMaxMolecules(false);
    String bngConsoleString = bngOutput.getConsoleOutput();
    // TODO: this message we check if insufficient iterations / max molecules
    // DO IT OUTSIDE (in the bng service), we now can
    // tcm = new TaskCallbackMessage(TaskCallbackStatus.DetailBatch, bngConsoleString);
    // simContext.appendToConsole(tcm);
    tcm = new TaskCallbackMessage(TaskCallbackStatus.TaskEndNotificationOnly, "");
    simContext.setNewCallbackMessage(tcm);
    tcm = new TaskCallbackMessage(TaskCallbackStatus.TaskEndAdjustSimulationContextFlagsOnly, "");
    simContext.setNewCallbackMessage(tcm);
    String bngNetString = bngOutput.getNetFileContent();
    outputSpec = BNGOutputFileParser.createBngOutputSpec(bngNetString);
    // prints all output to console
    BNGOutputFileParser.printBNGNetOutput(outputSpec);
    if (mathMappingCallback.isInterrupted()) {
        String msg = "Canceled by user.";
        tcm = new TaskCallbackMessage(TaskCallbackStatus.Error, msg);
        simContext.appendToConsole(tcm);
        // clean the cache if the user interrupts
        simContext.setMd5hash(null);
        throw new UserCancelException(msg);
    }
    if (outputSpec.getBNGSpecies().length > NetworkTransformer.speciesLimit) {
        String message = NetworkTransformer.getSpeciesLimitExceededMessage(outputSpec);
        tcm = new TaskCallbackMessage(TaskCallbackStatus.Error, message);
        simContext.appendToConsole(tcm);
        simContext.setMd5hash(null);
        message = "Unable to generate Math for Application " + simContext.getName() + ".\n" + message;
        throw new RuntimeException(message);
    }
    if (outputSpec.getBNGReactions().length > NetworkTransformer.reactionsLimit) {
        String message = NetworkTransformer.getReactionsLimitExceededMessage(outputSpec);
        tcm = new TaskCallbackMessage(TaskCallbackStatus.Error, message);
        simContext.appendToConsole(tcm);
        simContext.setMd5hash(null);
        message = "Unable to generate Math for Application " + simContext.getName() + ".\n" + message;
        throw new RuntimeException(message);
    }
    // System.out.println("old hash: " + simContext.getMd5hash());
    if (md5hash != null && md5hash.length() != 0 && outputSpec != null) {
        System.out.println("saving hash and output spec");
        synchronized (this) {
            simContext.setMd5hash(md5hash);
            simContext.setMostRecentlyCreatedOutputSpec(outputSpec);
        }
    } else {
        System.out.println("something is wrong with the hash and/or output spec");
    }
    return (BNGOutputSpec) BeanUtils.cloneSerializable(outputSpec);
}
Also used : UserCancelException(org.vcell.util.UserCancelException) SpeciesContext(cbit.vcell.model.SpeciesContext) BNGExecutorService(cbit.vcell.server.bionetgen.BNGExecutorService) BNGOutput(cbit.vcell.server.bionetgen.BNGOutput) FakeSeedSpeciesInitialConditionsParameter(org.vcell.model.rbm.FakeSeedSpeciesInitialConditionsParameter) BNGOutputSpec(cbit.vcell.bionetgen.BNGOutputSpec) PropertyVetoException(java.beans.PropertyVetoException) ExpressionBindingException(cbit.vcell.parser.ExpressionBindingException) ParseException(org.vcell.model.bngl.ParseException) BNGException(cbit.vcell.server.bionetgen.BNGException) ModelException(cbit.vcell.model.ModelException) IOException(java.io.IOException) ExpressionException(cbit.vcell.parser.ExpressionException) UserCancelException(org.vcell.util.UserCancelException) BNGException(cbit.vcell.server.bionetgen.BNGException) Expression(cbit.vcell.parser.Expression) BNGInput(cbit.vcell.server.bionetgen.BNGInput) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Pair(org.vcell.util.Pair)

Aggregations

BNGExecutorService (cbit.vcell.server.bionetgen.BNGExecutorService)4 BNGInput (cbit.vcell.server.bionetgen.BNGInput)3 IOException (java.io.IOException)3 BNGOutputSpec (cbit.vcell.bionetgen.BNGOutputSpec)2 AsynchClientTask (cbit.vcell.client.task.AsynchClientTask)2 RunBioNetGen (cbit.vcell.client.task.RunBioNetGen)2 ModelException (cbit.vcell.model.ModelException)2 SpeciesContext (cbit.vcell.model.SpeciesContext)2 Expression (cbit.vcell.parser.Expression)2 ExpressionException (cbit.vcell.parser.ExpressionException)2 BNGOutput (cbit.vcell.server.bionetgen.BNGOutput)2 PropertyVetoException (java.beans.PropertyVetoException)2 EventObject (java.util.EventObject)2 Hashtable (java.util.Hashtable)2 LinkedHashMap (java.util.LinkedHashMap)2 Map (java.util.Map)2 FakeSeedSpeciesInitialConditionsParameter (org.vcell.model.rbm.FakeSeedSpeciesInitialConditionsParameter)2 Pair (org.vcell.util.Pair)2 ProgressDialogListener (org.vcell.util.ProgressDialogListener)2 UserCancelException (org.vcell.util.UserCancelException)2