Search in sources :

Example 1 with ParseException

use of org.vcell.model.bngl.ParseException in project vcell by virtualcell.

the class NetworkTransformer method transform.

private void transform(SimulationContext simContext, SimulationContext transformedSimulationContext, ArrayList<ModelEntityMapping> entityMappings, MathMappingCallback mathMappingCallback, NetworkGenerationRequirements networkGenerationRequirements) {
    String msg = "Generating network: flattening...";
    mathMappingCallback.setMessage(msg);
    TaskCallbackMessage tcm = new TaskCallbackMessage(TaskCallbackStatus.Clean, "");
    simContext.appendToConsole(tcm);
    tcm = new TaskCallbackMessage(TaskCallbackStatus.TaskStart, msg);
    simContext.appendToConsole(tcm);
    long startTime = System.currentTimeMillis();
    System.out.println("Convert to bngl, execute BNG, retrieve the results.");
    try {
        BNGOutputSpec outputSpec = generateNetwork(simContext, mathMappingCallback, networkGenerationRequirements);
        if (mathMappingCallback.isInterrupted()) {
            msg = "Canceled by user.";
            tcm = new TaskCallbackMessage(TaskCallbackStatus.Error, msg);
            simContext.appendToConsole(tcm);
            throw new UserCancelException(msg);
        }
        long endTime = System.currentTimeMillis();
        long elapsedTime = endTime - startTime;
        System.out.println("     " + elapsedTime + " milliseconds");
        Model model = transformedSimulationContext.getModel();
        ReactionContext reactionContext = transformedSimulationContext.getReactionContext();
        // ---- Parameters -----------------------------------------------------------------------------------------------
        startTime = System.currentTimeMillis();
        for (int i = 0; i < outputSpec.getBNGParams().length; i++) {
            BNGParameter p = outputSpec.getBNGParams()[i];
            // System.out.println(i+1 + ":\t\t"+ p.toString());
            if (model.getRbmModelContainer().getParameter(p.getName()) != null) {
                // if it's already there we don't try to add it again; this should be true for all of them!
                continue;
            }
            String s = p.getName();
            if (NetworkConstraints.SPECIES_LIMIT_PARAMETER.equals(s)) {
                System.out.println("found NetworkConstraints seciesLimit parameter.");
                continue;
            }
            if (NetworkConstraints.REACTIONS_LIMIT_PARAMETER.equals(s)) {
                System.out.println("found NetworkConstraints reactionsLimit parameter.");
                continue;
            }
            FakeSeedSpeciesInitialConditionsParameter fakeICParam = FakeSeedSpeciesInitialConditionsParameter.fromString(s);
            if (speciesEquivalenceMap.containsKey(fakeICParam)) {
                // we get rid of the fake parameters we use as keys
                continue;
            }
            FakeReactionRuleRateParameter fakeKineticParam = FakeReactionRuleRateParameter.fromString(s);
            if (fakeKineticParam != null) {
                System.out.println("found fakeKineticParam " + fakeKineticParam.fakeParameterName);
                // we get rid of the fake parameters we use as keys
                continue;
            }
            throw new RuntimeException("unexpected parameter " + p.getName() + " in internal BNG processing");
        // Expression exp = new Expression(p.getValue());
        // exp.bindExpression(model.getRbmModelContainer().getSymbolTable());
        // model.getRbmModelContainer().addParameter(p.getName(), exp, model.getUnitSystem().getInstance_TBD());
        }
        endTime = System.currentTimeMillis();
        elapsedTime = endTime - startTime;
        msg = "Adding " + outputSpec.getBNGParams().length + " parameters to model, " + elapsedTime + " ms";
        System.out.println(msg);
        // ---- Species ------------------------------------------------------------------------------------------------------------
        mathMappingCallback.setMessage("generating network: adding species...");
        mathMappingCallback.setProgressFraction(progressFractionQuota / 4.0f);
        startTime = System.currentTimeMillis();
        System.out.println("\nSpecies :");
        // the reactions will need this map to recover the names of species knowing only the networkFileIndex
        HashMap<Integer, String> speciesMap = new HashMap<Integer, String>();
        LinkedHashMap<String, Species> sMap = new LinkedHashMap<String, Species>();
        LinkedHashMap<String, SpeciesContext> scMap = new LinkedHashMap<String, SpeciesContext>();
        LinkedHashMap<String, BNGSpecies> crossMap = new LinkedHashMap<String, BNGSpecies>();
        List<SpeciesContext> noMapForThese = new ArrayList<SpeciesContext>();
        // final int decimalTickCount = Math.max(outputSpec.getBNGSpecies().length/10, 1);
        for (int i = 0; i < outputSpec.getBNGSpecies().length; i++) {
            BNGSpecies s = outputSpec.getBNGSpecies()[i];
            // System.out.println(i+1 + ":\t\t"+ s.toString());
            String key = s.getConcentration().infix();
            FakeSeedSpeciesInitialConditionsParameter fakeParam = FakeSeedSpeciesInitialConditionsParameter.fromString(key);
            if (fakeParam != null) {
                Pair<SpeciesContext, Expression> value = speciesEquivalenceMap.get(fakeParam);
                // the species context of the original model
                SpeciesContext originalsc = value.one;
                Expression initial = value.two;
                // replace the fake initial condition with the real one
                s.setConcentration(initial);
                // we'll have to find the species context from the cloned model which correspond to the original species
                SpeciesContext sc = model.getSpeciesContext(originalsc.getName());
                // System.out.println(sc.getName() + ", " + sc.getSpecies().getCommonName() + "   ...is one of the original seed species.");
                // existing name
                speciesMap.put(s.getNetworkFileIndex(), sc.getName());
                sMap.put(sc.getName(), sc.getSpecies());
                scMap.put(sc.getName(), sc);
                crossMap.put(sc.getName(), s);
                noMapForThese.add(sc);
                continue;
            }
            // all these species are new!
            // generate unique name for the species
            int count = 0;
            String speciesName = null;
            String nameRoot = "s";
            String speciesPatternNameString = s.extractName();
            while (true) {
                speciesName = nameRoot + count;
                if (Model.isNameUnused(speciesName, model) && !sMap.containsKey(speciesName) && !scMap.containsKey(speciesName)) {
                    break;
                }
                count++;
            }
            // newly created name
            speciesMap.put(s.getNetworkFileIndex(), speciesName);
            SpeciesContext speciesContext;
            if (s.hasCompartment()) {
                String speciesPatternCompartmentString = s.extractCompartment();
                speciesContext = new SpeciesContext(new Species(speciesName, s.getName()), model.getStructure(speciesPatternCompartmentString), null);
            } else {
                speciesContext = new SpeciesContext(new Species(speciesName, s.getName()), model.getStructure(0), null);
            }
            speciesContext.setName(speciesName);
            try {
                if (speciesPatternNameString != null) {
                    SpeciesPattern sp = RbmUtils.parseSpeciesPattern(speciesPatternNameString, model);
                    speciesContext.setSpeciesPattern(sp);
                }
            } catch (ParseException e) {
                e.printStackTrace();
                throw new RuntimeException("Bad format for species pattern string: " + e.getMessage());
            }
            // speciesContext.setSpeciesPatternString(speciesPatternString);
            // model.addSpecies(speciesContext.getSpecies());
            // model.addSpeciesContext(speciesContext);
            sMap.put(speciesName, speciesContext.getSpecies());
            scMap.put(speciesName, speciesContext);
            crossMap.put(speciesName, s);
            // }
            if (mathMappingCallback.isInterrupted()) {
                msg = "Canceled by user.";
                tcm = new TaskCallbackMessage(TaskCallbackStatus.Error, msg);
                simContext.appendToConsole(tcm);
                throw new UserCancelException(msg);
            }
        // if(i%50 == 0) {
        // System.out.println(i+"");
        // }
        // if(i%decimalTickCount == 0) {
        // int multiplier = i/decimalTickCount;
        // float progress = progressFractionQuota/4.0f + progressFractionQuotaSpecies*multiplier;
        // mathMappingCallback.setProgressFraction(progress);
        // }
        }
        for (SpeciesContext sc1 : model.getSpeciesContexts()) {
            boolean found = false;
            for (Map.Entry<String, SpeciesContext> entry : scMap.entrySet()) {
                SpeciesContext sc2 = entry.getValue();
                if (sc1.getName().equals(sc2.getName())) {
                    found = true;
                    // System.out.println("found species context " + sc1.getName() + " of species " + sc1.getSpecies().getCommonName() + " // " + sc2.getSpecies().getCommonName());
                    break;
                }
            }
            if (found == false) {
                // we add to the map the species context and the species which exist in the model but which are not in the map yet
                // the only ones in this situation should be plain species which were not given to bngl for flattening (they are flat already)
                // System.out.println("species context " + sc1.getName() + " not found in the map. Adding it.");
                scMap.put(sc1.getName(), sc1);
                sMap.put(sc1.getName(), sc1.getSpecies());
                noMapForThese.add(sc1);
            }
        }
        for (Species s1 : model.getSpecies()) {
            boolean found = false;
            for (Map.Entry<String, Species> entry : sMap.entrySet()) {
                Species s2 = entry.getValue();
                if (s1.getCommonName().equals(s2.getCommonName())) {
                    found = true;
                    // System.out.println("found species " + s1.getCommonName());
                    break;
                }
            }
            if (found == false) {
                System.err.println("species " + s1.getCommonName() + " not found in the map!");
            }
        }
        SpeciesContext[] sca = new SpeciesContext[scMap.size()];
        scMap.values().toArray(sca);
        Species[] sa = new HashSet<Species>(sMap.values()).toArray(new Species[0]);
        model.setSpecies(sa);
        model.setSpeciesContexts(sca);
        boolean isSpatial = transformedSimulationContext.getGeometry().getDimension() > 0;
        for (SpeciesContext sc : sca) {
            if (noMapForThese.contains(sc)) {
                continue;
            }
            SpeciesContextSpec scs = reactionContext.getSpeciesContextSpec(sc);
            Parameter param = scs.getParameter(SpeciesContextSpec.ROLE_InitialConcentration);
            BNGSpecies s = crossMap.get(sc.getName());
            param.setExpression(s.getConcentration());
            SpeciesContext origSpeciesContext = simContext.getModel().getSpeciesContext(s.getName());
            if (origSpeciesContext != null) {
                ModelEntityMapping em = new ModelEntityMapping(origSpeciesContext, sc);
                entityMappings.add(em);
            } else {
                ModelEntityMapping em = new ModelEntityMapping(new GeneratedSpeciesSymbolTableEntry(sc), sc);
                if (isSpatial) {
                    scs.initializeForSpatial();
                }
                entityMappings.add(em);
            }
        }
        // for(SpeciesContext sc : sca) {		// clean all the species patterns from the flattened species, we have no sp now
        // sc.setSpeciesPattern(null);
        // }
        endTime = System.currentTimeMillis();
        elapsedTime = endTime - startTime;
        msg = "Adding " + outputSpec.getBNGSpecies().length + " species to model, " + elapsedTime + " ms";
        System.out.println(msg);
        // ---- Reactions -----------------------------------------------------------------------------------------------------
        mathMappingCallback.setMessage("generating network: adding reactions...");
        mathMappingCallback.setProgressFraction(progressFractionQuota / 4.0f * 3.0f);
        startTime = System.currentTimeMillis();
        System.out.println("\nReactions :");
        Map<String, HashSet<String>> ruleKeyMap = new HashMap<String, HashSet<String>>();
        Map<String, BNGReaction> directBNGReactionsMap = new HashMap<String, BNGReaction>();
        Map<String, BNGReaction> reverseBNGReactionsMap = new HashMap<String, BNGReaction>();
        for (int i = 0; i < outputSpec.getBNGReactions().length; i++) {
            BNGReaction r = outputSpec.getBNGReactions()[i];
            if (!r.isRuleReversed()) {
                // direct
                directBNGReactionsMap.put(r.getKey(), r);
            } else {
                reverseBNGReactionsMap.put(r.getKey(), r);
            }
            // 
            // for each rule name, store set of keySets (number of unique keysets are number of generated reactions from this ruleName).
            // 
            HashSet<String> keySet = ruleKeyMap.get(r.getRuleName());
            if (keySet == null) {
                keySet = new HashSet<String>();
                ruleKeyMap.put(r.getRuleName(), keySet);
            }
            keySet.add(r.getKey());
        }
        Map<String, ReactionStep> reactionStepMap = new HashMap<String, ReactionStep>();
        for (int i = 0; i < outputSpec.getBNGReactions().length; i++) {
            BNGReaction bngReaction = outputSpec.getBNGReactions()[i];
            // System.out.println(i+1 + ":\t\t"+ r.writeReaction());
            String baseName = bngReaction.getRuleName();
            // which may never happen since we encountered this problem only one time in many years
            if (baseName.contains(",") && (baseName.length() > 192)) {
                int pos = baseName.indexOf(",");
                baseName = baseName.substring(0, pos);
            }
            // System.out.println(i + ": " + baseName);
            String reactionName = null;
            HashSet<String> keySetsForThisRule = ruleKeyMap.get(bngReaction.getRuleName());
            if (keySetsForThisRule.size() == 1 && model.getReactionStep(bngReaction.getRuleName()) == null && !reactionStepMap.containsKey(bngReaction.getRuleName())) {
                // we can reuse the reaction rule labels
                reactionName = baseName;
            } else {
                reactionName = baseName + "_0";
                while (true) {
                    if (model.getReactionStep(reactionName) == null && !reactionStepMap.containsKey(reactionName)) {
                        // we can reuse the reaction rule labels
                        break;
                    }
                    reactionName = TokenMangler.getNextEnumeratedToken(reactionName);
                }
            }
            // 
            if (directBNGReactionsMap.containsValue(bngReaction)) {
                BNGReaction forwardBNGReaction = bngReaction;
                BNGReaction reverseBNGReaction = reverseBNGReactionsMap.get(bngReaction.getKey());
                String name = forwardBNGReaction.getRuleName();
                if (name.endsWith(ReactionRule.DirectHalf)) {
                    name = name.substring(0, name.indexOf(ReactionRule.DirectHalf));
                }
                if (name.endsWith(ReactionRule.InverseHalf)) {
                    name = name.substring(0, name.indexOf(ReactionRule.InverseHalf));
                }
                ReactionRule rr = model.getRbmModelContainer().getReactionRule(name);
                Structure structure = rr.getStructure();
                boolean bReversible = reverseBNGReaction != null;
                SimpleReaction sr = new SimpleReaction(model, structure, reactionName, bReversible);
                for (int j = 0; j < forwardBNGReaction.getReactants().length; j++) {
                    BNGSpecies s = forwardBNGReaction.getReactants()[j];
                    String scName = speciesMap.get(s.getNetworkFileIndex());
                    SpeciesContext sc = model.getSpeciesContext(scName);
                    Reactant reactant = sr.getReactant(scName);
                    if (reactant == null) {
                        int stoichiometry = 1;
                        sr.addReactant(sc, stoichiometry);
                    } else {
                        int stoichiometry = reactant.getStoichiometry();
                        stoichiometry += 1;
                        reactant.setStoichiometry(stoichiometry);
                    }
                }
                for (int j = 0; j < forwardBNGReaction.getProducts().length; j++) {
                    BNGSpecies s = forwardBNGReaction.getProducts()[j];
                    String scName = speciesMap.get(s.getNetworkFileIndex());
                    SpeciesContext sc = model.getSpeciesContext(scName);
                    Product product = sr.getProduct(scName);
                    if (product == null) {
                        int stoichiometry = 1;
                        sr.addProduct(sc, stoichiometry);
                    } else {
                        int stoichiometry = product.getStoichiometry();
                        stoichiometry += 1;
                        product.setStoichiometry(stoichiometry);
                    }
                }
                if (!bngReaction.isMichaelisMenten()) {
                    // MassAction
                    MassActionKinetics targetKinetics = new MassActionKinetics(sr);
                    sr.setKinetics(targetKinetics);
                    KineticsParameter kforward = targetKinetics.getForwardRateParameter();
                    KineticsParameter kreverse = targetKinetics.getReverseRateParameter();
                    String kforwardNewName = rr.getKineticLaw().getLocalParameter(RbmKineticLawParameterType.MassActionForwardRate).getName();
                    if (!kforward.getName().equals(kforwardNewName)) {
                        targetKinetics.renameParameter(kforward.getName(), kforwardNewName);
                        kforward = targetKinetics.getForwardRateParameter();
                    }
                    final String kreverseNewName = rr.getKineticLaw().getLocalParameter(RbmKineticLawParameterType.MassActionReverseRate).getName();
                    if (!kreverse.getName().equals(kreverseNewName)) {
                        targetKinetics.renameParameter(kreverse.getName(), kreverseNewName);
                        kreverse = targetKinetics.getReverseRateParameter();
                    }
                    applyKineticsExpressions(forwardBNGReaction, kforward, targetKinetics);
                    if (reverseBNGReaction != null) {
                        applyKineticsExpressions(reverseBNGReaction, kreverse, targetKinetics);
                    }
                } else {
                    // MichaelisMenten
                    HMM_IRRKinetics targetKinetics = new HMM_IRRKinetics(sr);
                    sr.setKinetics(targetKinetics);
                    KineticsParameter vmax = targetKinetics.getVmaxParameter();
                    KineticsParameter km = targetKinetics.getKmParameter();
                    String vmaxNewName = rr.getKineticLaw().getLocalParameter(RbmKineticLawParameterType.MichaelisMentenVmax).getName();
                    if (!vmax.getName().equals(vmaxNewName)) {
                        targetKinetics.renameParameter(vmax.getName(), vmaxNewName);
                        vmax = targetKinetics.getVmaxParameter();
                    }
                    applyKineticsExpressions(forwardBNGReaction, vmax, targetKinetics);
                    final String kmNewName = rr.getKineticLaw().getLocalParameter(RbmKineticLawParameterType.MichaelisMentenKm).getName();
                    if (!km.getName().equals(kmNewName)) {
                        targetKinetics.renameParameter(km.getName(), kmNewName);
                        km = targetKinetics.getKmParameter();
                    }
                    applyKineticsExpressions(forwardBNGReaction, km, targetKinetics);
                }
                reactionStepMap.put(reactionName, sr);
            } else if (reverseBNGReactionsMap.containsValue(bngReaction) && !directBNGReactionsMap.containsKey(bngReaction.getKey())) {
                // reverse only (must be irreversible, cannot be Michaelis-Menten)
                BNGReaction reverseBNGReaction = reverseBNGReactionsMap.get(bngReaction.getKey());
                ReactionRule rr = model.getRbmModelContainer().getReactionRule(reverseBNGReaction.extractRuleName());
                Structure structure = rr.getStructure();
                boolean bReversible = false;
                SimpleReaction sr = new SimpleReaction(model, structure, reactionName, bReversible);
                for (int j = 0; j < reverseBNGReaction.getReactants().length; j++) {
                    BNGSpecies s = reverseBNGReaction.getReactants()[j];
                    String scName = speciesMap.get(s.getNetworkFileIndex());
                    SpeciesContext sc = model.getSpeciesContext(scName);
                    Reactant reactant = sr.getReactant(scName);
                    if (reactant == null) {
                        int stoichiometry = 1;
                        sr.addReactant(sc, stoichiometry);
                    } else {
                        int stoichiometry = reactant.getStoichiometry();
                        stoichiometry += 1;
                        reactant.setStoichiometry(stoichiometry);
                    }
                }
                for (int j = 0; j < reverseBNGReaction.getProducts().length; j++) {
                    BNGSpecies s = reverseBNGReaction.getProducts()[j];
                    String scName = speciesMap.get(s.getNetworkFileIndex());
                    SpeciesContext sc = model.getSpeciesContext(scName);
                    Product product = sr.getProduct(scName);
                    if (product == null) {
                        int stoichiometry = 1;
                        sr.addProduct(sc, stoichiometry);
                    } else {
                        int stoichiometry = product.getStoichiometry();
                        stoichiometry += 1;
                        product.setStoichiometry(stoichiometry);
                    }
                }
                MassActionKinetics k = new MassActionKinetics(sr);
                sr.setKinetics(k);
                KineticsParameter kforward = k.getForwardRateParameter();
                KineticsParameter kreverse = k.getReverseRateParameter();
                String kforwardNewName = rr.getKineticLaw().getLocalParameter(RbmKineticLawParameterType.MassActionForwardRate).getName();
                if (!kforward.getName().equals(kforwardNewName)) {
                    k.renameParameter(kforward.getName(), kforwardNewName);
                    kforward = k.getForwardRateParameter();
                }
                final String kreverseNewName = rr.getKineticLaw().getLocalParameter(RbmKineticLawParameterType.MassActionReverseRate).getName();
                if (!kreverse.getName().equals(kreverseNewName)) {
                    k.renameParameter(kreverse.getName(), kreverseNewName);
                    kreverse = k.getReverseRateParameter();
                }
                applyKineticsExpressions(reverseBNGReaction, kforward, k);
                // String fieldParameterName = kforward.getName();
                // fieldParameterName += "_" + r.getRuleName();
                // kforward.setName(fieldParameterName);
                reactionStepMap.put(reactionName, sr);
            }
        }
        for (ReactionStep rs : model.getReactionSteps()) {
            reactionStepMap.put(rs.getName(), rs);
        }
        ReactionStep[] reactionSteps = new ReactionStep[reactionStepMap.size()];
        reactionStepMap.values().toArray(reactionSteps);
        model.setReactionSteps(reactionSteps);
        if (mathMappingCallback.isInterrupted()) {
            msg = "Canceled by user.";
            tcm = new TaskCallbackMessage(TaskCallbackStatus.Error, msg);
            simContext.appendToConsole(tcm);
            throw new UserCancelException(msg);
        }
        endTime = System.currentTimeMillis();
        elapsedTime = endTime - startTime;
        msg = "Adding " + outputSpec.getBNGReactions().length + " reactions to model, " + elapsedTime + " ms";
        System.out.println(msg);
        // clean all the reaction rules
        model.getRbmModelContainer().getReactionRuleList().clear();
        // ---- Observables -------------------------------------------------------------------------------------------------
        mathMappingCallback.setMessage("generating network: adding observables...");
        mathMappingCallback.setProgressFraction(progressFractionQuota / 8.0f * 7.0f);
        startTime = System.currentTimeMillis();
        System.out.println("\nObservables :");
        RbmModelContainer rbmmc = model.getRbmModelContainer();
        for (int i = 0; i < outputSpec.getObservableGroups().length; i++) {
            ObservableGroup o = outputSpec.getObservableGroups()[i];
            if (rbmmc.getParameter(o.getObservableGroupName()) != null) {
                System.out.println("   ...already exists.");
                // if it's already there we don't try to add it again; this should be true for all of them!
                continue;
            }
            ArrayList<Expression> terms = new ArrayList<Expression>();
            for (int j = 0; j < o.getListofSpecies().length; j++) {
                Expression term = Expression.mult(new Expression(o.getSpeciesMultiplicity()[j]), new Expression(speciesMap.get(o.getListofSpecies()[j].getNetworkFileIndex())));
                terms.add(term);
            }
            Expression exp = Expression.add(terms.toArray(new Expression[terms.size()])).flatten();
            exp.bindExpression(rbmmc.getSymbolTable());
            RbmObservable originalObservable = rbmmc.getObservable(o.getObservableGroupName());
            VCUnitDefinition observableUnitDefinition = originalObservable.getUnitDefinition();
            rbmmc.removeObservable(originalObservable);
            Parameter newParameter = rbmmc.addParameter(o.getObservableGroupName(), exp, observableUnitDefinition);
            RbmObservable origObservable = simContext.getModel().getRbmModelContainer().getObservable(o.getObservableGroupName());
            ModelEntityMapping em = new ModelEntityMapping(origObservable, newParameter);
            entityMappings.add(em);
        }
        if (mathMappingCallback.isInterrupted()) {
            msg = "Canceled by user.";
            tcm = new TaskCallbackMessage(TaskCallbackStatus.Error, msg);
            simContext.appendToConsole(tcm);
            throw new UserCancelException(msg);
        }
        endTime = System.currentTimeMillis();
        elapsedTime = endTime - startTime;
        msg = "Adding " + outputSpec.getObservableGroups().length + " observables to model, " + elapsedTime + " ms";
        System.out.println(msg);
    } catch (PropertyVetoException ex) {
        ex.printStackTrace(System.out);
        throw new RuntimeException(ex.getMessage());
    } catch (ExpressionBindingException ex) {
        ex.printStackTrace(System.out);
        throw new RuntimeException(ex.getMessage());
    } catch (ModelException ex) {
        ex.printStackTrace(System.out);
        throw new RuntimeException(ex.getMessage());
    } catch (ExpressionException ex) {
        ex.printStackTrace(System.out);
        throw new RuntimeException(ex.getMessage());
    } catch (ClassNotFoundException ex) {
        throw new RuntimeException(ex.getMessage());
    } catch (IOException ex) {
        throw new RuntimeException(ex.getMessage());
    }
    System.out.println("Done transforming");
    msg = "Generating math...";
    System.out.println(msg);
    mathMappingCallback.setMessage(msg);
    mathMappingCallback.setProgressFraction(progressFractionQuota);
}
Also used : HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) HMM_IRRKinetics(cbit.vcell.model.HMM_IRRKinetics) UserCancelException(org.vcell.util.UserCancelException) ArrayList(java.util.ArrayList) Product(cbit.vcell.model.Product) SpeciesContext(cbit.vcell.model.SpeciesContext) FakeSeedSpeciesInitialConditionsParameter(org.vcell.model.rbm.FakeSeedSpeciesInitialConditionsParameter) Reactant(cbit.vcell.model.Reactant) BNGOutputSpec(cbit.vcell.bionetgen.BNGOutputSpec) ExpressionException(cbit.vcell.parser.ExpressionException) LinkedHashMap(java.util.LinkedHashMap) FakeReactionRuleRateParameter(org.vcell.model.rbm.FakeReactionRuleRateParameter) KineticsParameter(cbit.vcell.model.Kinetics.KineticsParameter) RbmModelContainer(cbit.vcell.model.Model.RbmModelContainer) Species(cbit.vcell.model.Species) BNGSpecies(cbit.vcell.bionetgen.BNGSpecies) HashSet(java.util.HashSet) BNGParameter(cbit.vcell.bionetgen.BNGParameter) ModelException(cbit.vcell.model.ModelException) ObservableGroup(cbit.vcell.bionetgen.ObservableGroup) RbmObservable(cbit.vcell.model.RbmObservable) PropertyVetoException(java.beans.PropertyVetoException) BNGReaction(cbit.vcell.bionetgen.BNGReaction) VCUnitDefinition(cbit.vcell.units.VCUnitDefinition) ReactionStep(cbit.vcell.model.ReactionStep) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) SpeciesPattern(org.vcell.model.rbm.SpeciesPattern) Structure(cbit.vcell.model.Structure) SimpleReaction(cbit.vcell.model.SimpleReaction) ReactionRule(cbit.vcell.model.ReactionRule) IOException(java.io.IOException) ExpressionBindingException(cbit.vcell.parser.ExpressionBindingException) Expression(cbit.vcell.parser.Expression) Model(cbit.vcell.model.Model) FakeSeedSpeciesInitialConditionsParameter(org.vcell.model.rbm.FakeSeedSpeciesInitialConditionsParameter) Parameter(cbit.vcell.model.Parameter) KineticsParameter(cbit.vcell.model.Kinetics.KineticsParameter) LocalParameter(cbit.vcell.mapping.ParameterContext.LocalParameter) BNGParameter(cbit.vcell.bionetgen.BNGParameter) FakeReactionRuleRateParameter(org.vcell.model.rbm.FakeReactionRuleRateParameter) MassActionKinetics(cbit.vcell.model.MassActionKinetics) ParseException(org.vcell.model.bngl.ParseException) BNGSpecies(cbit.vcell.bionetgen.BNGSpecies)

