Search in sources :

Example 6 with MathMapping

use of cbit.vcell.mapping.MathMapping 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 7 with MathMapping

use of cbit.vcell.mapping.MathMapping in project vcell by virtualcell.

the class OptimizationService method updateMath.

private static void updateMath(SimulationContext simulationContext, final NetworkGenerationRequirements networkGenerationRequirements) throws Exception {
    Geometry geometry = simulationContext.getGeometry();
    if (geometry.getDimension() > 0 && geometry.getGeometrySurfaceDescription().getGeometricRegions() == null) {
        geometry.getGeometrySurfaceDescription().updateAll();
    }
    simulationContext.checkValidity();
    MathMapping mathMapping = simulationContext.createNewMathMapping(callback, networkGenerationRequirements);
    MathDescription mathDesc = mathMapping.getMathDescription(callback);
    callback.setProgressFraction(1.0f / 3.0f * 2.0f);
    if (mathDesc != null) {
        simulationContext.setMathDescription(mathDesc);
    }
}
Also used : Geometry(cbit.vcell.geometry.Geometry) MathDescription(cbit.vcell.math.MathDescription) MathMapping(cbit.vcell.mapping.MathMapping)

Example 8 with MathMapping

use of cbit.vcell.mapping.MathMapping in project vcell by virtualcell.

the class Generate2DExpModelOpAbstract method generateModel.

