Search in sources :

Example 11 with Kinetics

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

the class XmlHelper method applyOverridesForSBML.

/**
 * applyOverrides: private method to apply overrides from the simulation in 'simJob' to simContext, if any.
 * 				Start off by cloning biomodel, since all the references are required in cloned simContext and is
 * 				best retained by cloning biomodel.
 * @param bm - biomodel to be cloned
 * @param sc - simulationContext to be cloned and overridden using math overrides in simulation
 * @param simJob - simulationJob from where simulation with overrides is obtained.
 * @return
 */
public static SimulationContext applyOverridesForSBML(BioModel bm, SimulationContext sc, SimulationJob simJob) {
    SimulationContext overriddenSimContext = sc;
    if (simJob != null) {
        Simulation sim = simJob.getSimulation();
        // need to clone Biomodel, simContext, etc. only if simulation has override(s)
        try {
            if (sim != null && sim.getMathOverrides().hasOverrides()) {
                // BioModel clonedBM = (BioModel)BeanUtils.cloneSerializable(bm);
                BioModel clonedBM = XMLToBioModel(new XMLSource(bioModelToXML(bm)));
                clonedBM.refreshDependencies();
                // get the simContext in cloned Biomodel that corresponds to 'sc'
                SimulationContext[] simContexts = clonedBM.getSimulationContexts();
                for (int i = 0; i < simContexts.length; i++) {
                    if (simContexts[i].getName().equals(sc.getName())) {
                        overriddenSimContext = simContexts[i];
                        break;
                    }
                }
                // 
                overriddenSimContext.getModel().refreshDependencies();
                overriddenSimContext.refreshDependencies();
                MathMapping mathMapping = overriddenSimContext.createNewMathMapping();
                MathSymbolMapping msm = mathMapping.getMathSymbolMapping();
                MathOverrides mathOverrides = sim.getMathOverrides();
                String[] moConstNames = mathOverrides.getOverridenConstantNames();
                for (int i = 0; i < moConstNames.length; i++) {
                    cbit.vcell.math.Constant overriddenConstant = mathOverrides.getConstant(moConstNames[i]);
                    // Expression overriddenExpr = mathOverrides.getActualExpression(moConstNames[i], 0);
                    Expression overriddenExpr = mathOverrides.getActualExpression(moConstNames[i], simJob.getJobIndex());
                    // The above constant (from mathoverride) is not the same instance as the one in the MathSymbolMapping hash.
                    // Hence retreive the correct instance from mathSymbolMapping (mathMapping -> mathDescription) and use it to
                    // retrieve its value (symbolTableEntry) from hash.
                    cbit.vcell.math.Variable overriddenVar = msm.findVariableByName(overriddenConstant.getName());
                    cbit.vcell.parser.SymbolTableEntry[] stes = msm.getBiologicalSymbol(overriddenVar);
                    if (stes == null) {
                        throw new NullPointerException("No matching biological symbol for : " + overriddenConstant.getName());
                    }
                    if (stes.length > 1) {
                        throw new RuntimeException("Cannot have more than one mapping entry for constant : " + overriddenConstant.getName());
                    }
                    if (stes[0] instanceof Parameter) {
                        Parameter param = (Parameter) stes[0];
                        if (param.isExpressionEditable()) {
                            if (param instanceof Kinetics.KineticsParameter) {
                                // Kinetics param has to be set separately for the integrity of the kinetics object
                                Kinetics.KineticsParameter kinParam = (Kinetics.KineticsParameter) param;
                                ReactionStep[] rs = overriddenSimContext.getModel().getReactionSteps();
                                for (int j = 0; j < rs.length; j++) {
                                    if (rs[j].getNameScope().getName().equals(kinParam.getNameScope().getName())) {
                                        rs[j].getKinetics().setParameterValue(kinParam, overriddenExpr);
                                    }
                                }
                            } else if (param instanceof cbit.vcell.model.ExpressionContainer) {
                                // If it is any other editable param, set its expression with the
                                ((cbit.vcell.model.ExpressionContainer) param).setExpression(overriddenExpr);
                            }
                        }
                    }
                // end - if (stes[0] is Parameter)
                }
            // end  - for moConstNames
            }
        // end if (sim has MathOverrides)
        } catch (Exception e) {
            e.printStackTrace(System.out);
            throw new RuntimeException("Could not apply overrides from simulation to application parameters : " + e.getMessage());
        }
    }
    // end if (simJob != null)
    return overriddenSimContext;
}
Also used : SimulationContext(cbit.vcell.mapping.SimulationContext) MathSymbolMapping(cbit.vcell.mapping.MathSymbolMapping) XMLStreamException(javax.xml.stream.XMLStreamException) SbmlException(org.vcell.sbml.SbmlException) SBMLException(org.sbml.jsbml.SBMLException) IOException(java.io.IOException) ExpressionException(cbit.vcell.parser.ExpressionException) MathOverrides(cbit.vcell.solver.MathOverrides) Simulation(cbit.vcell.solver.Simulation) Expression(cbit.vcell.parser.Expression) BioModel(cbit.vcell.biomodel.BioModel) ReactionStep(cbit.vcell.model.ReactionStep) MathMapping(cbit.vcell.mapping.MathMapping) Parameter(cbit.vcell.model.Parameter) Kinetics(cbit.vcell.model.Kinetics)

