Search in sources :

Example 6 with ModelException

use of cbit.vcell.model.ModelException in project vcell by virtualcell.

the class RulebasedMathMapping method refreshMathDescription.

/**
 * This method was created in VisualAge.
 */
@Override
protected void refreshMathDescription() throws MappingException, MatrixException, MathException, ExpressionException, ModelException {
    // use local variable instead of using getter all the time.
    SimulationContext simContext = getSimulationContext();
    GeometryClass geometryClass = simContext.getGeometry().getGeometrySpec().getSubVolumes()[0];
    Domain domain = new Domain(geometryClass);
    // local structure mapping list
    StructureMapping[] structureMappings = simContext.getGeometryContext().getStructureMappings();
    // We have to check if all the reactions are able to transform to stochastic jump processes before generating the math.
    String stochChkMsg = simContext.getModel().isValidForStochApp();
    if (!(stochChkMsg.equals(""))) {
        throw new ModelException("Problem updating math description: " + simContext.getName() + "\n" + stochChkMsg);
    }
    simContext.checkValidity();
    // 
    if (simContext.getGeometry().getDimension() > 0) {
        throw new MappingException("rule-based particle math mapping not implemented for spatial geometry - dimension >= 1");
    }
    // 
    for (int i = 0; i < structureMappings.length; i++) {
        if (structureMappings[i] instanceof MembraneMapping) {
            if (((MembraneMapping) structureMappings[i]).getCalculateVoltage()) {
                throw new MappingException("electric potential not yet supported for particle models");
            }
        }
    }
    // 
    // fail if any events
    // 
    BioEvent[] bioEvents = simContext.getBioEvents();
    if (bioEvents != null && bioEvents.length > 0) {
        throw new MappingException("events not yet supported for particle-based models");
    }
    // 
    // verify that all structures are mapped to subvolumes and all subvolumes are mapped to a structure
    // 
    Structure[] structures = simContext.getGeometryContext().getModel().getStructures();
    for (int i = 0; i < structures.length; i++) {
        StructureMapping sm = simContext.getGeometryContext().getStructureMapping(structures[i]);
        if (sm == null || (sm instanceof FeatureMapping && ((FeatureMapping) sm).getGeometryClass() == null)) {
            throw new MappingException("model structure '" + structures[i].getName() + "' not mapped to a geometry subVolume");
        }
        if (sm != null && (sm instanceof MembraneMapping) && ((MembraneMapping) sm).getVolumeFractionParameter() != null) {
            Expression volFractExp = ((MembraneMapping) sm).getVolumeFractionParameter().getExpression();
            try {
                if (volFractExp != null) {
                    double volFract = volFractExp.evaluateConstant();
                    if (volFract >= 1.0) {
                        throw new MappingException("model structure '" + (getSimulationContext().getModel().getStructureTopology().getInsideFeature(((MembraneMapping) sm).getMembrane()).getName() + "' has volume fraction >= 1.0"));
                    }
                }
            } catch (ExpressionException e) {
                e.printStackTrace(System.out);
            }
        }
    }
    SubVolume[] subVolumes = simContext.getGeometryContext().getGeometry().getGeometrySpec().getSubVolumes();
    for (int i = 0; i < subVolumes.length; i++) {
        Structure[] mappedStructures = simContext.getGeometryContext().getStructuresFromGeometryClass(subVolumes[i]);
        if (mappedStructures == null || mappedStructures.length == 0) {
            throw new MappingException("geometry subVolume '" + subVolumes[i].getName() + "' not mapped from a model structure");
        }
    }
    // 
    // gather only those reactionRules that are not "excluded"
    // 
    ArrayList<ReactionRule> rrList = new ArrayList<ReactionRule>();
    for (ReactionRuleSpec reactionRuleSpec : simContext.getReactionContext().getReactionRuleSpecs()) {
        if (!reactionRuleSpec.isExcluded()) {
            rrList.add(reactionRuleSpec.getReactionRule());
        }
    }
    // 
    for (ReactionRule reactionRule : rrList) {
        UnresolvedParameter[] unresolvedParameters = reactionRule.getKineticLaw().getUnresolvedParameters();
        if (unresolvedParameters != null && unresolvedParameters.length > 0) {
            StringBuffer buffer = new StringBuffer();
            for (int j = 0; j < unresolvedParameters.length; j++) {
                if (j > 0) {
                    buffer.append(", ");
                }
                buffer.append(unresolvedParameters[j].getName());
            }
            throw new MappingException("In Application '" + simContext.getName() + "', " + reactionRule.getDisplayType() + " '" + reactionRule.getName() + "' contains unresolved identifier(s): " + buffer);
        }
    }
    // 
    // create new MathDescription (based on simContext's previous MathDescription if possible)
    // 
    MathDescription oldMathDesc = simContext.getMathDescription();
    mathDesc = null;
    if (oldMathDesc != null) {
        if (oldMathDesc.getVersion() != null) {
            mathDesc = new MathDescription(oldMathDesc.getVersion());
        } else {
            mathDesc = new MathDescription(oldMathDesc.getName());
        }
    } else {
        mathDesc = new MathDescription(simContext.getName() + "_generated");
    }
    // 
    // temporarily place all variables in a hashtable (before binding) and discarding duplicates
    // 
    VariableHash varHash = new VariableHash();
    // 
    // conversion factors
    // 
    Model model = simContext.getModel();
    varHash.addVariable(new Constant(getMathSymbol(model.getKMOLE(), null), getIdentifierSubstitutions(model.getKMOLE().getExpression(), model.getKMOLE().getUnitDefinition(), null)));
    varHash.addVariable(new Constant(getMathSymbol(model.getN_PMOLE(), null), getIdentifierSubstitutions(model.getN_PMOLE().getExpression(), model.getN_PMOLE().getUnitDefinition(), null)));
    varHash.addVariable(new Constant(getMathSymbol(model.getPI_CONSTANT(), null), getIdentifierSubstitutions(model.getPI_CONSTANT().getExpression(), model.getPI_CONSTANT().getUnitDefinition(), null)));
    varHash.addVariable(new Constant(getMathSymbol(model.getFARADAY_CONSTANT(), null), getIdentifierSubstitutions(model.getFARADAY_CONSTANT().getExpression(), model.getFARADAY_CONSTANT().getUnitDefinition(), null)));
    varHash.addVariable(new Constant(getMathSymbol(model.getFARADAY_CONSTANT_NMOLE(), null), getIdentifierSubstitutions(model.getFARADAY_CONSTANT_NMOLE().getExpression(), model.getFARADAY_CONSTANT_NMOLE().getUnitDefinition(), null)));
    varHash.addVariable(new Constant(getMathSymbol(model.getGAS_CONSTANT(), null), getIdentifierSubstitutions(model.getGAS_CONSTANT().getExpression(), model.getGAS_CONSTANT().getUnitDefinition(), null)));
    varHash.addVariable(new Constant(getMathSymbol(model.getTEMPERATURE(), null), getIdentifierSubstitutions(new Expression(simContext.getTemperatureKelvin()), model.getTEMPERATURE().getUnitDefinition(), null)));
    Enumeration<SpeciesContextMapping> enum1 = getSpeciesContextMappings();
    while (enum1.hasMoreElements()) {
        SpeciesContextMapping scm = enum1.nextElement();
        if (scm.getVariable() instanceof StochVolVariable) {
            varHash.addVariable(scm.getVariable());
        }
    }
    // deals with model parameters
    ModelParameter[] modelParameters = simContext.getModel().getModelParameters();
    for (int j = 0; j < modelParameters.length; j++) {
        Expression expr = getSubstitutedExpr(modelParameters[j].getExpression(), true, false);
        expr = getIdentifierSubstitutions(expr, modelParameters[j].getUnitDefinition(), geometryClass);
        varHash.addVariable(newFunctionOrConstant(getMathSymbol(modelParameters[j], geometryClass), expr, geometryClass));
    }
    // added July 2009, ElectricalStimulusParameter electric mapping tab
    ElectricalStimulus[] elecStimulus = simContext.getElectricalStimuli();
    if (elecStimulus.length > 0) {
        throw new MappingException("Modles with electrophysiology are not supported for stochastic applications.");
    }
    for (int j = 0; j < structureMappings.length; j++) {
        if (structureMappings[j] instanceof MembraneMapping) {
            MembraneMapping memMapping = (MembraneMapping) structureMappings[j];
            Parameter initialVoltageParm = memMapping.getInitialVoltageParameter();
            try {
                Expression exp = initialVoltageParm.getExpression();
                exp.evaluateConstant();
                varHash.addVariable(newFunctionOrConstant(getMathSymbol(memMapping.getMembrane().getMembraneVoltage(), memMapping.getGeometryClass()), getIdentifierSubstitutions(memMapping.getInitialVoltageParameter().getExpression(), memMapping.getInitialVoltageParameter().getUnitDefinition(), memMapping.getGeometryClass()), memMapping.getGeometryClass()));
            } catch (ExpressionException e) {
                e.printStackTrace(System.out);
                throw new MappingException("Membrane initial voltage: " + initialVoltageParm.getName() + " cannot be evaluated as constant.");
            }
        }
    }
    // 
    for (ReactionRule reactionRule : rrList) {
        // if (reactionRule.getKineticLaw() instanceof LumpedKinetics){
        // throw new RuntimeException("Lumped Kinetics not yet supported for RuleBased Modeling");
        // }
        LocalParameter[] parameters = reactionRule.getKineticLaw().getLocalParameters();
        for (LocalParameter parameter : parameters) {
            // 
            if ((parameter.getRole() == RbmKineticLawParameterType.RuleRate)) {
                continue;
            }
            // 
            if (!reactionRule.isReversible() && parameter.getRole() == RbmKineticLawParameterType.MassActionReverseRate) {
                continue;
            }
            Expression expr = getSubstitutedExpr(parameter.getExpression(), true, false);
            varHash.addVariable(newFunctionOrConstant(getMathSymbol(parameter, geometryClass), getIdentifierSubstitutions(expr, parameter.getUnitDefinition(), geometryClass), geometryClass));
        }
    }
    // the parameter "Size" is already put into mathsymbolmapping in refreshSpeciesContextMapping()
    for (int i = 0; i < structureMappings.length; i++) {
        StructureMapping sm = structureMappings[i];
        StructureMapping.StructureMappingParameter parm = sm.getParameterFromRole(StructureMapping.ROLE_Size);
        if (parm.getExpression() != null) {
            try {
                double value = parm.getExpression().evaluateConstant();
                varHash.addVariable(new Constant(getMathSymbol(parm, sm.getGeometryClass()), new Expression(value)));
            } catch (ExpressionException e) {
                // varHash.addVariable(new Function(getMathSymbol0(parm,sm),getIdentifierSubstitutions(parm.getExpression(),parm.getUnitDefinition(),sm)));
                e.printStackTrace(System.out);
                throw new MappingException("Size of structure:" + sm.getNameScope().getName() + " cannot be evaluated as constant.");
            }
        }
    }
    SpeciesContextSpec[] speciesContextSpecs = getSimulationContext().getReactionContext().getSpeciesContextSpecs();
    addInitialConditions(domain, speciesContextSpecs, varHash);
    // 
    if (simContext.getGeometryContext().getGeometry() != null) {
        try {
            mathDesc.setGeometry(simContext.getGeometryContext().getGeometry());
        } catch (java.beans.PropertyVetoException e) {
            e.printStackTrace(System.out);
            throw new MappingException("failure setting geometry " + e.getMessage());
        }
    } else {
        throw new MappingException("Geometry must be defined in Application " + simContext.getName());
    }
    // 
    // create subDomains
    // 
    SubVolume subVolume = simContext.getGeometry().getGeometrySpec().getSubVolumes()[0];
    SubDomain subDomain = new CompartmentSubDomain(subVolume.getName(), 0);
    mathDesc.addSubDomain(subDomain);
    // 
    // define all molecules and unique species patterns (add molecules to mathDesc and speciesPatterns to varHash).
    // 
    HashMap<SpeciesPattern, VolumeParticleSpeciesPattern> speciesPatternMap = addSpeciesPatterns(domain, rrList);
    HashSet<VolumeParticleSpeciesPattern> uniqueParticleSpeciesPatterns = new HashSet<>(speciesPatternMap.values());
    for (VolumeParticleSpeciesPattern volumeParticleSpeciesPattern : uniqueParticleSpeciesPatterns) {
        varHash.addVariable(volumeParticleSpeciesPattern);
    }
    // 
    // define observables (those explicitly declared and those corresponding to seed species.
    // 
    List<ParticleObservable> observables = addObservables(geometryClass, domain, speciesPatternMap);
    for (ParticleObservable particleObservable : observables) {
        varHash.addVariable(particleObservable);
    }
    try {
        addParticleJumpProcesses(varHash, geometryClass, subDomain, speciesPatternMap);
    } catch (PropertyVetoException e1) {
        e1.printStackTrace();
        throw new MappingException(e1.getMessage(), e1);
    }
    // 
    for (int i = 0; i < fieldMathMappingParameters.length; i++) {
        if (fieldMathMappingParameters[i] instanceof UnitFactorParameter || fieldMathMappingParameters[i] instanceof ObservableConcentrationParameter) {
            varHash.addVariable(newFunctionOrConstant(getMathSymbol(fieldMathMappingParameters[i], geometryClass), getIdentifierSubstitutions(fieldMathMappingParameters[i].getExpression(), fieldMathMappingParameters[i].getUnitDefinition(), geometryClass), fieldMathMappingParameters[i].getGeometryClass()));
        }
    }
    // 
    // set Variables to MathDescription all at once with the order resolved by "VariableHash"
    // 
    mathDesc.setAllVariables(varHash.getAlphabeticallyOrderedVariables());
    // 
    for (SpeciesContext sc : model.getSpeciesContexts()) {
        if (!sc.hasSpeciesPattern()) {
            throw new MappingException("species " + sc.getName() + " has no molecular pattern");
        }
        VolumeParticleSpeciesPattern volumeParticleSpeciesPattern = speciesPatternMap.get(sc.getSpeciesPattern());
        ArrayList<ParticleInitialCondition> particleInitialConditions = new ArrayList<ParticleProperties.ParticleInitialCondition>();
        // initial conditions from scs
        SpeciesContextSpec scs = simContext.getReactionContext().getSpeciesContextSpec(sc);
        Parameter initialCountParameter = scs.getInitialCountParameter();
        Expression e = getIdentifierSubstitutions(new Expression(initialCountParameter, getNameScope()), initialCountParameter.getUnitDefinition(), geometryClass);
        particleInitialConditions.add(new ParticleInitialConditionCount(e, new Expression(0.0), new Expression(0.0), new Expression(0.0)));
        ParticleProperties particleProperies = new ParticleProperties(volumeParticleSpeciesPattern, new Expression(0.0), new Expression(0.0), new Expression(0.0), new Expression(0.0), particleInitialConditions);
        subDomain.addParticleProperties(particleProperies);
    }
    // 
    for (int i = 0; i < fieldMathMappingParameters.length; i++) {
        if (fieldMathMappingParameters[i] instanceof UnitFactorParameter) {
            Variable variable = newFunctionOrConstant(getMathSymbol(fieldMathMappingParameters[i], geometryClass), getIdentifierSubstitutions(fieldMathMappingParameters[i].getExpression(), fieldMathMappingParameters[i].getUnitDefinition(), geometryClass), fieldMathMappingParameters[i].getGeometryClass());
            if (mathDesc.getVariable(variable.getName()) == null) {
                mathDesc.addVariable(variable);
            }
        }
        if (fieldMathMappingParameters[i] instanceof ObservableConcentrationParameter) {
            Variable variable = newFunctionOrConstant(getMathSymbol(fieldMathMappingParameters[i], geometryClass), getIdentifierSubstitutions(fieldMathMappingParameters[i].getExpression(), fieldMathMappingParameters[i].getUnitDefinition(), geometryClass), fieldMathMappingParameters[i].getGeometryClass());
            if (mathDesc.getVariable(variable.getName()) == null) {
                mathDesc.addVariable(variable);
            }
        }
    }
    if (!mathDesc.isValid()) {
        System.out.println(mathDesc.getVCML_database());
        throw new MappingException("generated an invalid mathDescription: " + mathDesc.getWarning());
    }
}
Also used : MathDescription(cbit.vcell.math.MathDescription) ArrayList(java.util.ArrayList) SpeciesContext(cbit.vcell.model.SpeciesContext) ExpressionException(cbit.vcell.parser.ExpressionException) PropertyVetoException(java.beans.PropertyVetoException) CompartmentSubDomain(cbit.vcell.math.CompartmentSubDomain) SubDomain(cbit.vcell.math.SubDomain) SubVolume(cbit.vcell.geometry.SubVolume) HashSet(java.util.HashSet) ModelException(cbit.vcell.model.ModelException) VolumeParticleSpeciesPattern(cbit.vcell.math.VolumeParticleSpeciesPattern) PropertyVetoException(java.beans.PropertyVetoException) ModelParameter(cbit.vcell.model.Model.ModelParameter) CompartmentSubDomain(cbit.vcell.math.CompartmentSubDomain) ParticleInitialCondition(cbit.vcell.math.ParticleProperties.ParticleInitialCondition) ParticleProperties(cbit.vcell.math.ParticleProperties) VolumeParticleObservable(cbit.vcell.math.VolumeParticleObservable) ParticleObservable(cbit.vcell.math.ParticleObservable) CompartmentSubDomain(cbit.vcell.math.CompartmentSubDomain) SubDomain(cbit.vcell.math.SubDomain) Domain(cbit.vcell.math.Variable.Domain) GeometryClass(cbit.vcell.geometry.GeometryClass) VolumeParticleVariable(cbit.vcell.math.VolumeParticleVariable) ParticleVariable(cbit.vcell.math.ParticleVariable) StochVolVariable(cbit.vcell.math.StochVolVariable) Variable(cbit.vcell.math.Variable) VariableHash(cbit.vcell.math.VariableHash) MacroscopicRateConstant(cbit.vcell.math.MacroscopicRateConstant) Constant(cbit.vcell.math.Constant) UnresolvedParameter(cbit.vcell.mapping.ParameterContext.UnresolvedParameter) VolumeParticleSpeciesPattern(cbit.vcell.math.VolumeParticleSpeciesPattern) SpeciesPattern(org.vcell.model.rbm.SpeciesPattern) Structure(cbit.vcell.model.Structure) StochVolVariable(cbit.vcell.math.StochVolVariable) ReactionRule(cbit.vcell.model.ReactionRule) LocalParameter(cbit.vcell.mapping.ParameterContext.LocalParameter) Expression(cbit.vcell.parser.Expression) Model(cbit.vcell.model.Model) Parameter(cbit.vcell.model.Parameter) UnresolvedParameter(cbit.vcell.mapping.ParameterContext.UnresolvedParameter) LocalParameter(cbit.vcell.mapping.ParameterContext.LocalParameter) ModelParameter(cbit.vcell.model.Model.ModelParameter) ParticleInitialConditionCount(cbit.vcell.math.ParticleProperties.ParticleInitialConditionCount)