public final GeneratedModelResults generateModel(double deltaX, double bleachRadius, double cellRadius, double bleachDuration, double bleachRate, double postbleachDelay, double postbleachDuration, double psfSigma, double outputTimeStep, double primaryDiffusionRate, double primaryFraction, double bleachMonitorRate, double secondaryDiffusionRate, double secondaryFraction, String extracellularName, String cytosolName, Context context) throws PropertyVetoException, ExpressionException, GeometryException, ImageException, ModelException, MappingException, MathException, MatrixException {
    double domainSize = 2.2 * cellRadius;
    Extent extent = new Extent(domainSize, domainSize, 1.0);
    Origin origin = new Origin(-extent.getX() / 2.0, -extent.getY() / 2.0, -extent.getZ() / 2.0);
    String EXTRACELLULAR_NAME = extracellularName;
    String CYTOSOL_NAME = cytosolName;
    AnalyticSubVolume cytosolSubVolume = new AnalyticSubVolume(CYTOSOL_NAME, new Expression("pow(x,2)+pow(y,2)<pow(" + cellRadius + ",2)"));
    AnalyticSubVolume extracellularSubVolume = new AnalyticSubVolume(EXTRACELLULAR_NAME, new Expression(1.0));
    Geometry geometry = new Geometry("geometry", 2);
    geometry.getGeometrySpec().setExtent(extent);
    geometry.getGeometrySpec().setOrigin(origin);
    geometry.getGeometrySpec().addSubVolume(extracellularSubVolume);
    geometry.getGeometrySpec().addSubVolume(cytosolSubVolume, true);
    geometry.getGeometrySurfaceDescription().updateAll();
    BioModel bioModel = new BioModel(null);
    bioModel.setName("unnamed");
    Model model = new Model("model");
    bioModel.setModel(model);
    model.addFeature(EXTRACELLULAR_NAME);
    Feature extracellular = (Feature) model.getStructure(EXTRACELLULAR_NAME);
    model.addFeature(CYTOSOL_NAME);
    Feature cytosol = (Feature) model.getStructure(CYTOSOL_NAME);
    SpeciesContext immobileSC = model.createSpeciesContext(cytosol);
    SpeciesContext primarySC = model.createSpeciesContext(cytosol);
    SpeciesContext secondarySC = model.createSpeciesContext(cytosol);
    // 
    // common bleaching rate for all species
    // 
    double bleachStart = 10 * outputTimeStep - bleachDuration - postbleachDelay;
    double bleachEnd = bleachStart + bleachDuration;
    Expression bleachRateExp = createBleachExpression(bleachRadius, bleachRate, bleachMonitorRate, bleachStart, bleachEnd);
    {
        SimpleReaction immobileBWM = model.createSimpleReaction(cytosol);
        GeneralKinetics immobileBWMKinetics = new GeneralKinetics(immobileBWM);
        immobileBWM.setKinetics(immobileBWMKinetics);
        immobileBWM.addReactant(immobileSC, 1);
        immobileBWMKinetics.getReactionRateParameter().setExpression(Expression.mult(bleachRateExp, new Expression(immobileSC.getName())));
    }
    {
        SimpleReaction primaryBWM = model.createSimpleReaction(cytosol);
        GeneralKinetics primaryBWMKinetics = new GeneralKinetics(primaryBWM);
        primaryBWM.setKinetics(primaryBWMKinetics);
        primaryBWM.addReactant(primarySC, 1);
        primaryBWMKinetics.getReactionRateParameter().setExpression(Expression.mult(bleachRateExp, new Expression(primarySC.getName())));
    }
    {
        SimpleReaction secondaryBWM = model.createSimpleReaction(cytosol);
        GeneralKinetics secondaryBWMKinetics = new GeneralKinetics(secondaryBWM);
        secondaryBWM.setKinetics(secondaryBWMKinetics);
        secondaryBWM.addReactant(secondarySC, 1);
        secondaryBWMKinetics.getReactionRateParameter().setExpression(Expression.mult(bleachRateExp, new Expression(secondarySC.getName())));
    }
    // create simulation context
    SimulationContext simContext = bioModel.addNewSimulationContext("simContext", SimulationContext.Application.NETWORK_DETERMINISTIC);
    simContext.setGeometry(geometry);
    FeatureMapping cytosolFeatureMapping = (FeatureMapping) simContext.getGeometryContext().getStructureMapping(cytosol);
    FeatureMapping extracellularFeatureMapping = (FeatureMapping) simContext.getGeometryContext().getStructureMapping(extracellular);
    SubVolume cytSubVolume = geometry.getGeometrySpec().getSubVolume(CYTOSOL_NAME);
    SubVolume exSubVolume = geometry.getGeometrySpec().getSubVolume(EXTRACELLULAR_NAME);
    // unused? SurfaceClass pmSurfaceClass = geometry.getGeometrySurfaceDescription().getSurfaceClass(exSubVolume, cytSubVolume);
    cytosolFeatureMapping.setGeometryClass(cytSubVolume);
    extracellularFeatureMapping.setGeometryClass(exSubVolume);
    cytosolFeatureMapping.getUnitSizeParameter().setExpression(new Expression(1.0));
    extracellularFeatureMapping.getUnitSizeParameter().setExpression(new Expression(1.0));
    double fixedFraction = 1.0 - primaryFraction - secondaryFraction;
    SpeciesContextSpec immobileSCS = simContext.getReactionContext().getSpeciesContextSpec(immobileSC);
    immobileSCS.getInitialConditionParameter().setExpression(new Expression(fixedFraction));
    immobileSCS.getDiffusionParameter().setExpression(new Expression(0.0));
    SpeciesContextSpec primarySCS = simContext.getReactionContext().getSpeciesContextSpec(primarySC);
    primarySCS.getInitialConditionParameter().setExpression(new Expression(primaryFraction));
    primarySCS.getDiffusionParameter().setExpression(new Expression(primaryDiffusionRate));
    SpeciesContextSpec secondarySCS = simContext.getReactionContext().getSpeciesContextSpec(secondarySC);
    secondarySCS.getInitialConditionParameter().setExpression(new Expression(secondaryFraction));
    secondarySCS.getDiffusionParameter().setExpression(new Expression(secondaryDiffusionRate));
    simContext.getMicroscopeMeasurement().addFluorescentSpecies(immobileSC);
    simContext.getMicroscopeMeasurement().addFluorescentSpecies(primarySC);
    simContext.getMicroscopeMeasurement().addFluorescentSpecies(secondarySC);
    simContext.getMicroscopeMeasurement().setConvolutionKernel(new GaussianConvolutionKernel(new Expression(psfSigma), new Expression(psfSigma)));
    MathMapping mathMapping = simContext.createNewMathMapping();
    MathDescription mathDesc = mathMapping.getMathDescription();
    simContext.setMathDescription(mathDesc);
    User owner = context.getDefaultOwner();
    int meshSize = (int) (domainSize / deltaX);
    if (meshSize % 2 == 0) {
        // want an odd-sized mesh in x and y ... so centered at the origin.
        meshSize = meshSize + 1;
    }
    TimeBounds timeBounds = new TimeBounds(0.0, postbleachDuration);
    // 
    // simulation to use for data generation (output time steps as recorded by the microscope)
    // 
    double bleachBlackoutBegin = bleachStart - postbleachDelay;
    double bleachBlackoutEnd = bleachEnd + postbleachDelay;
    // ArrayList<Double> times = new ArrayList<Double>();
    // double time = 0;
    // while (time<=timeBounds.getEndingTime()){
    // if (time<=bleachBlackoutBegin || time>bleachBlackoutEnd){
    // // postbleachDelay is the time it takes to switch the filters.
    // times.add(time);
    // }
    // time += outputTimeStep.getData();
    // }
    // double[] timeArray = new double[times.size()];
    // for (int i=0;i<timeArray.length;i++){
    // timeArray[i] = times.get(i);
    // }
    // OutputTimeSpec fakeDataSimOutputTimeSpec = new ExplicitOutputTimeSpec(timeArray);
    OutputTimeSpec fakeDataSimOutputTimeSpec = new UniformOutputTimeSpec(outputTimeStep);
    KeyValue fakeDataSimKey = context.createNewKeyValue();
    SimulationVersion fakeDataSimVersion = new SimulationVersion(fakeDataSimKey, "fakeDataSim", owner, new GroupAccessNone(), new KeyValue("0"), new BigDecimal(0), new Date(), VersionFlag.Current, "", null);
    Simulation fakeDataSim = new Simulation(fakeDataSimVersion, mathDesc);
    simContext.addSimulation(fakeDataSim);
    fakeDataSim.getSolverTaskDescription().setTimeBounds(timeBounds);
    fakeDataSim.getMeshSpecification().setSamplingSize(new ISize(meshSize, meshSize, 1));
    fakeDataSim.getSolverTaskDescription().setSolverDescription(SolverDescription.SundialsPDE);
    fakeDataSim.getSolverTaskDescription().setOutputTimeSpec(fakeDataSimOutputTimeSpec);
    // 
    // simulation to use for viewing the protocol (output time steps to understand the physics)
    // 
    KeyValue fullExperimentSimKey = context.createNewKeyValue();
    SimulationVersion fullExperimentSimVersion = new SimulationVersion(fullExperimentSimKey, "fullExperiment", owner, new GroupAccessNone(), new KeyValue("0"), new BigDecimal(0), new Date(), VersionFlag.Current, "", null);
    Simulation fullExperimentSim = new Simulation(fullExperimentSimVersion, mathDesc);
    simContext.addSimulation(fullExperimentSim);
    OutputTimeSpec fullExperimentOutputTimeSpec = new UniformOutputTimeSpec(outputTimeStep / 10.0);
    fullExperimentSim.getSolverTaskDescription().setTimeBounds(timeBounds);
    fullExperimentSim.getMeshSpecification().setSamplingSize(new ISize(meshSize, meshSize, 1));
    fullExperimentSim.getSolverTaskDescription().setSolverDescription(SolverDescription.SundialsPDE);
    fullExperimentSim.getSolverTaskDescription().setOutputTimeSpec(fullExperimentOutputTimeSpec);
    GeneratedModelResults results = new GeneratedModelResults();
    results.bioModel_2D = bioModel;
    results.simulation_2D = fakeDataSim;
    results.bleachBlackoutBeginTime = bleachBlackoutBegin;
    results.bleachBlackoutEndTime = bleachBlackoutEnd;
    return results;
}
Also used : Origin(org.vcell.util.Origin) User(org.vcell.util.document.User) KeyValue(org.vcell.util.document.KeyValue) Extent(org.vcell.util.Extent) MathDescription(cbit.vcell.math.MathDescription) ISize(org.vcell.util.ISize) SpeciesContext(cbit.vcell.model.SpeciesContext) GeneralKinetics(cbit.vcell.model.GeneralKinetics) SpeciesContextSpec(cbit.vcell.mapping.SpeciesContextSpec) Feature(cbit.vcell.model.Feature) TimeBounds(cbit.vcell.solver.TimeBounds) GroupAccessNone(org.vcell.util.document.GroupAccessNone) UniformOutputTimeSpec(cbit.vcell.solver.UniformOutputTimeSpec) OutputTimeSpec(cbit.vcell.solver.OutputTimeSpec) SimulationVersion(org.vcell.util.document.SimulationVersion) FeatureMapping(cbit.vcell.mapping.FeatureMapping) SubVolume(cbit.vcell.geometry.SubVolume) AnalyticSubVolume(cbit.vcell.geometry.AnalyticSubVolume) SimpleReaction(cbit.vcell.model.SimpleReaction) UniformOutputTimeSpec(cbit.vcell.solver.UniformOutputTimeSpec) SimulationContext(cbit.vcell.mapping.SimulationContext) GaussianConvolutionKernel(cbit.vcell.mapping.MicroscopeMeasurement.GaussianConvolutionKernel) BigDecimal(java.math.BigDecimal) Date(java.util.Date) Geometry(cbit.vcell.geometry.Geometry) Simulation(cbit.vcell.solver.Simulation) Expression(cbit.vcell.parser.Expression) BioModel(cbit.vcell.biomodel.BioModel) BioModel(cbit.vcell.biomodel.BioModel) Model(cbit.vcell.model.Model) MathMapping(cbit.vcell.mapping.MathMapping) AnalyticSubVolume(cbit.vcell.geometry.AnalyticSubVolume)