Example 12 with Kinetics

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

the class ReactionPropertiesPanel method getJToggleButton.

private JButton getJToggleButton() {
    if (jToggleButton == null) {
        jToggleButton = new JButton("Convert");
        jToggleButton.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent e) {
                ModelUnitSystem modelUnitSystem = reactionStep.getModel().getUnitSystem();
                Kinetics kinetics = reactionStep.getKinetics();
                if (kinetics instanceof DistributedKinetics) {
                    try {
                        reactionStep.setKinetics(LumpedKinetics.toLumpedKinetics((DistributedKinetics) kinetics));
                    } catch (Exception e2) {
                        e2.printStackTrace(System.out);
                        if (kinetics.getKineticsDescription().isElectrical()) {
                            DialogUtils.showErrorDialog(ReactionPropertiesPanel.this, "failed to translate into General Current Kinetics [" + modelUnitSystem.getCurrentUnit().getSymbolUnicode() + "]: " + e2.getMessage(), e2);
                        } else {
                            DialogUtils.showErrorDialog(ReactionPropertiesPanel.this, "failed to translate into General Lumped Kinetics [" + modelUnitSystem.getLumpedReactionRateUnit().getSymbolUnicode() + "]: " + e2.getMessage(), e2);
                        }
                    }
                } else if (kinetics instanceof LumpedKinetics) {
                    try {
                        reactionStep.setKinetics(DistributedKinetics.toDistributedKinetics((LumpedKinetics) kinetics));
                    } catch (Exception e2) {
                        e2.printStackTrace(System.out);
                        if (kinetics.getKineticsDescription().isElectrical()) {
                            DialogUtils.showErrorDialog(ReactionPropertiesPanel.this, "failed to translate into General Current Density Kinetics [" + modelUnitSystem.getCurrentDensityUnit().getSymbolUnicode() + "]: " + e2.getMessage(), e2);
                        } else {
                            if (kinetics.getReactionStep().getStructure() instanceof Feature) {
                                DialogUtils.showErrorDialog(ReactionPropertiesPanel.this, "failed to translate into General Kinetics [" + modelUnitSystem.getVolumeReactionRateUnit().getSymbolUnicode() + "]: " + e2.getMessage(), e2);
                            } else {
                                DialogUtils.showErrorDialog(ReactionPropertiesPanel.this, "failed to translate into General Kinetics [" + modelUnitSystem.getMembraneReactionRateUnit().getSymbolUnicode() + "]: " + e2.getMessage(), e2);
                            }
                        }
                    }
                }
            }
        });
    }
    return jToggleButton;
}
Also used : DistributedKinetics(cbit.vcell.model.DistributedKinetics) ActionListener(java.awt.event.ActionListener) LumpedKinetics(cbit.vcell.model.LumpedKinetics) JButton(javax.swing.JButton) Macroscopic_IRRKinetics(cbit.vcell.model.Macroscopic_IRRKinetics) Kinetics(cbit.vcell.model.Kinetics) MassActionKinetics(cbit.vcell.model.MassActionKinetics) DistributedKinetics(cbit.vcell.model.DistributedKinetics) HMM_IRRKinetics(cbit.vcell.model.HMM_IRRKinetics) Microscopic_IRRKinetics(cbit.vcell.model.Microscopic_IRRKinetics) LumpedKinetics(cbit.vcell.model.LumpedKinetics) HMM_REVKinetics(cbit.vcell.model.HMM_REVKinetics) Feature(cbit.vcell.model.Feature) PropertyVetoException(java.beans.PropertyVetoException) ModelUnitSystem(cbit.vcell.model.ModelUnitSystem)

Example 13 with Kinetics

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

the class VCellCopyPasteHelper method chooseApplyPaste.

/**
 * Insert the method's description here.
 * Creation date: (7/10/2006 11:05:19 AM)
 */