Example 7 with ModelException

use of cbit.vcell.model.ModelException in project vcell by virtualcell.

the class RulebasedTransformer method transform.

private void transform(SimulationContext originalSimContext, SimulationContext transformedSimulationContext, ArrayList<ModelEntityMapping> entityMappings, MathMappingCallback mathMappingCallback) throws PropertyVetoException {
    Model newModel = transformedSimulationContext.getModel();
    Model originalModel = originalSimContext.getModel();
    ModelEntityMapping em = null;
    // list of rules created from the reactions; we apply the symmetry factor computed by bionetgen only to these
    Set<ReactionRule> fromReactions = new HashSet<>();
    for (SpeciesContext newSpeciesContext : newModel.getSpeciesContexts()) {
        final SpeciesContext originalSpeciesContext = originalModel.getSpeciesContext(newSpeciesContext.getName());
        // map new and old species contexts
        em = new ModelEntityMapping(originalSpeciesContext, newSpeciesContext);
        entityMappings.add(em);
        if (newSpeciesContext.hasSpeciesPattern()) {
            // it's perfect already and can't be improved
            continue;
        }
        try {
            MolecularType newmt = newModel.getRbmModelContainer().createMolecularType();
            newModel.getRbmModelContainer().addMolecularType(newmt, false);
            MolecularTypePattern newmtp_sc = new MolecularTypePattern(newmt);
            SpeciesPattern newsp_sc = new SpeciesPattern();
            newsp_sc.addMolecularTypePattern(newmtp_sc);
            newSpeciesContext.setSpeciesPattern(newsp_sc);
            RbmObservable newo = new RbmObservable(newModel, "O0_" + newmt.getName() + "_tot", newSpeciesContext.getStructure(), RbmObservable.ObservableType.Molecules);
            MolecularTypePattern newmtp_ob = new MolecularTypePattern(newmt);
            SpeciesPattern newsp_ob = new SpeciesPattern();
            newsp_ob.addMolecularTypePattern(newmtp_ob);
            newo.addSpeciesPattern(newsp_ob);
            newModel.getRbmModelContainer().addObservable(newo);
            // map new observable to old species context
            em = new ModelEntityMapping(originalSpeciesContext, newo);
            entityMappings.add(em);
        } catch (ModelException e) {
            e.printStackTrace();
            throw new RuntimeException("unable to transform species context: " + e.getMessage());
        } catch (PropertyVetoException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    ReactionSpec[] reactionSpecs = transformedSimulationContext.getReactionContext().getReactionSpecs();
    for (ReactionSpec reactionSpec : reactionSpecs) {
        if (reactionSpec.isExcluded()) {
            // we create rules only from those reactions which are not excluded
            continue;
        }
        ReactionStep rs = reactionSpec.getReactionStep();
        String name = rs.getName();
        String mangled = TokenMangler.fixTokenStrict(name);
        mangled = newModel.getReactionName(mangled);
        Kinetics k = rs.getKinetics();
        if (!(k instanceof MassActionKinetics)) {
            throw new RuntimeException("Only Mass Action Kinetics supported at this time, reaction \"" + rs.getName() + "\" uses kinetic law type \"" + rs.getKinetics().getName() + "\"");
        }
        boolean bReversible = rs.isReversible();
        ReactionRule rr = new ReactionRule(newModel, mangled, rs.getStructure(), bReversible);
        fromReactions.add(rr);
        MassActionKinetics massActionKinetics = (MassActionKinetics) k;
        List<Reactant> rList = rs.getReactants();
        List<Product> pList = rs.getProducts();
        // counting the stoichiometry - 2A+B means 3 reactants
        int numReactants = 0;
        for (Reactant r : rList) {
            numReactants += r.getStoichiometry();
            if (numReactants > 2) {
                String message = "NFSim doesn't support more than 2 reactants within a reaction: " + name;
                throw new RuntimeException(message);
            }
        }
        int numProducts = 0;
        for (Product p : pList) {
            numProducts += p.getStoichiometry();
            if (bReversible && numProducts > 2) {
                String message = "NFSim doesn't support more than 2 products within a reversible reaction: " + name;
                throw new RuntimeException(message);
            }
        }
        RateLawType rateLawType = RateLawType.MassAction;
        RbmKineticLaw kineticLaw = new RbmKineticLaw(rr, rateLawType);
        try {
            String forwardRateName = massActionKinetics.getForwardRateParameter().getName();
            Expression forwardRateExp = massActionKinetics.getForwardRateParameter().getExpression();
            String reverseRateName = massActionKinetics.getReverseRateParameter().getName();
            Expression reverseRateExp = massActionKinetics.getReverseRateParameter().getExpression();
            LocalParameter fR = kineticLaw.getLocalParameter(RbmKineticLawParameterType.MassActionForwardRate);
            fR.setName(forwardRateName);
            LocalParameter rR = kineticLaw.getLocalParameter(RbmKineticLawParameterType.MassActionReverseRate);
            rR.setName(reverseRateName);
            if (rs.hasReactant()) {
                kineticLaw.setParameterValue(fR, forwardRateExp, true);
            }
            if (rs.hasProduct()) {
                kineticLaw.setParameterValue(rR, reverseRateExp, true);
            }
            // 
            for (KineticsParameter reaction_p : massActionKinetics.getKineticsParameters()) {
                if (reaction_p.getRole() == Kinetics.ROLE_UserDefined) {
                    LocalParameter rule_p = kineticLaw.getLocalParameter(reaction_p.getName());
                    if (rule_p == null) {
                        // 
                        // after lazy parameter creation we didn't find a user-defined rule parameter with this same name.
                        // 
                        // there must be a global symbol with the same name, that the local reaction parameter has overridden.
                        // 
                        ParameterContext.LocalProxyParameter rule_proxy_parameter = null;
                        for (ProxyParameter proxyParameter : kineticLaw.getProxyParameters()) {
                            if (proxyParameter.getName().equals(reaction_p.getName())) {
                                rule_proxy_parameter = (LocalProxyParameter) proxyParameter;
                            }
                        }
                        if (rule_proxy_parameter != null) {
                            // we want to convert to local
                            boolean bConvertToGlobal = false;
                            kineticLaw.convertParameterType(rule_proxy_parameter, bConvertToGlobal);
                        } else {
                            // could find neither local parameter nor proxy parameter
                            throw new RuntimeException("user defined parameter " + reaction_p.getName() + " from reaction " + rs.getName() + " didn't map to a reactionRule parameter");
                        }
                    } else if (rule_p.getRole() == RbmKineticLawParameterType.UserDefined) {
                        kineticLaw.setParameterValue(rule_p, reaction_p.getExpression(), true);
                        rule_p.setUnitDefinition(reaction_p.getUnitDefinition());
                    } else {
                        throw new RuntimeException("user defined parameter " + reaction_p.getName() + " from reaction " + rs.getName() + " mapped to a reactionRule parameter with unexpected role " + rule_p.getRole().getDescription());
                    }
                }
            }
        } catch (ExpressionException e) {
            e.printStackTrace();
            throw new RuntimeException("Problem attempting to set RbmKineticLaw expression: " + e.getMessage());
        }
        rr.setKineticLaw(kineticLaw);
        KineticsParameter[] kpList = k.getKineticsParameters();
        ModelParameter[] mpList = rs.getModel().getModelParameters();
        ModelParameter mp = rs.getModel().getModelParameter(kpList[0].getName());
        ReactionParticipant[] rpList = rs.getReactionParticipants();
        for (ReactionParticipant p : rpList) {
            if (p instanceof Reactant) {
                int stoichiometry = p.getStoichiometry();
                for (int i = 0; i < stoichiometry; i++) {
                    SpeciesPattern speciesPattern = new SpeciesPattern(rs.getModel(), p.getSpeciesContext().getSpeciesPattern());
                    ReactantPattern reactantPattern = new ReactantPattern(speciesPattern, p.getStructure());
                    rr.addReactant(reactantPattern);
                }
            } else if (p instanceof Product) {
                int stoichiometry = p.getStoichiometry();
                for (int i = 0; i < stoichiometry; i++) {
                    SpeciesPattern speciesPattern = new SpeciesPattern(rs.getModel(), p.getSpeciesContext().getSpeciesPattern());
                    ProductPattern productPattern = new ProductPattern(speciesPattern, p.getStructure());
                    rr.addProduct(productPattern);
                }
            }
        }
        // commented code below is probably obsolete, we verify (above) in the reaction the number of participants,
        // no need to do it again in the corresponding rule
        // if(rr.getReactantPatterns().size() > 2) {
        // String message = "NFSim doesn't support more than 2 reactants within a reaction: " + name;
        // throw new RuntimeException(message);
        // }
        // if(rr.getProductPatterns().size() > 2) {
        // String message = "NFSim doesn't support more than 2 products within a reaction: " + name;
        // throw new RuntimeException(message);
        // }
        newModel.removeReactionStep(rs);
        newModel.getRbmModelContainer().addReactionRule(rr);
    }
    for (ReactionRuleSpec rrs : transformedSimulationContext.getReactionContext().getReactionRuleSpecs()) {
        if (rrs == null) {
            continue;
        }
        ReactionRule rr = rrs.getReactionRule();
        if (rrs.isExcluded()) {
            // delete those rules which are disabled (excluded) in the Specifications / Reaction table
            newModel.getRbmModelContainer().removeReactionRule(rr);
            continue;
        }
    }
    // now that we generated the rules we can delete the reaction steps they're coming from
    for (ReactionStep rs : newModel.getReactionSteps()) {
        newModel.removeReactionStep(rs);
    }
    try {
        // we invoke bngl just for the purpose of generating the xml file, which we'll then use to extract the symmetry factor
        generateNetwork(transformedSimulationContext, fromReactions, mathMappingCallback);
    } catch (ClassNotFoundException | IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println("Finished RuleBased Transformer.");
}
Also used : Product(cbit.vcell.model.Product) SpeciesContext(cbit.vcell.model.SpeciesContext) Reactant(cbit.vcell.model.Reactant) LocalProxyParameter(cbit.vcell.mapping.ParameterContext.LocalProxyParameter) SpeciesPattern(org.vcell.model.rbm.SpeciesPattern) ExpressionException(cbit.vcell.parser.ExpressionException) KineticsParameter(cbit.vcell.model.Kinetics.KineticsParameter) RateLawType(cbit.vcell.model.RbmKineticLaw.RateLawType) HashSet(java.util.HashSet) ReactantPattern(cbit.vcell.model.ReactantPattern) ReactionRule(cbit.vcell.model.ReactionRule) ModelException(cbit.vcell.model.ModelException) ProductPattern(cbit.vcell.model.ProductPattern) RbmObservable(cbit.vcell.model.RbmObservable) RbmKineticLaw(cbit.vcell.model.RbmKineticLaw) IOException(java.io.IOException) MolecularType(org.vcell.model.rbm.MolecularType) PropertyVetoException(java.beans.PropertyVetoException) LocalParameter(cbit.vcell.mapping.ParameterContext.LocalParameter) ModelParameter(cbit.vcell.model.Model.ModelParameter) ProxyParameter(cbit.vcell.model.ProxyParameter) LocalProxyParameter(cbit.vcell.mapping.ParameterContext.LocalProxyParameter) Expression(cbit.vcell.parser.Expression) ReactionStep(cbit.vcell.model.ReactionStep) Model(cbit.vcell.model.Model) MassActionKinetics(cbit.vcell.model.MassActionKinetics) Kinetics(cbit.vcell.model.Kinetics) MassActionKinetics(cbit.vcell.model.MassActionKinetics) MolecularTypePattern(org.vcell.model.rbm.MolecularTypePattern) ReactionParticipant(cbit.vcell.model.ReactionParticipant)

Example 8 with ModelException

use of cbit.vcell.model.ModelException in project vcell by virtualcell.

the class ModelOptimizationMapping method getRemappedReferenceData.

/**
 * Gets the constraintData property (cbit.vcell.opt.ConstraintData) value.
 * @return The constraintData property value.
 * @see #setConstraintData
 */
private ReferenceData getRemappedReferenceData(MathMapping mathMapping) throws MappingException {
    if (modelOptimizationSpec.getReferenceData() == null) {
        return null;
    }
    // 
    // make sure time is mapped
    // 
    ReferenceData refData = modelOptimizationSpec.getReferenceData();
    ReferenceDataMappingSpec[] refDataMappingSpecs = modelOptimizationSpec.getReferenceDataMappingSpecs();
    RowColumnResultSet rowColResultSet = new RowColumnResultSet();
    Vector<SymbolTableEntry> modelObjectList = new Vector<SymbolTableEntry>();
    Vector<double[]> dataList = new Vector<double[]>();
    // 
    // find bound columns, (time is always mapped to the first column)
    // 
    int mappedColumnCount = 0;
    for (int i = 0; i < refDataMappingSpecs.length; i++) {
        SymbolTableEntry modelObject = refDataMappingSpecs[i].getModelObject();
        if (modelObject != null) {
            int mappedColumnIndex = mappedColumnCount;
            if (modelObject instanceof Model.ReservedSymbol && ((ReservedSymbol) modelObject).isTime()) {
                mappedColumnIndex = 0;
            }
            String origRefDataColumnName = refDataMappingSpecs[i].getReferenceDataColumnName();
            int origRefDataColumnIndex = refData.findColumn(origRefDataColumnName);
            if (origRefDataColumnIndex < 0) {
                throw new RuntimeException("reference data column named '" + origRefDataColumnName + "' not found");
            }
            double[] columnData = refData.getDataByColumn(origRefDataColumnIndex);
            if (modelObjectList.contains(modelObject)) {
                throw new RuntimeException("multiple reference data columns mapped to same model object '" + modelObject.getName() + "'");
            }
            modelObjectList.insertElementAt(modelObject, mappedColumnIndex);
            dataList.insertElementAt(columnData, mappedColumnIndex);
            mappedColumnCount++;
        }
    }
    // 
    if (modelObjectList.size() == 0) {
        throw new RuntimeException("reference data was not associated with model");
    }
    if (modelObjectList.size() == 1) {
        throw new RuntimeException("reference data was not associated with model, must map time and at least one other column");
    }
    boolean bFoundTimeVar = false;
    for (SymbolTableEntry ste : modelObjectList) {
        if (ste instanceof Model.ReservedSymbol && ((ReservedSymbol) ste).isTime()) {
            bFoundTimeVar = true;
            break;
        }
    }
    if (!bFoundTimeVar) {
        throw new RuntimeException("must map time column of reference data to model");
    }
    // 
    for (int i = 0; i < modelObjectList.size(); i++) {
        SymbolTableEntry modelObject = (SymbolTableEntry) modelObjectList.elementAt(i);
        try {
            // Find by name because MathSybolMapping has different 'objects' than refDataMapping 'objects'
            Variable variable = mathMapping.getMathSymbolMapping().findVariableByName(modelObject.getName());
            if (variable != null) {
                String symbol = variable.getName();
                rowColResultSet.addDataColumn(new ODESolverResultSetColumnDescription(symbol));
            } else if (modelObject instanceof Model.ReservedSymbol && ((Model.ReservedSymbol) modelObject).isTime()) {
                Model.ReservedSymbol time = (Model.ReservedSymbol) modelObject;
                String symbol = time.getName();
                rowColResultSet.addDataColumn(new ODESolverResultSetColumnDescription(symbol));
            }
        } catch (MathException | MatrixException | ExpressionException | ModelException e) {
            e.printStackTrace();
            throw new MappingException(e.getMessage(), e);
        }
    }
    // 
    // populate data columns (time and rest)
    // 
    double[] weights = new double[rowColResultSet.getColumnDescriptionsCount()];
    weights[0] = 1.0;
    int numRows = ((double[]) dataList.elementAt(0)).length;
    int numColumns = modelObjectList.size();
    for (int j = 0; j < numRows; j++) {
        double[] row = new double[numColumns];
        for (int i = 0; i < numColumns; i++) {
            row[i] = ((double[]) dataList.elementAt(i))[j];
            if (i > 0) {
                weights[i] += row[i] * row[i];
            }
        }
        rowColResultSet.addRow(row);
    }
    for (int i = 0; i < numColumns; i++) {
        if (weights[i] == 0) {
            weights[i] = 1;
        } else {
            weights[i] = 1 / weights[i];
        }
    }
    SimpleReferenceData remappedRefData = new SimpleReferenceData(rowColResultSet, weights);
    return remappedRefData;
}
Also used : ParameterVariable(cbit.vcell.math.ParameterVariable) Variable(cbit.vcell.math.Variable) ReservedSymbol(cbit.vcell.model.Model.ReservedSymbol) ReservedSymbol(cbit.vcell.model.Model.ReservedSymbol) ExpressionException(cbit.vcell.parser.ExpressionException) MappingException(cbit.vcell.mapping.MappingException) MatrixException(cbit.vcell.matrix.MatrixException) SymbolTableEntry(cbit.vcell.parser.SymbolTableEntry) ODESolverResultSetColumnDescription(cbit.vcell.math.ODESolverResultSetColumnDescription) Vector(java.util.Vector) RowColumnResultSet(cbit.vcell.math.RowColumnResultSet) ModelException(cbit.vcell.model.ModelException) SimpleReferenceData(cbit.vcell.opt.SimpleReferenceData) SimpleReferenceData(cbit.vcell.opt.SimpleReferenceData) ReferenceData(cbit.vcell.opt.ReferenceData) MathException(cbit.vcell.math.MathException) Model(cbit.vcell.model.Model)

Example 9 with ModelException

use of cbit.vcell.model.ModelException in project vcell by virtualcell.

the class BioCartoonTool method mapStructures.

// map the structures to be pasted to existing structures in the cloned model
// we may need to generate some name iteratively until we solve all naming conflicts
private static Map<Structure, String> mapStructures(Component requester, ReactionSpeciesCopy rsCopy, Model modelTo, Structure structTo, IssueContext issueContext) {
    // use internally only; we exit the dialog when there are no issues left
    Vector<Issue> issueVector = new Vector<>();
    Structure structFrom = rsCopy.getFromStructure();
    Map<Structure, String> fullyMappedStructures = new LinkedHashMap<>();
    fullyMappedStructures.put(structFrom, structTo.getName());
    StructurePasteMappingPanel structureMappingPanel = null;
    do {
        issueVector.clear();
        if (structureMappingPanel == null) {
            structureMappingPanel = new StructurePasteMappingPanel(rsCopy, modelTo, structTo, issueVector, issueContext);
            structureMappingPanel.setPreferredSize(new Dimension(400, 220));
        }
        int result = DialogUtils.showComponentOKCancelDialog(requester, structureMappingPanel, "Assign 'From' structures to 'To' structures");
        if (result != JOptionPane.OK_OPTION) {
            throw UserCancelException.CANCEL_GENERIC;
        }
    } while (structureMappingPanel.hasErrors());
    for (Map.Entry<Structure, JComboBox<String>> entry : structureMappingPanel.getStructureMap().entrySet()) {
        if (entry.getValue().getSelectedItem().equals(StructurePasteMappingPanel.MAKE_NEW)) {
            // we generate a "to" structure name based on the "from" name
            String newNameTo = entry.getKey().getName();
            while (modelTo.getStructure(newNameTo) != null) {
                newNameTo = org.vcell.util.TokenMangler.getNextEnumeratedToken(newNameTo);
                for (Structure sFrom : rsCopy.getStructuresArr()) {
                    if (newNameTo.equals(sFrom.getName())) {
                        // the new name must not match any existing "from" name either
                        newNameTo = org.vcell.util.TokenMangler.getNextEnumeratedToken(newNameTo);
                        break;
                    }
                }
            }
            try {
                // as to avoid risk of duplicates / conflicting names
                if (entry.getKey() instanceof Membrane) {
                    modelTo.addMembrane(newNameTo);
                } else {
                    modelTo.addFeature(newNameTo);
                }
            } catch (ModelException | PropertyVetoException e) {
                throw new RuntimeException("Failed to generate the missing 'from' Structures in the cloned model, " + e.getMessage());
            }
            fullyMappedStructures.put(entry.getKey(), newNameTo);
        } else {
            // name of an existing "to" structure
            fullyMappedStructures.put(entry.getKey(), (String) entry.getValue().getSelectedItem());
        }
    }
    return fullyMappedStructures;
}
Also used : Issue(org.vcell.util.Issue) JComboBox(javax.swing.JComboBox) ModelException(cbit.vcell.model.ModelException) Dimension(java.awt.Dimension) LinkedHashMap(java.util.LinkedHashMap) PropertyVetoException(java.beans.PropertyVetoException) Membrane(cbit.vcell.model.Membrane) Structure(cbit.vcell.model.Structure) Vector(java.util.Vector) Map(java.util.Map) IdentityHashMap(java.util.IdentityHashMap) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap)

Example 10 with ModelException

use of cbit.vcell.model.ModelException in project vcell by virtualcell.

the class MathVerifier method scan.

/**
 * Insert the method's description here.
 * Creation date: (2/2/01 3:40:29 PM)
 */
public void scan(User[] users, boolean bUpdateDatabase, KeyValue[] bioAndMathModelKeys) throws MathException, MappingException, SQLException, DataAccessException, ModelException, ExpressionException {
    // java.util.Calendar calendar = java.util.GregorianCalendar.getInstance();
    // //	calendar.set(2002,java.util.Calendar.MAY,7+1);
    // calendar.set(2002,java.util.Calendar.JULY,1);
    // final java.util.Date fluxCorrectionOrDisablingBugFixDate = calendar.getTime();
    // //	calendar.set(2001,java.util.Calendar.JUNE,13+1);
    // calendar.set(2002,java.util.Calendar.JANUARY,1);
    // final java.util.Date totalVolumeCorrectionFixDate = calendar.getTime();
    KeyValue[] sortedBioAndMathModelKeys = null;
    if (bioAndMathModelKeys != null) {
        sortedBioAndMathModelKeys = bioAndMathModelKeys.clone();
        Arrays.sort(sortedBioAndMathModelKeys, keyValueCpmparator);
    }
    for (int i = 0; i < users.length; i++) {
        User user = users[i];
        BioModelInfo[] bioModelInfos0 = dbServerImpl.getBioModelInfos(user, false);
        MathModelInfo[] mathModelInfos0 = dbServerImpl.getMathModelInfos(user, false);
        if (lg.isTraceEnabled())
            lg.trace("Testing user '" + user + "'");
        Vector<VCDocumentInfo> userBioAndMathModelInfoV = new Vector<VCDocumentInfo>();
        userBioAndMathModelInfoV.addAll(Arrays.asList(bioModelInfos0));
        userBioAndMathModelInfoV.addAll(Arrays.asList(mathModelInfos0));
        // 
        for (int j = 0; j < userBioAndMathModelInfoV.size(); j++) {
            // 
            // if certain Bio or Math models are requested, then filter all else out
            // 
            VCDocumentInfo documentInfo = userBioAndMathModelInfoV.elementAt(j);
            KeyValue versionKey = documentInfo.getVersion().getVersionKey();
            if (sortedBioAndMathModelKeys != null) {
                int srch = Arrays.binarySearch(sortedBioAndMathModelKeys, versionKey, keyValueCpmparator);
                if (srch < 0) {
                    continue;
                }
            }
            if (!(documentInfo instanceof BioModelInfo)) {
                continue;
            }
            // 
            if (skipHash.contains(versionKey)) {
                System.out.println("skipping " + (documentInfo instanceof BioModelInfo ? "BioModel" : "MathModel") + " with key '" + versionKey + "'");
                continue;
            }
            try {
                // 
                // read in the BioModel and MathModel from the database
                // 
                VCDocument vcDocumentFromDBCache = null;
                BigString vcDocumentXMLFromDBCache = null;
                try {
                    long startTime = System.currentTimeMillis();
                    if (documentInfo instanceof BioModelInfo) {
                        vcDocumentXMLFromDBCache = new BigString(dbServerImpl.getServerDocumentManager().getBioModelXML(new QueryHashtable(), user, versionKey, false));
                        vcDocumentFromDBCache = XmlHelper.XMLToBioModel(new XMLSource(vcDocumentXMLFromDBCache.toString()));
                    } else {
                        vcDocumentXMLFromDBCache = new BigString(dbServerImpl.getServerDocumentManager().getMathModelXML(new QueryHashtable(), user, versionKey, false));
                        vcDocumentFromDBCache = XmlHelper.XMLToMathModel(new XMLSource(vcDocumentXMLFromDBCache.toString()));
                    }
                    if (bUpdateDatabase && testFlag.equals(MathVerifier.MV_LOAD_XML)) {
                        updateLoadModelsStatTable_LoadTest(System.currentTimeMillis() - startTime, versionKey, null);
                    }
                } catch (Exception e) {
                    lg.error(e.getMessage(), e);
                    if (bUpdateDatabase && testFlag.equals(MathVerifier.MV_LOAD_XML)) {
                        updateLoadModelsStatTable_LoadTest(0, versionKey, e);
                    }
                }
                if (testFlag.equals(MathVerifier.MV_LOAD_XML)) {
                    // 
                    if (vcDocumentXMLFromDBCache != null) {
                        testDocumentLoad(bUpdateDatabase, user, documentInfo, vcDocumentFromDBCache);
                    }
                } else if (testFlag.equals(MathVerifier.MV_DEFAULT)) {
                    // 
                    if (vcDocumentFromDBCache instanceof BioModel) {
                        BioModel bioModel = (BioModel) vcDocumentFromDBCache;
                        checkMathForBioModel(vcDocumentXMLFromDBCache, bioModel, user, bUpdateDatabase);
                    }
                }
            } catch (Throwable e) {
                // exception in whole BioModel
                lg.error(e.getMessage(), e);
            // can't update anything in database, since we don't know what simcontexts are involved
            }
        }
    }
}
Also used : QueryHashtable(cbit.sql.QueryHashtable) KeyValue(org.vcell.util.document.KeyValue) User(org.vcell.util.document.User) VCDocument(org.vcell.util.document.VCDocument) BioModelInfo(org.vcell.util.document.BioModelInfo) MathModelInfo(org.vcell.util.document.MathModelInfo) BigString(org.vcell.util.BigString) PropertyVetoException(java.beans.PropertyVetoException) MatrixException(cbit.vcell.matrix.MatrixException) ModelException(cbit.vcell.model.ModelException) ObjectNotFoundException(org.vcell.util.ObjectNotFoundException) SQLException(java.sql.SQLException) XmlParseException(cbit.vcell.xml.XmlParseException) DataAccessException(org.vcell.util.DataAccessException) ExpressionException(cbit.vcell.parser.ExpressionException) MappingException(cbit.vcell.mapping.MappingException) MathException(cbit.vcell.math.MathException) VCDocumentInfo(org.vcell.util.document.VCDocumentInfo) BioModel(cbit.vcell.biomodel.BioModel) Vector(java.util.Vector) XMLSource(cbit.vcell.xml.XMLSource)

Aggregations

ModelException (cbit.vcell.model.ModelException)27 PropertyVetoException (java.beans.PropertyVetoException)25 Model (cbit.vcell.model.Model)14 Structure (cbit.vcell.model.Structure)12 ExpressionException (cbit.vcell.parser.ExpressionException)12 SpeciesContext (cbit.vcell.model.SpeciesContext)9 SpeciesPattern (org.vcell.model.rbm.SpeciesPattern)9 MappingException (cbit.vcell.mapping.MappingException)8 VCellSortTableModel (cbit.vcell.client.desktop.biomodel.VCellSortTableModel)7 SimulationContext (cbit.vcell.mapping.SimulationContext)7 MathDescription (cbit.vcell.math.MathDescription)7 Expression (cbit.vcell.parser.Expression)7 ArrayList (java.util.ArrayList)7 Vector (java.util.Vector)7 MolecularType (org.vcell.model.rbm.MolecularType)7 BioModel (cbit.vcell.biomodel.BioModel)6 MathException (cbit.vcell.math.MathException)6 MatrixException (cbit.vcell.matrix.MatrixException)5 ModelParameter (cbit.vcell.model.Model.ModelParameter)5 ReactionStep (cbit.vcell.model.ReactionStep)5