Example 2 with ParseException

use of org.vcell.model.bngl.ParseException in project vcell by virtualcell.

the class RbmUtils method parseMolecularType.

public static MolecularType parseMolecularType(String inputString) throws ParseException {
    try {
        BNGLParser parser = new BNGLParser(new StringReader(inputString));
        ASTMolecularTypePattern astMolecularPattern = parser.MolecularTypePattern();
        BnglObjectConstructionVisitor constructionVisitor = new BnglObjectConstructionVisitor();
        MolecularType molecularType = (MolecularType) astMolecularPattern.jjtAccept(constructionVisitor, null);
        return molecularType;
    } catch (Throwable ex) {
        ex.printStackTrace();
        throw new ParseException(ex.getMessage());
    }
}
Also used : ParticleMolecularType(cbit.vcell.math.ParticleMolecularType) BNGLParser(org.vcell.model.bngl.BNGLParser) ASTMolecularTypePattern(org.vcell.model.bngl.ASTMolecularTypePattern) StringReader(java.io.StringReader) ParseException(org.vcell.model.bngl.ParseException)

Example 3 with ParseException

use of org.vcell.model.bngl.ParseException in project vcell by virtualcell.

the class RbmUtils method importBnglFile.

public static ASTModel importBnglFile(BufferedReader br) throws ParseException {
    try {
        // remove all the comments
        reactionRuleNames.clear();
        // just the prologue
        StringBuilder sPrologBuilder = new StringBuilder();
        StringBuilder sb = new StringBuilder();
        ArrayList<BnglComment> comments = new ArrayList<BnglComment>();
        int lineNumber = 0;
        boolean bEscapingExpressionBegin = false;
        boolean inProlog = true;
        BnglLocation location = BnglLocation.OutsideBlock;
        Set<String> compartments = new HashSet<>();
        Map<String, String> anchors = new HashMap<>();
        while (true) {
            String line = br.readLine();
            if (line == null) {
                break;
            }
            line = line.trim();
            line = applySyntaxCorrections(line);
            // we capture all the prologue and insert in in the BioModel notes
            if (line.startsWith("begin model") || line.startsWith("begin parameters")) {
                inProlog = false;
            }
            if (inProlog == true) {
                sPrologBuilder.append(line);
                sPrologBuilder.append("\n");
                sb.append("\n");
                lineNumber++;
                continue;
            }
            if (line.startsWith("version")) {
                // we include the version in the prologue even if it shows up later in the code
                sPrologBuilder.append(line);
                sPrologBuilder.append("\n");
                sb.append("\n");
                lineNumber++;
                continue;
            }
            if (line.length() == 0 || line.charAt(0) == '#') {
                if (line.length() > 0 && line.charAt(0) == '#') {
                    BnglComment bc = new BnglComment("empty", lineNumber, location, line);
                    comments.add(bc);
                }
                sb.append("\n");
                lineNumber++;
                continue;
            }
            if (line.endsWith(":\\")) {
                // we'll try to treat single line labels as comments
                sb.append("\n");
                lineNumber++;
                continue;
            } else if (line.endsWith("\\")) {
                // concatenation with next line, we make one single continuous line
                String line2 = br.readLine();
                if (line2 == null) {
                    break;
                }
                line2 = line2.trim();
                // we don't try to get too fancy here, we'll just assume there are 2 lines of code somewhere
                // within a block and we simply concatenate them; if it's more than 2 we're out of luck
                int concatenationTokenIndex = line.lastIndexOf("\\");
                line = line.substring(0, concatenationTokenIndex);
                if (line.endsWith(" ")) {
                    line = line + line2;
                } else {
                    line = line + " " + line2;
                }
                // we add an empty line so that the total number of lines in the document won't change
                sb.append("\n");
                lineNumber++;
            }
            if (line.startsWith("end parameters") || line.startsWith("end seed species")) {
                // TODO: position sensitive, do not move this 'if' down
                bEscapingExpressionBegin = false;
            }
            // remove comments which follow some code
            int commentIndex = line.indexOf('#');
            if (commentIndex >= 0) {
                BnglComment bc = new BnglComment("item ", lineNumber, location, line.substring(commentIndex));
                comments.add(bc);
                line = line.substring(0, commentIndex);
            }
            int labelEndIndex = line.indexOf(":");
            if (labelEndIndex > 0 && line.substring(0, labelEndIndex).contains("@")) {
                // this is not a label, is a compartment
                ;
            } else {
                if (labelEndIndex == -1) {
                    // there may still be a label present, just without the ":"
                    StringTokenizer st = new StringTokenizer(line);
                    String nextToken = st.nextToken();
                    String prefix = "";
                    if (nextToken.matches("[0-9]+")) {
                        // we transform them in proper labels by adding a letter prefix and the ":" suffix
                        if (location == BnglLocation.ReactionRule) {
                            // labels can't start with a number, so we add "r" as a prefix
                            prefix = "r";
                        } else {
                            // this just for consistency, below we'll actually remove all labels except the reaction rule ones
                            prefix = "l";
                        }
                        line = line.replaceFirst(nextToken, prefix + nextToken + ":");
                        labelEndIndex = line.indexOf(":");
                    }
                }
                // remove labels except for reaction rule labels
                if (labelEndIndex >= 0 && line.length() > labelEndIndex) {
                    // we're certain they cannot be inside a comment since comments were removed already (above)
                    if (location == BnglLocation.ReactionRule) {
                        String reactionRuleName = line.substring(0, labelEndIndex);
                        if (reactionRuleNames.indexOf(reactionRuleName) != -1) {
                            // already in use
                            line = line.substring(labelEndIndex);
                            reactionRuleName = reactionRuleName + "_" + lineNumber;
                            line = reactionRuleName + line;
                        }
                        reactionRuleNames.add(reactionRuleName);
                    } else {
                        line = line.substring(labelEndIndex + 1);
                    }
                }
            }
            // there may be some blanks hanging around
            line = line.trim();
            if (line.length() == 0) {
                // line may be empty now
                sb.append("\n");
                lineNumber++;
                continue;
            }
            if (bEscapingExpressionBegin) {
                StringTokenizer st = new StringTokenizer(line);
                String nextToken = st.nextToken();
                if (Character.isDigit(nextToken.charAt(0))) {
                    sb.append(nextToken + " ");
                    nextToken = st.nextToken();
                }
                sb.append(nextToken);
                sb.append(" {");
                while (st.hasMoreTokens()) {
                    sb.append(st.nextToken());
                }
                sb.append("}");
                sb.append("\n");
            } else {
                sb.append(line + "\n");
                if (location == BnglLocation.Compartment) {
                    // make a list with all the compartment names, we'll need them during phase 2 to remove the "containing
                    // compartment" (which we can't deal with) and to build the escape expression for the volume using the  { }
                    StringTokenizer st = new StringTokenizer(line);
                    // first token is compartment name
                    String firstToken = st.nextToken();
                    if (!compartments.add(firstToken)) {
                        System.out.println("BnglPreprocessor: Duplicate compartment name!" + firstToken);
                    }
                }
            }
            if (line.startsWith("begin parameters") || line.startsWith("begin seed species")) {
                // TODO: position sensitive, do not move this 'if' up
                bEscapingExpressionBegin = true;
            }
            location = markBlock(location, line);
            lineNumber++;
        }
        br.close();
        ListIterator<BnglComment> it = comments.listIterator();
        while (it.hasNext()) {
            BnglComment bc = it.next();
            System.out.println(bc.entityName + " " + bc.location + " " + bc.comment);
        }
        // pass 2, deal with comments and labels
        String cleanedBngl = sb.toString();
        // System.out.println(cleanedBngl);
        br = new BufferedReader(new StringReader(cleanedBngl));
        sb = new StringBuilder();
        lineNumber = 0;
        location = BnglLocation.OutsideBlock;
        while (true) {
            String line = br.readLine();
            if (line == null) {
                // end of document
                break;
            }
            if (line.isEmpty()) {
                sb.append("\n");
                lineNumber++;
                continue;
            }
            BnglLocation newLocation = markBlock(location, line);
            if ((newLocation == BnglLocation.ReactionRule) && (location == BnglLocation.ReactionRule)) {
                int labelEndIndex = line.indexOf(":");
                if (labelEndIndex == -1) {
                    // no label on this reaction rule, so we make one
                    String reactionRuleName = generateReactionRuleName();
                    if (reactionRuleNames.indexOf(reactionRuleName) != -1) {
                        // already in use
                        reactionRuleName = reactionRuleName + "_" + lineNumber;
                    }
                    reactionRuleNames.add(reactionRuleName);
                    line = reactionRuleName + ":" + line;
                    sb.append(line + "\n");
                } else {
                    // rule has label, we keep it as it is
                    sb.append(line + "\n");
                }
            } else if ((newLocation == BnglLocation.Compartment) && (location == BnglLocation.Compartment)) {
                // remove the optional "containing compartment" if specified
                System.out.println(line);
                StringTokenizer st = new StringTokenizer(line);
                String lastToken = "";
                while (st.hasMoreTokens()) {
                    lastToken = st.nextToken();
                }
                if (compartments.contains(lastToken)) {
                    line = line.substring(0, line.lastIndexOf(lastToken));
                }
                line = line.trim();
                // start again and add the { } around the expression of volume
                st = new StringTokenizer(line);
                // name
                String nextToken = st.nextToken();
                sb.append(nextToken + " ");
                // dimension
                nextToken = st.nextToken();
                sb.append(nextToken + " ");
                sb.append("{");
                while (st.hasMoreTokens()) {
                    sb.append(st.nextToken());
                }
                sb.append("}");
                sb.append("\n");
            } else {
                // all other cases nothing special to do
                sb.append(line + "\n");
            }
            location = newLocation;
            lineNumber++;
        }
        br.close();
        cleanedBngl = sb.toString();
        // System.out.println(cleanedBngl);
        // BufferedWriter writer = null;
        // try	{
        // writer = new BufferedWriter( new FileWriter( "c:\\TEMP\\workRules.bngl"));
        // writer.write( cleanedBngl);
        // }
        // catch ( IOException e) {
        // }
        // finally {
        // try {
        // if ( writer != null)
        // writer.close( );
        // }
        // catch ( IOException e) {
        // }
        // }
        // BufferedReader br1 = new BufferedReader(new FileReader("c:\\TEMP\\workRules.bngl"));
        // try {
        // StringBuilder sb1 = new StringBuilder();
        // String line = br1.readLine();
        // while (line != null) {
        // sb1.append(line);
        // sb1.append("\n");
        // line = br1.readLine();
        // }
        // cleanedBngl = sb1.toString();
        // } finally {
        // br.close();
        // }
        // System.out.println(cleanedBngl);
        BNGLParser parser = new BNGLParser(new StringReader(cleanedBngl));
        ASTModel astModel = parser.Model();
        String prologString = sPrologBuilder.toString();
        astModel.setProlog(prologString);
        return astModel;
    // BnglObjectConstructionVisitor constructionVisitor = new BnglObjectConstructionVisitor(rbmModelContainer);
    // astModel.jjtAccept(constructionVisitor, rbmModelContainer);
    } catch (Throwable ex) {
        // ex.printStackTrace();
        if (ex instanceof ParseException) {
            ParseException pe = (ParseException) ex;
            throw pe;
        } else {
            throw new ParseException(ex.getMessage());
        }
    }
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) StringTokenizer(java.util.StringTokenizer) BNGLParser(org.vcell.model.bngl.BNGLParser) BufferedReader(java.io.BufferedReader) StringReader(java.io.StringReader) ParseException(org.vcell.model.bngl.ParseException) ASTModel(org.vcell.model.bngl.ASTModel) HashSet(java.util.HashSet)