public static void chooseApplyPaste(Component requester, String[] pasteDetails, Parameter[] changingParamters, Expression[] newParameterExpression) {
    if (pasteDetails.length != changingParamters.length || changingParamters.length != newParameterExpression.length) {
        throw new IllegalArgumentException(VCellCopyPasteHelper.class.getName() + ".chooseApplyPaste(...) arguments must have unequal lengths");
    }
    // Only present things that will actually change
    boolean bAtLeatOneDifferent = false;
    boolean[] bEnableDisplay = new boolean[changingParamters.length];
    for (int i = 0; i < changingParamters.length; i += 1) {
        // bEnableDisplay[i] = !changingParamters[i].getExpression().equals(newParameterExpression[i]);
        bEnableDisplay[i] = !Compare.isEqualOrNull(changingParamters[i].getExpression(), newParameterExpression[i]);
        bAtLeatOneDifferent = bAtLeatOneDifferent || bEnableDisplay[i];
    }
    if (!bAtLeatOneDifferent) {
        PopupGenerator.showInfoDialog(requester, "All valid paste values are equal to the destination values.\nNo paste needed.");
        return;
    }
    boolean[] bChoices = showChoices(requester, pasteDetails, bEnableDisplay);
    if (bChoices != null) {
        StringBuffer statusMessages = new StringBuffer();
        boolean bFailure = false;
        for (int i = 0; i < changingParamters.length; i += 1) {
            try {
                if (bChoices[i]) {
                    if (changingParamters[i] instanceof Kinetics.KineticsParameter) {
                        Kinetics kinetics = ((ReactionStep) changingParamters[i].getNameScope().getScopedSymbolTable()).getKinetics();
                        kinetics.setParameterValue((Kinetics.KineticsParameter) changingParamters[i], newParameterExpression[i]);
                    } else {
                        throw new Exception("Changing " + changingParamters[i].getNameScope().getName() + " " + changingParamters[i].getName() + " not yet implemented");
                    }
                }
                statusMessages.append("(OK) " + pasteDetails + "\n");
            } catch (Exception e) {
                bFailure = true;
                statusMessages.append("(Failed) " + pasteDetails + " " + e.getMessage() + " " + e.getClass().getName() + "\n");
            }
        }
        if (bFailure) {
            PopupGenerator.showErrorDialog(requester, "Paste Results:\n" + statusMessages.toString());
        }
    }
}
Also used : ReactionStep(cbit.vcell.model.ReactionStep) Kinetics(cbit.vcell.model.Kinetics)

Example 14 with Kinetics

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

the class BNGWindowManager method importSbml.

/**
 * Comment
 */
public void importSbml(String bngSbmlStr) {
    if (bngSbmlStr == null || bngSbmlStr.length() == 0) {
        throw new RuntimeException("SBMl string is empty, cannot import into VCell.");
    }
    // 
    // 1. Convert SBML string from BNG to SBML model, add unitDefintions to SBML model using VCell sbml compatible unit system
    // 2. Import unit modified SBML model into VCell as biomodel
    // 3. Enforce "cleaner" (looking) units on this imported biomodel (can use the units added to the sbml model above)
    // 4. Convert all LumpedKinetics reactions into DistributedKinetics.
    // 4. Convert this biomodel into vcml string and pass it into XMLInfo and then to RequestManager to open document.
    // 
    ModelUnitSystem mus = ModelUnitSystem.createDefaultVCModelUnitSystem();
    ModelUnitSystem sbmlCompatibleVCModelUnitSystem = ModelUnitSystem.createSBMLUnitSystem(mus.getVolumeSubstanceUnit(), mus.getVolumeUnit(), mus.getAreaUnit(), mus.getLengthUnit(), mus.getTimeUnit());
    // display to user to change units if desired.
    UnitSystemSelectionPanel unitSystemSelectionPanel = new UnitSystemSelectionPanel(true);
    unitSystemSelectionPanel.initialize(sbmlCompatibleVCModelUnitSystem);
    int retcode = DialogUtils.showComponentOKCancelDialog(getBngOutputPanel(), unitSystemSelectionPanel, "Select new unit system to import into VCell");
    ModelUnitSystem forcedModelUnitSystem = null;
    while (retcode == JOptionPane.OK_OPTION) {
        try {
            forcedModelUnitSystem = unitSystemSelectionPanel.createModelUnitSystem();
            break;
        } catch (Exception e) {
            e.printStackTrace(System.out);
            DialogUtils.showErrorDialog(getBngOutputPanel(), e.getMessage(), e);
            retcode = DialogUtils.showComponentOKCancelDialog(getBngOutputPanel(), unitSystemSelectionPanel, "Select new unit system to import into VCell");
        }
    }
    if (forcedModelUnitSystem == null) {
        DialogUtils.showErrorDialog(getBngOutputPanel(), "Units are required for import into Virtual Cell.");
    }
    try {
        // SBMLUnitTranslator.addUnitDefinitionsToSbmlModel(bngSbmlStr, forcedModelUnitSystem);
        String modifiedSbmlStr = bngSbmlStr;
        // Create a default VCLogger - SBMLImporter needs it
        cbit.util.xml.VCLogger logger = new cbit.util.xml.VCLogger() {

            @Override
            public void sendMessage(Priority p, ErrorType et, String message) throws Exception {
                System.err.println("LOGGER: msgLevel=" + p + ", msgType=" + et + ", " + message);
                if (p == VCLogger.Priority.HighPriority) {
                    throw new RuntimeException("Import failed : " + message);
                }
            }

            public void sendAllMessages() {
            }

            public boolean hasMessages() {
                return false;
            }
        };
        // import sbml String into VCell biomodel
        File sbmlFile = File.createTempFile("temp", ".xml");
        sbmlFile.deleteOnExit();
        XmlUtil.writeXMLStringToFile(modifiedSbmlStr, sbmlFile.getAbsolutePath(), true);
        org.vcell.sbml.vcell.SBMLImporter sbmlImporter = new SBMLImporter(sbmlFile.getAbsolutePath(), logger, false);
        BioModel bioModel = sbmlImporter.getBioModel();
        // enforce 'cleaner looking' units on vc biomodel (the process of adding unit defintion to sbml model messes up the units, though they are correct units (eg., 1e-6m for um).
        BioModel modifiedBiomodel = ModelUnitConverter.createBioModelWithNewUnitSystem(bioModel, forcedModelUnitSystem);
        // convert any reaction that has GeneralLumpedKinetics to GeneralKinetics
        for (ReactionStep rs : modifiedBiomodel.getModel().getReactionSteps()) {
            Kinetics kinetics = rs.getKinetics();
            if (kinetics instanceof LumpedKinetics) {
                rs.setKinetics(DistributedKinetics.toDistributedKinetics((LumpedKinetics) kinetics));
            }
        }
        // convert biomodel to vcml string
        String vcmlString = XmlHelper.bioModelToXML(modifiedBiomodel);
        ExternalDocInfo externalDocInfo = new ExternalDocInfo(vcmlString);
        if (externalDocInfo != null) {
            getRequestManager().openDocument(externalDocInfo, this, true);
        }
    } catch (Exception e) {
        e.printStackTrace(System.out);
        throw new RuntimeException("Cound not convert BNG sbml string to VCell biomodel : ", e);
    }
}
Also used : SBMLImporter(org.vcell.sbml.vcell.SBMLImporter) LumpedKinetics(cbit.vcell.model.LumpedKinetics) UnitSystemSelectionPanel(cbit.vcell.client.desktop.biomodel.UnitSystemSelectionPanel) VCLogger(cbit.util.xml.VCLogger) SBMLImporter(org.vcell.sbml.vcell.SBMLImporter) IOException(java.io.IOException) UserCancelException(org.vcell.util.UserCancelException) ExternalDocInfo(cbit.vcell.xml.ExternalDocInfo) BioModel(cbit.vcell.biomodel.BioModel) ReactionStep(cbit.vcell.model.ReactionStep) DistributedKinetics(cbit.vcell.model.DistributedKinetics) LumpedKinetics(cbit.vcell.model.LumpedKinetics) Kinetics(cbit.vcell.model.Kinetics) File(java.io.File) VCLogger(cbit.util.xml.VCLogger) ModelUnitSystem(cbit.vcell.model.ModelUnitSystem)