Example 9 with MathMapping

use of cbit.vcell.mapping.MathMapping in project vcell by virtualcell.

the class InitialConditionsPanel method jMenuItemPaste_ActionPerformed.

/**
 * Comment
 */
private void jMenuItemPaste_ActionPerformed(final java.awt.event.ActionEvent actionEvent) {
    final Vector<String> pasteDescriptionsV = new Vector<String>();
    final Vector<Expression> newExpressionsV = new Vector<Expression>();
    final Vector<SpeciesContextSpec.SpeciesContextSpecParameter> changedParametersV = new Vector<SpeciesContextSpec.SpeciesContextSpecParameter>();
    AsynchClientTask task1 = new AsynchClientTask("validating", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {

        @Override
        public void run(Hashtable<String, Object> hashTable) throws Exception {
            if (actionEvent.getSource() == getJMenuItemPaste() || actionEvent.getSource() == getJMenuItemPasteAll()) {
                Object pasteThis = VCellTransferable.getFromClipboard(VCellTransferable.OBJECT_FLAVOR);
                MathSymbolMapping msm = null;
                Exception mathMappingException = null;
                try {
                    MathMapping mm = null;
                    mm = getSimulationContext().createNewMathMapping();
                    msm = mm.getMathSymbolMapping();
                } catch (Exception e) {
                    mathMappingException = e;
                    e.printStackTrace(System.out);
                }
                int[] rows = null;
                if (actionEvent.getSource() == getJMenuItemPasteAll()) {
                    rows = new int[getScrollPaneTable().getRowCount()];
                    for (int i = 0; i < rows.length; i += 1) {
                        rows[i] = i;
                    }
                } else {
                    rows = getScrollPaneTable().getSelectedRows();
                }
                // 
                // Check paste
                // 
                StringBuffer errors = null;
                for (int i = 0; i < rows.length; i += 1) {
                    SpeciesContextSpec scs = tableModel.getValueAt(rows[i]);
                    try {
                        if (pasteThis instanceof VCellTransferable.ResolvedValuesSelection) {
                            VCellTransferable.ResolvedValuesSelection rvs = (VCellTransferable.ResolvedValuesSelection) pasteThis;
                            for (int j = 0; j < rvs.getPrimarySymbolTableEntries().length; j += 1) {
                                SpeciesContextSpec.SpeciesContextSpecParameter pasteDestination = null;
                                SpeciesContextSpec.SpeciesContextSpecParameter clipboardBiologicalParameter = null;
                                if (rvs.getPrimarySymbolTableEntries()[j] instanceof SpeciesContextSpec.SpeciesContextSpecParameter) {
                                    clipboardBiologicalParameter = (SpeciesContextSpec.SpeciesContextSpecParameter) rvs.getPrimarySymbolTableEntries()[j];
                                } else if (rvs.getAlternateSymbolTableEntries() != null && rvs.getAlternateSymbolTableEntries()[j] instanceof SpeciesContextSpec.SpeciesContextSpecParameter) {
                                    clipboardBiologicalParameter = (SpeciesContextSpec.SpeciesContextSpecParameter) rvs.getAlternateSymbolTableEntries()[j];
                                }
                                if (clipboardBiologicalParameter == null) {
                                    Variable pastedMathVariable = null;
                                    if (rvs.getPrimarySymbolTableEntries()[j] instanceof Variable) {
                                        pastedMathVariable = (Variable) rvs.getPrimarySymbolTableEntries()[j];
                                    } else if (rvs.getAlternateSymbolTableEntries() != null && rvs.getAlternateSymbolTableEntries()[j] instanceof Variable) {
                                        pastedMathVariable = (Variable) rvs.getAlternateSymbolTableEntries()[j];
                                    }
                                    if (pastedMathVariable != null) {
                                        if (msm == null) {
                                            throw mathMappingException;
                                        }
                                        Variable localMathVariable = msm.findVariableByName(pastedMathVariable.getName());
                                        if (localMathVariable == null) {
                                            // try if localMathVariable is a speciesContext init parameter
                                            String initSuffix = DiffEquMathMapping.MATH_FUNC_SUFFIX_SPECIES_INIT_CONC_UNIT_PREFIX + TokenMangler.fixTokenStrict(scs.getInitialConcentrationParameter().getUnitDefinition().getSymbol());
                                            localMathVariable = msm.findVariableByName(pastedMathVariable.getName() + initSuffix);
                                        }
                                        if (localMathVariable != null) {
                                            SymbolTableEntry[] localBiologicalSymbolArr = msm.getBiologicalSymbol(localMathVariable);
                                            for (int k = 0; k < localBiologicalSymbolArr.length; k += 1) {
                                                if (localBiologicalSymbolArr[k] instanceof SpeciesContext && scs.getSpeciesContext() == localBiologicalSymbolArr[k]) {
                                                    // need to change
                                                    pasteDestination = scs.getInitialConditionParameter();
                                                } else if (localBiologicalSymbolArr[k] instanceof SpeciesContextSpec.SpeciesContextSpecParameter) {
                                                    for (int l = 0; l < scs.getParameters().length; l += 1) {
                                                        if (scs.getParameters()[l] == localBiologicalSymbolArr[k]) {
                                                            pasteDestination = (SpeciesContextSpec.SpeciesContextSpecParameter) localBiologicalSymbolArr[k];
                                                            break;
                                                        }
                                                    }
                                                }
                                                if (pasteDestination != null) {
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                } else {
                                    for (int k = 0; k < scs.getParameters().length; k += 1) {
                                        SpeciesContextSpec.SpeciesContextSpecParameter scsp = (SpeciesContextSpec.SpeciesContextSpecParameter) scs.getParameters()[k];
                                        if (scsp.getRole() == clipboardBiologicalParameter.getRole() && scs.getSpeciesContext().compareEqual(((SpeciesContextSpec) clipboardBiologicalParameter.getNameScope().getScopedSymbolTable()).getSpeciesContext())) {
                                            pasteDestination = (SpeciesContextSpec.SpeciesContextSpecParameter) scsp;
                                        }
                                    }
                                }
                                if (pasteDestination != null) {
                                    changedParametersV.add(pasteDestination);
                                    newExpressionsV.add(rvs.getExpressionValues()[j]);
                                    pasteDescriptionsV.add(VCellCopyPasteHelper.formatPasteList(scs.getSpeciesContext().getName(), pasteDestination.getName(), pasteDestination.getExpression().infix(), rvs.getExpressionValues()[j].infix()));
                                }
                            }
                        }
                    } catch (Throwable e) {
                        if (errors == null) {
                            errors = new StringBuffer();
                        }
                        errors.append(scs.getSpeciesContext().getName() + " (" + e.getClass().getName() + ") " + e.getMessage() + "\n\n");
                    }
                }
                if (errors != null) {
                    throw new Exception(errors.toString());
                }
            }
        }
    };
    AsynchClientTask task2 = new AsynchClientTask("pasting", AsynchClientTask.TASKTYPE_SWING_BLOCKING) {

        @Override
        public void run(Hashtable<String, Object> hashTable) throws Exception {
            // Do paste
            if (pasteDescriptionsV.size() > 0) {
                String[] pasteDescriptionArr = new String[pasteDescriptionsV.size()];
                pasteDescriptionsV.copyInto(pasteDescriptionArr);
                SpeciesContextSpec.SpeciesContextSpecParameter[] changedParametersArr = new SpeciesContextSpec.SpeciesContextSpecParameter[changedParametersV.size()];
                changedParametersV.copyInto(changedParametersArr);
                Expression[] newExpressionsArr = new Expression[newExpressionsV.size()];
                newExpressionsV.copyInto(newExpressionsArr);
                VCellCopyPasteHelper.chooseApplyPaste(InitialConditionsPanel.this, pasteDescriptionArr, changedParametersArr, newExpressionsArr);
            } else {
                PopupGenerator.showInfoDialog(InitialConditionsPanel.this, "No paste items match the destination (no changes made).");
            }
        }
    };
    ClientTaskDispatcher.dispatch(this, new Hashtable<String, Object>(), new AsynchClientTask[] { task1, task2 });
}
Also used : AsynchClientTask(cbit.vcell.client.task.AsynchClientTask) Variable(cbit.vcell.math.Variable) VCellTransferable(cbit.vcell.desktop.VCellTransferable) SpeciesContext(cbit.vcell.model.SpeciesContext) SpeciesContextSpec(cbit.vcell.mapping.SpeciesContextSpec) SymbolTableEntry(cbit.vcell.parser.SymbolTableEntry) Vector(java.util.Vector) SpeciesContextSpecParameter(cbit.vcell.mapping.SpeciesContextSpec.SpeciesContextSpecParameter) SpeciesContextSpecParameter(cbit.vcell.mapping.SpeciesContextSpec.SpeciesContextSpecParameter) Hashtable(java.util.Hashtable) MathSymbolMapping(cbit.vcell.mapping.MathSymbolMapping) ScopedExpression(cbit.gui.ScopedExpression) Expression(cbit.vcell.parser.Expression) DiffEquMathMapping(cbit.vcell.mapping.DiffEquMathMapping) MathMapping(cbit.vcell.mapping.MathMapping)

Example 10 with MathMapping

use of cbit.vcell.mapping.MathMapping in project vcell by virtualcell.

the class ParameterMappingPanel method jMenuItemCopy_ActionPerformed.

/**
 * Comment
 */
private void jMenuItemCopy_ActionPerformed(java.awt.event.ActionEvent actionEvent) {
    if (actionEvent.getSource() == getJMenuItemCopy() || actionEvent.getSource() == getJMenuItemCopyAll()) {
        try {
            // 
            // Copy Optimization Parameters (Initial Guess or Solution)
            // 
            int[] rows = null;
            if (actionEvent.getSource() == getJMenuItemCopyAll()) {
                rows = new int[getScrollPaneTable().getRowCount()];
                for (int i = 0; i < rows.length; i += 1) {
                    rows[i] = i;
                }
            } else {
                rows = getScrollPaneTable().getSelectedRows();
            }
            SimulationContext sc = getParameterEstimationTask().getModelOptimizationSpec().getSimulationContext();
            MathSymbolMapping msm = null;
            try {
                MathMapping mm = sc.createNewMathMapping();
                msm = mm.getMathSymbolMapping();
            } catch (Exception e) {
                e.printStackTrace(System.out);
                DialogUtils.showWarningDialog(this, "current math not valid, some paste operations will be limited\n\nreason: " + e.getMessage());
            }
            boolean bInitialGuess = (getScrollPaneTable().getSelectedColumn() == ParameterMappingTableModel.COLUMN_CURRENTVALUE);
            ParameterMappingSpec[] parameterMappingSpecs = new ParameterMappingSpec[rows.length];
            java.util.Vector<SymbolTableEntry> primarySymbolTableEntriesV = new java.util.Vector<SymbolTableEntry>();
            java.util.Vector<SymbolTableEntry> alternateSymbolTableEntriesV = new java.util.Vector<SymbolTableEntry>();
            java.util.Vector<Expression> resolvedValuesV = new java.util.Vector<Expression>();
            // 
            // Create formatted string for text/spreadsheet pasting.
            // 
            StringBuffer sb = new StringBuffer();
            sb.append("\"Parameters for (Optimization Task)" + getParameterEstimationTask().getName() + " -> " + "(BioModel)" + getParameterEstimationTask().getModelOptimizationSpec().getSimulationContext().getBioModel().getName() + " -> " + "(App)" + getParameterEstimationTask().getModelOptimizationSpec().getSimulationContext().getName() + "\"\n");
            sb.append("\"Parameter Name\"\t\"" + (bInitialGuess ? "Initial Guess" : "Solution") + "\"\n");
            for (int i = 0; i < rows.length; i += 1) {
                ParameterMappingSpec pms = parameterMappingTableModel.getValueAt(rows[i]);
                parameterMappingSpecs[i] = pms;
                primarySymbolTableEntriesV.add(pms.getModelParameter());
                if (msm != null) {
                    alternateSymbolTableEntriesV.add(msm.getVariable(pms.getModelParameter()));
                } else {
                    alternateSymbolTableEntriesV.add(null);
                }
                Double resolvedValue = null;
                if (!bInitialGuess) {
                    resolvedValue = getParameterEstimationTask().getCurrentSolution(pms);
                }
                if (resolvedValue == null) {
                    resolvedValue = new Double(pms.getCurrent());
                }
                resolvedValuesV.add(new Expression(resolvedValue.doubleValue()));
                sb.append("\"" + parameterMappingSpecs[i].getModelParameter().getName() + "\"\t" + resolvedValue + "\n");
            }
            // 
            // Send to clipboard
            // 
            VCellTransferable.ResolvedValuesSelection rvs = new VCellTransferable.ResolvedValuesSelection((SymbolTableEntry[]) BeanUtils.getArray(primarySymbolTableEntriesV, SymbolTableEntry.class), (SymbolTableEntry[]) BeanUtils.getArray(alternateSymbolTableEntriesV, SymbolTableEntry.class), (Expression[]) BeanUtils.getArray(resolvedValuesV, Expression.class), sb.toString());
            VCellTransferable.sendToClipboard(rvs);
        } catch (Throwable e) {
            PopupGenerator.showErrorDialog(this, "ParameterMappingPanel copy failed.  " + e.getMessage(), e);
        }
    }
}
Also used : VCellTransferable(cbit.vcell.desktop.VCellTransferable) SimulationContext(cbit.vcell.mapping.SimulationContext) MathSymbolMapping(cbit.vcell.mapping.MathSymbolMapping) SymbolTableEntry(cbit.vcell.parser.SymbolTableEntry) Expression(cbit.vcell.parser.Expression) ParameterMappingSpec(cbit.vcell.modelopt.ParameterMappingSpec) MathMapping(cbit.vcell.mapping.MathMapping)

Aggregations

MathMapping (cbit.vcell.mapping.MathMapping)21 SimulationContext (cbit.vcell.mapping.SimulationContext)16 MathDescription (cbit.vcell.math.MathDescription)13 BioModel (cbit.vcell.biomodel.BioModel)12 Expression (cbit.vcell.parser.Expression)10 Simulation (cbit.vcell.solver.Simulation)10 Model (cbit.vcell.model.Model)8 KeyValue (org.vcell.util.document.KeyValue)8 TimeBounds (cbit.vcell.solver.TimeBounds)7 UniformOutputTimeSpec (cbit.vcell.solver.UniformOutputTimeSpec)7 Geometry (cbit.vcell.geometry.Geometry)6 MathSymbolMapping (cbit.vcell.mapping.MathSymbolMapping)6 SpeciesContextSpec (cbit.vcell.mapping.SpeciesContextSpec)6 SpeciesContext (cbit.vcell.model.SpeciesContext)6 ExpressionException (cbit.vcell.parser.ExpressionException)6 SimulationVersion (org.vcell.util.document.SimulationVersion)6 Variable (cbit.vcell.math.Variable)5 SymbolTableEntry (cbit.vcell.parser.SymbolTableEntry)5 IOException (java.io.IOException)5 ArrayList (java.util.ArrayList)5