Example 4 with ParseException

use of org.vcell.model.bngl.ParseException in project vcell by virtualcell.

the class SpeciesContext method parseSpeciesPatternString.

public void parseSpeciesPatternString(Model model) {
    if (speciesPatternString.equalsIgnoreCase("null")) {
        System.out.println("Species Pattern String is 'NULL'.");
        return;
    }
    if (speciesPatternString != null) {
        try {
            if (speciesPattern != null) {
                System.out.println("Species pattern already exists: " + speciesPattern.toString());
                return;
            }
            SpeciesPattern sp = RbmUtils.parseSpeciesPattern(speciesPatternString, model);
            setSpeciesPattern(sp);
        } catch (ParseException e) {
            e.printStackTrace();
            throw new RuntimeException("Bad format for repository species pattern string: " + e.getMessage());
        }
    }
}
Also used : ParseException(org.vcell.model.bngl.ParseException) SpeciesPattern(org.vcell.model.rbm.SpeciesPattern)

Example 5 with ParseException

use of org.vcell.model.bngl.ParseException in project vcell by virtualcell.

the class ViewGeneratedSpeciesPanel method updateShape.

public void updateShape(int selectedRow) {
    GeneratedSpeciesTableRow speciesTableRow = tableModel.getValueAt(selectedRow);
    String inputString = speciesTableRow.getExpression();
    // System.out.println(selectedRows[0] + ": " + inputString);
    Model tempModel = null;
    try {
        tempModel = new Model("MyTempModel");
        tempModel.addFeature("c0");
    } catch (ModelException | PropertyVetoException e1) {
        e1.printStackTrace();
    }
    if (owner != null && owner.getSimulationContext() != null) {
        List<MolecularType> mtList = owner.getSimulationContext().getModel().getRbmModelContainer().getMolecularTypeList();
        try {
            tempModel.getRbmModelContainer().setMolecularTypeList(mtList);
        } catch (PropertyVetoException e1) {
            e1.printStackTrace();
            throw new RuntimeException("Unexpected exception setting " + MolecularType.typeName + " list: " + e1.getMessage(), e1);
        }
    } else {
        System.out.println("something is wrong, we just do nothing rather than crash");
        return;
    }
    try {
        String strStructure = null;
        if (inputString.contains(RbmUtils.SiteStruct)) {
            // we are in the mode where we emulate compartments by adding the compartment name as a fake site
            Pair<List<String>, String> p = RbmUtils.extractCompartment(inputString);
            // we'll just assume there's only one, may want to throw exception if more
            strStructure = p.one.get(0);
            inputString = p.two;
        } else {
            // should be the normal @comp:expression format - if it's not it will return null
            strStructure = RbmUtils.parseCompartment(inputString, tempModel);
        }
        Structure structure;
        if (strStructure != null) {
            if (tempModel.getStructure(strStructure) == null) {
                if (owner.getSimulationContext().getModel().getStructure(strStructure).getTypeName().equals(Structure.TYPE_NAME_MEMBRANE)) {
                    tempModel.addMembrane(strStructure);
                } else {
                    tempModel.addFeature(strStructure);
                }
            }
            structure = tempModel.getStructure(strStructure);
        } else {
            structure = tempModel.getStructure(0);
        }
        SpeciesPattern sp = (SpeciesPattern) RbmUtils.parseSpeciesPattern(inputString, tempModel);
        sp.resolveBonds();
        SpeciesContext sc = new SpeciesContext(new Species("a", ""), structure, sp);
        spls = new SpeciesPatternLargeShape(20, 20, -1, sp, shapePanel, sc, issueManager);
    } catch (ParseException | PropertyVetoException | ModelException e1) {
        e1.printStackTrace();
        // error (red circle)
        spls = new SpeciesPatternLargeShape(20, 20, -1, shapePanel, true, issueManager);
        shapePanel.repaint();
    }
    int xOffset = spls.getRightEnd() + 45;
    Dimension preferredSize = new Dimension(xOffset + 90, 50);
    shapePanel.setPreferredSize(preferredSize);
    shapePanel.repaint();
}
Also used : ModelException(cbit.vcell.model.ModelException) SpeciesContext(cbit.vcell.model.SpeciesContext) Dimension(java.awt.Dimension) SpeciesPatternLargeShape(cbit.vcell.graph.SpeciesPatternLargeShape) SpeciesPattern(org.vcell.model.rbm.SpeciesPattern) Point(java.awt.Point) PropertyVetoException(java.beans.PropertyVetoException) MolecularType(org.vcell.model.rbm.MolecularType) Model(cbit.vcell.model.Model) VCellSortTableModel(cbit.vcell.client.desktop.biomodel.VCellSortTableModel) List(java.util.List) ArrayList(java.util.ArrayList) ParseException(org.vcell.model.bngl.ParseException) Structure(cbit.vcell.model.Structure) Species(cbit.vcell.model.Species) BNGSpecies(cbit.vcell.bionetgen.BNGSpecies)

Aggregations

ParseException (org.vcell.model.bngl.ParseException)9 BNGSpecies (cbit.vcell.bionetgen.BNGSpecies)4 ModelException (cbit.vcell.model.ModelException)4 Species (cbit.vcell.model.Species)4 SpeciesContext (cbit.vcell.model.SpeciesContext)4 Structure (cbit.vcell.model.Structure)4 PropertyVetoException (java.beans.PropertyVetoException)4 ArrayList (java.util.ArrayList)4 SpeciesPattern (org.vcell.model.rbm.SpeciesPattern)4 Model (cbit.vcell.model.Model)3 StringReader (java.io.StringReader)3 List (java.util.List)3 BNGLParser (org.vcell.model.bngl.BNGLParser)3 MolecularType (org.vcell.model.rbm.MolecularType)3 VCellSortTableModel (cbit.vcell.client.desktop.biomodel.VCellSortTableModel)2 SpeciesPatternLargeShape (cbit.vcell.graph.SpeciesPatternLargeShape)2 ParticleSpeciesPattern (cbit.vcell.math.ParticleSpeciesPattern)2 ReactionRule (cbit.vcell.model.ReactionRule)2 Dimension (java.awt.Dimension)2 Point (java.awt.Point)2