Example 15 with Kinetics

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

the class BioCartoonTool method pasteReactionSteps0.

/**
 * pasteReactionSteps0 : does the actual pasting. First called with a cloned model, to track issues. If user still wants to proceed, the paste
 * is performed on the original model.
 *
 * Insert the method's description here.
 * Creation date: (5/10/2003 3:55:25 PM)
 * @param pasteToModel cbit.vcell.model.Model
 * @param pasteToStructure cbit.vcell.model.Structure
 * @param bNew boolean
 */
private static final PasteHelper pasteReactionSteps0(HashMap<String, HashMap<ReactionParticipant, Structure>> rxPartMapStructure, Component parent, IssueContext issueContext, ReactionStep[] copyFromRxSteps, Model pasteToModel, Structure pasteToStructure, boolean bNew, /*boolean bUseDBSpecies,*/
UserResolvedRxElements userResolvedRxElements) throws Exception {
    HashMap<BioModelEntityObject, BioModelEntityObject> reactionsAndSpeciesContexts = new HashMap<>();
    if (copyFromRxSteps == null || copyFromRxSteps.length == 0 || pasteToModel == null || pasteToStructure == null) {
        throw new IllegalArgumentException("CartoonTool.pasteReactionSteps Error " + (copyFromRxSteps == null || copyFromRxSteps.length == 0 ? "reactionStepsArr empty " : "") + (pasteToModel == null ? "model is null " : "") + (pasteToStructure == null ? "struct is null " : ""));
    }
    if (!pasteToModel.contains(pasteToStructure)) {
        throw new IllegalArgumentException("CartoonTool.pasteReactionSteps model " + pasteToModel.getName() + " does not contain structure " + pasteToStructure.getName());
    }
    // Check PasteToModel has preferred targets if set
    if (userResolvedRxElements != null) {
        for (int i = 0; i < userResolvedRxElements.toSpeciesArr.length; i++) {
            if (userResolvedRxElements.toSpeciesArr[i] != null) {
                if (!pasteToModel.contains(userResolvedRxElements.toSpeciesArr[i])) {
                    throw new RuntimeException("PasteToModel does not contain preferred Species " + userResolvedRxElements.toSpeciesArr[i]);
                }
            }
            if (userResolvedRxElements.toStructureArr[i] != null) {
                if (!pasteToModel.contains(userResolvedRxElements.toStructureArr[i])) {
                    throw new RuntimeException("PasteToModel does not contain preferred Structure " + userResolvedRxElements.toStructureArr[i]);
                }
            }
        }
    }
    int counter = 0;
    Structure currentStruct = pasteToStructure;
    String copiedStructName = copyFromRxSteps[counter].getStructure().getName();
    StructureTopology structTopology = (copyFromRxSteps[counter].getModel() == null ? pasteToModel.getStructureTopology() : copyFromRxSteps[counter].getModel().getStructureTopology());
    IdentityHashMap<Species, Species> speciesHash = new IdentityHashMap<Species, Species>();
    IdentityHashMap<SpeciesContext, SpeciesContext> speciesContextHash = new IdentityHashMap<SpeciesContext, SpeciesContext>();
    Vector<Issue> issueVector = new Vector<Issue>();
    do {
        // create a new reaction, instead of cloning the old one; set struc
        ReactionStep copyFromReactionStep = copyFromRxSteps[counter];
        String newName = copyFromReactionStep.getName();
        while (pasteToModel.getReactionStep(newName) != null) {
            newName = org.vcell.util.TokenMangler.getNextEnumeratedToken(newName);
        }
        ReactionStep newReactionStep = null;
        if (copyFromReactionStep instanceof SimpleReaction) {
            newReactionStep = new SimpleReaction(pasteToModel, currentStruct, newName, copyFromReactionStep.isReversible());
        } else if (copyFromReactionStep instanceof FluxReaction && currentStruct instanceof Membrane) {
            newReactionStep = new FluxReaction(pasteToModel, (Membrane) currentStruct, null, newName, copyFromReactionStep.isReversible());
        }
        pasteToModel.addReactionStep(newReactionStep);
        reactionsAndSpeciesContexts.put(newReactionStep, copyFromReactionStep);
        Structure toRxnStruct = newReactionStep.getStructure();
        Structure fromRxnStruct = copyFromReactionStep.getStructure();
        if (!fromRxnStruct.getClass().equals(pasteToStructure.getClass())) {
            throw new Exception("Cannot copy reaction from " + fromRxnStruct.getTypeName() + " to " + pasteToStructure.getTypeName() + ".");
        }
        // add appropriate reactionParticipants to newReactionStep.
        StructureTopology toStructureTopology = pasteToModel.getStructureTopology();
        ReactionParticipant[] copyFromRxParticipantArr = copyFromReactionStep.getReactionParticipants();
        if (rxPartMapStructure == null) {
            // null during 'issues' trial
            rxPartMapStructure = new HashMap<String, HashMap<ReactionParticipant, Structure>>();
        }
        if (rxPartMapStructure.get(copyFromReactionStep.getName()) == null) {
            // Ask user to assign species to compartments for each reaction to be pasted
            rxPartMapStructure.put(copyFromReactionStep.getName(), askUserResolveMembraneConnections(parent, pasteToModel.getStructures(), currentStruct, fromRxnStruct, toRxnStruct, copyFromRxParticipantArr, toStructureTopology, structTopology));
        }
        for (int i = 0; i < copyFromRxParticipantArr.length; i += 1) {
            Structure pasteToStruct = currentStruct;
            // if(toRxnStruct instanceof Membrane){
            pasteToStruct = rxPartMapStructure.get(copyFromReactionStep.getName()).get(copyFromRxParticipantArr[i]);
            // if(pasteToStruct == null){
            // for(ReactionParticipant myRXPart:rxPartMapStructure.get(copyFromReactionStep.getName()).keySet()){
            // if(myRXPart.getSpeciesContext().getName().equals(copyFromRxParticipantArr[i].getSpeciesContext().getName())){
            // pasteToStruct = rxPartMapStructure.get(copyFromReactionStep.getName()).get(myRXPart);
            // break;
            // }
            // }
            // }
            // }
            // this adds the speciesContexts and species (if any) to the model)
            String rootSC = ReactionCartoonTool.speciesContextRootFinder(copyFromRxParticipantArr[i].getSpeciesContext());
            SpeciesContext newSc = null;
            SpeciesContext[] matchSC = pasteToModel.getSpeciesContexts();
            for (int j = 0; matchSC != null && j < matchSC.length; j++) {
                String matchRoot = ReactionCartoonTool.speciesContextRootFinder(matchSC[j]);
                if (matchRoot != null && matchRoot.equals(rootSC) && matchSC[j].getStructure().getName().equals(pasteToStruct.getName())) {
                    newSc = matchSC[j];
                    reactionsAndSpeciesContexts.put(newSc, matchSC[j]);
                    break;
                }
            }
            if (newSc == null) {
                newSc = pasteSpecies(parent, copyFromRxParticipantArr[i].getSpecies(), rootSC, pasteToModel, pasteToStruct, bNew, /*bUseDBSpecies,*/
                speciesHash, UserResolvedRxElements.getPreferredReactionElement(userResolvedRxElements, copyFromRxParticipantArr[i]));
                reactionsAndSpeciesContexts.put(newSc, copyFromRxParticipantArr[i].getSpeciesContext());
            }
            // record the old-new speciesContexts (reactionparticipants) in the IdHashMap, this is useful, esp for 'Paste new', while replacing proxyparams.
            SpeciesContext oldSc = copyFromRxParticipantArr[i].getSpeciesContext();
            if (speciesContextHash.get(oldSc) == null) {
                speciesContextHash.put(oldSc, newSc);
            }
            if (copyFromRxParticipantArr[i] instanceof Reactant) {
                newReactionStep.addReactionParticipant(new Reactant(null, newReactionStep, newSc, copyFromRxParticipantArr[i].getStoichiometry()));
            } else if (copyFromRxParticipantArr[i] instanceof Product) {
                newReactionStep.addReactionParticipant(new Product(null, newReactionStep, newSc, copyFromRxParticipantArr[i].getStoichiometry()));
            } else if (copyFromRxParticipantArr[i] instanceof Catalyst) {
                newReactionStep.addCatalyst(newSc);
            }
        }
        // // If 'newReactionStep' is a fluxRxn, set its fluxCarrier
        // if (newReactionStep instanceof FluxReaction) {
        // if (fluxCarrierSp != null) {
        // ((FluxReaction)newReactionStep).setFluxCarrier(fluxCarrierSp, pasteToModel);
        // } else {
        // throw new RuntimeException("Could not set FluxCarrier species for the flux reaction to be pasted");
        // }
        // }
        // For each kinetic parameter expression for new kinetics, replace the proxyParams from old kinetics with proxyParams in new kinetics
        // i.e., if the proxyParams are speciesContexts, replace with corresponding speciesContext in newReactionStep;
        // if the proxyParams are structureSizes or MembraneVoltages, replace with corresponding structure quantity in newReactionStep
        Kinetics oldKinetics = copyFromReactionStep.getKinetics();
        KineticsParameter[] oldKps = oldKinetics.getKineticsParameters();
        KineticsProxyParameter[] oldKprps = oldKinetics.getProxyParameters();
        Hashtable<String, Expression> paramExprHash = new Hashtable<String, Expression>();
        for (int i = 0; oldKps != null && i < oldKps.length; i++) {
            Expression newExpression = new Expression(oldKps[i].getExpression());
            for (int j = 0; oldKprps != null && j < oldKprps.length; j++) {
                // check if kinetic proxy parameter is in kinetic parameter expression
                if (newExpression.hasSymbol(oldKprps[j].getName())) {
                    SymbolTableEntry ste = oldKprps[j].getTarget();
                    Model pasteFromModel = copyFromReactionStep.getModel();
                    if (ste instanceof SpeciesContext) {
                        // if newRxnStruct is a feature/membrane, get matching spContexts from old reaction and replace them in new rate expr.
                        SpeciesContext oldSC = (SpeciesContext) ste;
                        SpeciesContext newSC = speciesContextHash.get(oldSC);
                        if (newSC == null) {
                            // check if oldSc is present in paste-model; if not, add it.
                            if (!pasteToModel.equals(pasteFromModel)) {
                                if (pasteToModel.getSpeciesContext(oldSC.getName()) == null) {
                                    // if paste-model has oldSc struct, paste it there,
                                    Structure newSCStruct = pasteToModel.getStructure(oldSC.getStructure().getName());
                                    if (newSCStruct != null) {
                                        newSC = pasteSpecies(parent, oldSC.getSpecies(), null, pasteToModel, newSCStruct, bNew, /*bUseDBSpecies,*/
                                        speciesHash, UserResolvedRxElements.getPreferredReactionElement(userResolvedRxElements, oldSC));
                                        speciesContextHash.put(oldSC, newSC);
                                    } else {
                                        // oldStruct wasn't found in paste-model, paste it in newRxnStruct and add warning to issues list
                                        newSC = pasteSpecies(parent, oldSC.getSpecies(), null, pasteToModel, toRxnStruct, bNew, /*bUseDBSpecies,*/
                                        speciesHash, UserResolvedRxElements.getPreferredReactionElement(userResolvedRxElements, oldSC));
                                        speciesContextHash.put(oldSC, newSC);
                                        Issue issue = new Issue(oldSC, issueContext, IssueCategory.CopyPaste, "SpeciesContext '" + oldSC.getSpecies().getCommonName() + "' was not found in compartment '" + oldSC.getStructure().getName() + "' in the model; the species was added to the compartment '" + toRxnStruct.getName() + "' where the reaction was pasted.", Issue.SEVERITY_WARNING);
                                        issueVector.add(issue);
                                    }
                                }
                            }
                        // if models are the same and newSc is null, then oldSc is not a rxnParticipant. Leave it as is in the expr.
                        }
                        if (newSC != null) {
                            reactionsAndSpeciesContexts.put(newSC, oldSC);
                            newExpression.substituteInPlace(new Expression(ste.getName()), new Expression(newSC.getName()));
                        }
                    // SpeciesContext sc = null;
                    // Species newSp = model.getSpecies(oldSc.getSpecies().getCommonName());
                    // if  (oldSc.getStructure() == (oldRxnStruct)) {
                    // sc = model.getSpeciesContext(newSp, newRxnStruct);
                    // } else {
                    // if (newRxnStruct instanceof Membrane) {
                    // // for a membrane, we need to make sure that inside-outside spContexts used are appropriately replaced.
                    // if (oldSc.getStructure() == ((Membrane)oldRxnStruct).getOutsideFeature()) {
                    // // old speciesContext is outside (old) membrane, new spContext should be outside new membrane
                    // sc = model.getSpeciesContext(newSp, ((Membrane)newRxnStruct).getOutsideFeature());
                    // } else if (oldSc.getStructure() == ((Membrane)oldRxnStruct).getInsideFeature()) {
                    // // old speciesContext is inside (old) membrane, new spContext should be inside new membrane
                    // sc = model.getSpeciesContext(newSp, ((Membrane)newRxnStruct).getInsideFeature());
                    // }
                    // }
                    // }
                    // if (sc != null) {
                    // newExpression.substituteInPlace(new Expression(ste.getName()), new Expression(sc.getName()));
                    // }
                    } else if (ste instanceof StructureSize) {
                        Structure str = ((StructureSize) ste).getStructure();
                        // if the structure size used is same as the structure in which the reaction is present, change the structSize to appropriate new struct
                        if (str.compareEqual(fromRxnStruct)) {
                            newExpression.substituteInPlace(new Expression(ste.getName()), new Expression(toRxnStruct.getStructureSize().getName()));
                        } else {
                            if (fromRxnStruct instanceof Membrane) {
                                if (str.equals(structTopology.getOutsideFeature((Membrane) fromRxnStruct))) {
                                    newExpression.substituteInPlace(new Expression(ste.getName()), new Expression(structTopology.getOutsideFeature((Membrane) toRxnStruct).getStructureSize().getName()));
                                } else if (str.equals(structTopology.getInsideFeature((Membrane) fromRxnStruct))) {
                                    newExpression.substituteInPlace(new Expression(ste.getName()), new Expression(structTopology.getInsideFeature((Membrane) toRxnStruct).getStructureSize().getName()));
                                }
                            }
                        }
                    } else if (ste instanceof MembraneVoltage) {
                        Membrane membr = ((MembraneVoltage) ste).getMembrane();
                        // if the MembraneVoltage used is same as that of the membrane in which the reaction is present, change the MemVoltage
                        if ((fromRxnStruct instanceof Membrane) && (membr.compareEqual(fromRxnStruct))) {
                            newExpression.substituteInPlace(new Expression(ste.getName()), new Expression(((Membrane) toRxnStruct).getMembraneVoltage().getName()));
                        }
                    } else if (ste instanceof ModelParameter) {
                        // see if model has this global parameter (if rxn is being pasted into another model, it won't)
                        if (!pasteToModel.equals(pasteFromModel)) {
                            ModelParameter oldMp = (ModelParameter) ste;
                            ModelParameter mp = pasteToModel.getModelParameter(oldMp.getName());
                            boolean bNonNumeric = false;
                            String newMpName = oldMp.getName();
                            if (mp != null) {
                                // new model has a model parameter with same name - are they the same param?
                                if (!mp.getExpression().equals(oldMp.getExpression())) {
                                    // no, they are not the same param, so mangle the 'ste' name and add as global in the other model
                                    while (pasteToModel.getModelParameter(newMpName) != null) {
                                        newMpName = TokenMangler.getNextEnumeratedToken(newMpName);
                                    }
                                    // if expression if numeric, add it as such. If not, set it to 0.0 and add it as global
                                    Expression exp = oldMp.getExpression();
                                    if (!exp.flatten().isNumeric()) {
                                        exp = new Expression(0.0);
                                        bNonNumeric = true;
                                    }
                                    ModelParameter newMp = pasteToModel.new ModelParameter(newMpName, exp, Model.ROLE_UserDefined, oldMp.getUnitDefinition());
                                    String annotation = "Copied from model : " + pasteFromModel.getNameScope();
                                    newMp.setModelParameterAnnotation(annotation);
                                    pasteToModel.addModelParameter(newMp);
                                    // if global param name had to be changed, make sure newExpr is updated as well.
                                    if (!newMpName.equals(oldMp.getName())) {
                                        newExpression.substituteInPlace(new Expression(oldMp.getName()), new Expression(newMpName));
                                    }
                                }
                            } else {
                                // no global param with same name was found in other model, so add it to other model.
                                // if expression if numeric, add it as such. If not, set it to 0.0 and add it as global
                                Expression exp = oldMp.getExpression();
                                if (!exp.flatten().isNumeric()) {
                                    exp = new Expression(0.0);
                                    bNonNumeric = true;
                                }
                                ModelParameter newMp = pasteToModel.new ModelParameter(newMpName, exp, Model.ROLE_UserDefined, oldMp.getUnitDefinition());
                                String annotation = "Copied from model : " + pasteFromModel.getNameScope();
                                newMp.setModelParameterAnnotation(annotation);
                                pasteToModel.addModelParameter(newMp);
                            }
                            // if a non-numeric parameter was encountered in the old model, it was added as a numeric (0.0), warn user of change.
                            if (bNonNumeric) {
                                Issue issue = new Issue(oldMp, issueContext, IssueCategory.CopyPaste, "Global parameter '" + oldMp.getName() + "' was non-numeric; it has been added " + "as global parameter '" + newMpName + "' in the new model with value = 0.0. " + "Please update its value, if required, before using it.", Issue.SEVERITY_WARNING);
                                issueVector.add(issue);
                            }
                        }
                    }
                }
            // end - if newExpr.hasSymbol(ProxyParam)
            }
            // now if store <param names, new expression> in hashTable
            if (paramExprHash.get(oldKps[i].getName()) == null) {
                paramExprHash.put(oldKps[i].getName(), newExpression);
            }
        }
        // end for - oldKps (old kinetic parameters)
        // use this new expression to generate 'vcml' for the (new) kinetics (easier way to transfer all kinetic parameters)
        String newKineticsStr = oldKinetics.writeTokensWithReplacingProxyParams(paramExprHash);
        // convert the kinetics 'vcml' to tokens.
        CommentStringTokenizer kineticsTokens = new CommentStringTokenizer(newKineticsStr);
        // skip the first token;
        kineticsTokens.nextToken();
        // second token is the kinetic type; use this to create a dummy kinetics
        String kineticType = kineticsTokens.nextToken();
        Kinetics newkinetics = KineticsDescription.fromVCMLKineticsName(kineticType).createKinetics(newReactionStep);
        // use the remaining tokens to construct the new kinetics
        newkinetics.fromTokens(newKineticsStr);
        // bind newkinetics to newReactionStep and add it to newReactionStep
        newkinetics.bind(newReactionStep);
        newReactionStep.setKinetics(newkinetics);
        counter += 1;
        if (counter == copyFromRxSteps.length) {
            break;
        }
        if (!copiedStructName.equals(fromRxnStruct.getName())) {
            if (currentStruct instanceof Feature) {
                currentStruct = structTopology.getMembrane((Feature) currentStruct);
            } else if (currentStruct instanceof Membrane) {
                currentStruct = structTopology.getInsideFeature((Membrane) currentStruct);
            }
        }
        copiedStructName = fromRxnStruct.getName();
    } while (true);
    return new PasteHelper(issueVector, rxPartMapStructure, reactionsAndSpeciesContexts);
}
Also used : Issue(org.vcell.util.Issue) IdentityHashMap(java.util.IdentityHashMap) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) IdentityHashMap(java.util.IdentityHashMap) Product(cbit.vcell.model.Product) FluxReaction(cbit.vcell.model.FluxReaction) SpeciesContext(cbit.vcell.model.SpeciesContext) Reactant(cbit.vcell.model.Reactant) Feature(cbit.vcell.model.Feature) SymbolTableEntry(cbit.vcell.parser.SymbolTableEntry) KineticsParameter(cbit.vcell.model.Kinetics.KineticsParameter) Membrane(cbit.vcell.model.Membrane) Structure(cbit.vcell.model.Structure) Species(cbit.vcell.model.Species) Vector(java.util.Vector) SimpleReaction(cbit.vcell.model.SimpleReaction) KineticsProxyParameter(cbit.vcell.model.Kinetics.KineticsProxyParameter) StructureTopology(cbit.vcell.model.Model.StructureTopology) Hashtable(java.util.Hashtable) BioModelEntityObject(cbit.vcell.model.BioModelEntityObject) StructureSize(cbit.vcell.model.Structure.StructureSize) PropertyVetoException(java.beans.PropertyVetoException) ExpressionBindingException(cbit.vcell.parser.ExpressionBindingException) ModelException(cbit.vcell.model.ModelException) UserCancelException(org.vcell.util.UserCancelException) ModelParameter(cbit.vcell.model.Model.ModelParameter) Expression(cbit.vcell.parser.Expression) MembraneVoltage(cbit.vcell.model.Membrane.MembraneVoltage) ReactionStep(cbit.vcell.model.ReactionStep) Model(cbit.vcell.model.Model) CommentStringTokenizer(org.vcell.util.CommentStringTokenizer) Kinetics(cbit.vcell.model.Kinetics) ReactionParticipant(cbit.vcell.model.ReactionParticipant) Catalyst(cbit.vcell.model.Catalyst)

Aggregations

Kinetics (cbit.vcell.model.Kinetics)31 KineticsParameter (cbit.vcell.model.Kinetics.KineticsParameter)21 ReactionStep (cbit.vcell.model.ReactionStep)17 Expression (cbit.vcell.parser.Expression)16 ModelParameter (cbit.vcell.model.Model.ModelParameter)11 ExpressionException (cbit.vcell.parser.ExpressionException)11 ReactionParticipant (cbit.vcell.model.ReactionParticipant)10 SpeciesContext (cbit.vcell.model.SpeciesContext)10 MassActionKinetics (cbit.vcell.model.MassActionKinetics)9 ModelUnitSystem (cbit.vcell.model.ModelUnitSystem)9 SimpleReaction (cbit.vcell.model.SimpleReaction)9 PropertyVetoException (java.beans.PropertyVetoException)9 LumpedKinetics (cbit.vcell.model.LumpedKinetics)8 VCUnitDefinition (cbit.vcell.units.VCUnitDefinition)8 Model (cbit.vcell.model.Model)7 Parameter (cbit.vcell.model.Parameter)7 Product (cbit.vcell.model.Product)7 Reactant (cbit.vcell.model.Reactant)7 FluxReaction (cbit.vcell.model.FluxReaction)6 StructureMapping (cbit.vcell.mapping.StructureMapping)5