Search in sources :

Example 16 with MathMapping

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

the class ClientRequestManager method createBioModelFromApplication.

public void createBioModelFromApplication(final BioModelWindowManager requester, final String name, final SimulationContext simContext) {
    if (simContext == null) {
        PopupGenerator.showErrorDialog(requester, "Selected Application is null, cannot generate corresponding bio model");
        return;
    }
    if (simContext.isRuleBased()) {
        createRuleBasedBioModelFromApplication(requester, name, simContext);
        return;
    }
    AsynchClientTask task1 = new AsynchClientTask("Creating BioModel from BioModel Application", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {

        @Override
        public void run(Hashtable<String, Object> hashTable) throws Exception {
            MathMappingCallback dummyCallback = new MathMappingCallback() {

                public void setProgressFraction(float percentDone) {
                }

                public void setMessage(String message) {
                }

                public boolean isInterrupted() {
                    return false;
                }
            };
            MathMapping transformedMathMapping = simContext.createNewMathMapping(dummyCallback, NetworkGenerationRequirements.ComputeFullStandardTimeout);
            BioModel newBioModel = new BioModel(null);
            SimulationContext transformedSimContext = transformedMathMapping.getTransformation().transformedSimContext;
            Model newModel = transformedSimContext.getModel();
            newBioModel.setModel(newModel);
            RbmModelContainer rbmmc = newModel.getRbmModelContainer();
            for (RbmObservable o : rbmmc.getObservableList()) {
                rbmmc.removeObservable(o);
            }
            for (ReactionRule r : rbmmc.getReactionRuleList()) {
                rbmmc.removeReactionRule(r);
            }
            for (ReactionStep rs : newModel.getReactionSteps()) {
                String oldName = rs.getName();
                if (oldName.startsWith("_reverse_")) {
                    String newName = newModel.getReactionName("rev", oldName.substring("_reverse_".length()));
                    rs.setName(newName);
                }
            }
            hashTable.put("newBioModel", newBioModel);
        }
    };
    AsynchClientTask task2 = new AsynchClientTask("Creating BioModel from BioModel Application", AsynchClientTask.TASKTYPE_SWING_BLOCKING) {

        @Override
        public void run(Hashtable<String, Object> hashTable) throws Exception {
            BioModel newBioModel = (BioModel) hashTable.get("newBioModel");
            DocumentWindowManager windowManager = createDocumentWindowManager(newBioModel);
            // if(simContext.getBioModel().getVersion() != null){
            // ((BioModelWindowManager)windowManager). setCopyFromBioModelAppVersionableTypeVersion(
            // new VersionableTypeVersion(VersionableType.BioModelMetaData, simContext.getBioModel().getVersion()));
            // }
            getMdiManager().createNewDocumentWindow(windowManager);
        }
    };
    ClientTaskDispatcher.dispatch(requester.getComponent(), new Hashtable<String, Object>(), new AsynchClientTask[] { task1, task2 }, false);
}
Also used : AsynchClientTask(cbit.vcell.client.task.AsynchClientTask) MathMappingCallback(cbit.vcell.mapping.SimulationContext.MathMappingCallback) ReactionRule(cbit.vcell.model.ReactionRule) Hashtable(java.util.Hashtable) RbmObservable(cbit.vcell.model.RbmObservable) SimulationContext(cbit.vcell.mapping.SimulationContext) RbmModelContainer(cbit.vcell.model.Model.RbmModelContainer) BioModel(cbit.vcell.biomodel.BioModel) ReactionStep(cbit.vcell.model.ReactionStep) MathMapping(cbit.vcell.mapping.MathMapping) ASTModel(org.vcell.model.bngl.ASTModel) MathModel(cbit.vcell.mathmodel.MathModel) Model(cbit.vcell.model.Model) ListSelectionModel(javax.swing.ListSelectionModel) BioModel(cbit.vcell.biomodel.BioModel) CSGObject(cbit.vcell.geometry.CSGObject)

Example 17 with MathMapping

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

the class ClientRequestManager method updateMath.

public static Collection<AsynchClientTask> updateMath(final Component requester, final SimulationContext simulationContext, final boolean bShowWarning, final NetworkGenerationRequirements networkGenerationRequirements) {
    ArrayList<AsynchClientTask> rval = new ArrayList<>();
    AsynchClientTask task1 = new AsynchClientTask("generating math", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {

        @Override
        public void run(Hashtable<String, Object> hashTable) throws Exception {
            Geometry geometry = simulationContext.getGeometry();
            if (geometry.getDimension() > 0 && geometry.getGeometrySurfaceDescription().getGeometricRegions() == null) {
                geometry.getGeometrySurfaceDescription().updateAll();
            }
            // Use differnt mathmapping for different applications (stoch or non-stoch)
            simulationContext.checkValidity();
            MathMappingCallback callback = new MathMappingCallbackTaskAdapter(getClientTaskStatusSupport());
            MathMapping mathMapping = simulationContext.createNewMathMapping(callback, networkGenerationRequirements);
            MathDescription mathDesc = mathMapping.getMathDescription(callback);
            callback.setProgressFraction(1.0f / 3.0f * 2.0f);
            hashTable.put("mathMapping", mathMapping);
            hashTable.put("mathDesc", mathDesc);
        }
    };
    rval.add(task1);
    AsynchClientTask task2 = new AsynchClientTask("formating math", AsynchClientTask.TASKTYPE_SWING_BLOCKING) {

        @Override
        public void run(Hashtable<String, Object> hashTable) throws Exception {
            MathDescription mathDesc = (MathDescription) hashTable.get("mathDesc");
            if (mathDesc != null) {
                simulationContext.setMathDescription(mathDesc);
            }
        }
    };
    rval.add(task2);
    if (bShowWarning) {
        AsynchClientTask task3 = new AsynchClientTask("showing issues", AsynchClientTask.TASKTYPE_SWING_BLOCKING) {

            @Override
            public void run(Hashtable<String, Object> hashTable) throws Exception {
                MathMapping mathMapping = (MathMapping) hashTable.get("mathMapping");
                MathDescription mathDesc = (MathDescription) hashTable.get("mathDesc");
                if (mathDesc != null) {
                    // 
                    // inform user if any issues
                    // 
                    Issue[] issues = mathMapping.getIssues();
                    if (issues != null && issues.length > 0) {
                        StringBuffer messageBuffer = new StringBuffer("Issues encountered during Math Generation:\n");
                        int issueCount = 0;
                        for (int i = 0; i < issues.length; i++) {
                            if (issues[i].getSeverity() == Issue.SEVERITY_ERROR || issues[i].getSeverity() == Issue.SEVERITY_WARNING) {
                                messageBuffer.append(issues[i].getCategory() + " " + issues[i].getSeverityName() + " : " + issues[i].getMessage() + "\n");
                                issueCount++;
                            }
                        }
                        if (issueCount > 0) {
                            PopupGenerator.showWarningDialog(requester, messageBuffer.toString(), new String[] { "OK" }, "OK");
                        }
                    }
                }
            }
        };
        rval.add(task3);
    }
    return rval;
}
Also used : AsynchClientTask(cbit.vcell.client.task.AsynchClientTask) MathMappingCallbackTaskAdapter(cbit.vcell.mapping.MathMappingCallbackTaskAdapter) Issue(org.vcell.util.Issue) MathMappingCallback(cbit.vcell.mapping.SimulationContext.MathMappingCallback) SetMathDescription(cbit.vcell.client.task.SetMathDescription) MathDescription(cbit.vcell.math.MathDescription) Hashtable(java.util.Hashtable) ArrayList(java.util.ArrayList) Geometry(cbit.vcell.geometry.Geometry) MathMapping(cbit.vcell.mapping.MathMapping)

Example 18 with MathMapping

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

the class FRAPStudy method createNewSimBioModel.

public static BioModel createNewSimBioModel(FRAPStudy sourceFrapStudy, Parameter[] params, TimeStep tStep, KeyValue simKey, User owner, int startingIndexForRecovery) throws Exception {
    if (owner == null) {
        throw new Exception("Owner is not defined");
    }
    ROI cellROI_2D = sourceFrapStudy.getFrapData().getRoi(FRAPData.VFRAP_ROI_ENUM.ROI_CELL.name());
    double df = params[FRAPModel.INDEX_PRIMARY_DIFF_RATE].getInitialGuess();
    double ff = params[FRAPModel.INDEX_PRIMARY_FRACTION].getInitialGuess();
    double bwmRate = params[FRAPModel.INDEX_BLEACH_MONITOR_RATE].getInitialGuess();
    double dc = 0;
    double fc = 0;
    double bs = 0;
    double onRate = 0;
    double offRate = 0;
    if (params.length == FRAPModel.NUM_MODEL_PARAMETERS_TWO_DIFF) {
        dc = params[FRAPModel.INDEX_SECONDARY_DIFF_RATE].getInitialGuess();
        fc = params[FRAPModel.INDEX_SECONDARY_FRACTION].getInitialGuess();
    } else if (params.length == FRAPModel.NUM_MODEL_PARAMETERS_BINDING) {
        dc = params[FRAPModel.INDEX_SECONDARY_DIFF_RATE].getInitialGuess();
        fc = params[FRAPModel.INDEX_SECONDARY_FRACTION].getInitialGuess();
        bs = params[FRAPModel.INDEX_BINDING_SITE_CONCENTRATION].getInitialGuess();
        onRate = params[FRAPModel.INDEX_ON_RATE].getInitialGuess();
        offRate = params[FRAPModel.INDEX_OFF_RATE].getInitialGuess();
    }
    // immobile fraction
    double fimm = 1 - ff - fc;
    if (fimm < FRAPOptimizationUtils.epsilon && fimm > (0 - FRAPOptimizationUtils.epsilon)) {
        fimm = 0;
    }
    if (fimm < (1 + FRAPOptimizationUtils.epsilon) && fimm > (1 - FRAPOptimizationUtils.epsilon)) {
        fimm = 1;
    }
    Extent extent = sourceFrapStudy.getFrapData().getImageDataset().getExtent();
    double[] timeStamps = sourceFrapStudy.getFrapData().getImageDataset().getImageTimeStamps();
    TimeBounds timeBounds = new TimeBounds(0.0, timeStamps[timeStamps.length - 1] - timeStamps[startingIndexForRecovery]);
    double timeStepVal = timeStamps[startingIndexForRecovery + 1] - timeStamps[startingIndexForRecovery];
    int numX = cellROI_2D.getRoiImages()[0].getNumX();
    int numY = cellROI_2D.getRoiImages()[0].getNumY();
    int numZ = cellROI_2D.getRoiImages().length;
    short[] shortPixels = cellROI_2D.getRoiImages()[0].getPixels();
    byte[] bytePixels = new byte[numX * numY * numZ];
    final byte EXTRACELLULAR_PIXVAL = 0;
    final byte CYTOSOL_PIXVAL = 1;
    for (int i = 0; i < bytePixels.length; i++) {
        if (shortPixels[i] != 0) {
            bytePixels[i] = CYTOSOL_PIXVAL;
        }
    }
    VCImage maskImage;
    try {
        maskImage = new VCImageUncompressed(null, bytePixels, extent, numX, numY, numZ);
    } catch (ImageException e) {
        e.printStackTrace();
        throw new RuntimeException("failed to create mask image for geometry");
    }
    Geometry geometry = new Geometry("geometry", maskImage);
    if (geometry.getGeometrySpec().getNumSubVolumes() != 2) {
        throw new Exception("Cell ROI has no ExtraCellular.");
    }
    int subVolume0PixVal = ((ImageSubVolume) geometry.getGeometrySpec().getSubVolume(0)).getPixelValue();
    geometry.getGeometrySpec().getSubVolume(0).setName((subVolume0PixVal == EXTRACELLULAR_PIXVAL ? EXTRACELLULAR_NAME : CYTOSOL_NAME));
    int subVolume1PixVal = ((ImageSubVolume) geometry.getGeometrySpec().getSubVolume(1)).getPixelValue();
    geometry.getGeometrySpec().getSubVolume(1).setName((subVolume1PixVal == CYTOSOL_PIXVAL ? CYTOSOL_NAME : EXTRACELLULAR_NAME));
    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);
    // Membrane mem = model.addMembrane(EXTRACELLULAR_CYTOSOL_MEM_NAME);
    // model.getStructureTopology().setInsideFeature(mem, cytosol);
    // model.getStructureTopology().setOutsideFeature(mem, extracellular);
    String roiDataName = FRAPStudy.ROI_EXTDATA_NAME;
    final int SPECIES_COUNT = 4;
    final int FREE_SPECIES_INDEX = 0;
    final int BS_SPECIES_INDEX = 1;
    final int COMPLEX_SPECIES_INDEX = 2;
    final int IMMOBILE_SPECIES_INDEX = 3;
    Expression[] diffusionConstants = null;
    Species[] species = null;
    SpeciesContext[] speciesContexts = null;
    Expression[] initialConditions = null;
    diffusionConstants = new Expression[SPECIES_COUNT];
    species = new Species[SPECIES_COUNT];
    speciesContexts = new SpeciesContext[SPECIES_COUNT];
    initialConditions = new Expression[SPECIES_COUNT];
    // total initial condition
    FieldFunctionArguments postBleach_first = new FieldFunctionArguments(roiDataName, "postbleach_first", new Expression(0), VariableType.VOLUME);
    FieldFunctionArguments prebleach_avg = new FieldFunctionArguments(roiDataName, "prebleach_avg", new Expression(0), VariableType.VOLUME);
    Expression expPostBleach_first = new Expression(postBleach_first.infix());
    Expression expPreBleach_avg = new Expression(prebleach_avg.infix());
    Expression totalIniCondition = Expression.div(expPostBleach_first, expPreBleach_avg);
    // Free Species
    diffusionConstants[FREE_SPECIES_INDEX] = new Expression(df);
    species[FREE_SPECIES_INDEX] = new Species(FRAPStudy.SPECIES_NAME_PREFIX_MOBILE, "Mobile bleachable species");
    speciesContexts[FREE_SPECIES_INDEX] = new SpeciesContext(null, species[FREE_SPECIES_INDEX].getCommonName(), species[FREE_SPECIES_INDEX], cytosol);
    initialConditions[FREE_SPECIES_INDEX] = Expression.mult(new Expression(ff), totalIniCondition);
    // Immobile Species (No diffusion)
    // Set very small diffusion rate on immobile to force evaluation as state variable (instead of FieldData function)
    // If left as a function errors occur because functions involving FieldData require a database connection
    final String IMMOBILE_DIFFUSION_KLUDGE = "1e-14";
    diffusionConstants[IMMOBILE_SPECIES_INDEX] = new Expression(IMMOBILE_DIFFUSION_KLUDGE);
    species[IMMOBILE_SPECIES_INDEX] = new Species(FRAPStudy.SPECIES_NAME_PREFIX_IMMOBILE, "Immobile bleachable species");
    speciesContexts[IMMOBILE_SPECIES_INDEX] = new SpeciesContext(null, species[IMMOBILE_SPECIES_INDEX].getCommonName(), species[IMMOBILE_SPECIES_INDEX], cytosol);
    initialConditions[IMMOBILE_SPECIES_INDEX] = Expression.mult(new Expression(fimm), totalIniCondition);
    // BS Species
    diffusionConstants[BS_SPECIES_INDEX] = new Expression(IMMOBILE_DIFFUSION_KLUDGE);
    species[BS_SPECIES_INDEX] = new Species(FRAPStudy.SPECIES_NAME_PREFIX_BINDING_SITE, "Binding Site species");
    speciesContexts[BS_SPECIES_INDEX] = new SpeciesContext(null, species[BS_SPECIES_INDEX].getCommonName(), species[BS_SPECIES_INDEX], cytosol);
    initialConditions[BS_SPECIES_INDEX] = Expression.mult(new Expression(bs), totalIniCondition);
    // Complex species
    diffusionConstants[COMPLEX_SPECIES_INDEX] = new Expression(dc);
    species[COMPLEX_SPECIES_INDEX] = new Species(FRAPStudy.SPECIES_NAME_PREFIX_SLOW_MOBILE, "Slower mobile bleachable species");
    speciesContexts[COMPLEX_SPECIES_INDEX] = new SpeciesContext(null, species[COMPLEX_SPECIES_INDEX].getCommonName(), species[COMPLEX_SPECIES_INDEX], cytosol);
    initialConditions[COMPLEX_SPECIES_INDEX] = Expression.mult(new Expression(fc), totalIniCondition);
    // add reactions to species if there is bleachWhileMonitoring rate.
    for (int i = 0; i < initialConditions.length; i++) {
        model.addSpecies(species[i]);
        model.addSpeciesContext(speciesContexts[i]);
        // reaction with BMW rate, which should not be applied to binding site
        if (!(species[i].getCommonName().equals(FRAPStudy.SPECIES_NAME_PREFIX_BINDING_SITE))) {
            SimpleReaction simpleReaction = new SimpleReaction(model, cytosol, speciesContexts[i].getName() + "_bleach", true);
            model.addReactionStep(simpleReaction);
            simpleReaction.addReactant(speciesContexts[i], 1);
            MassActionKinetics massActionKinetics = new MassActionKinetics(simpleReaction);
            simpleReaction.setKinetics(massActionKinetics);
            KineticsParameter kforward = massActionKinetics.getForwardRateParameter();
            simpleReaction.getKinetics().setParameterValue(kforward, new Expression(new Double(bwmRate)));
        }
    }
    // add the binding reaction: F + BS <-> C
    SimpleReaction simpleReaction2 = new SimpleReaction(model, cytosol, "reac_binding", true);
    model.addReactionStep(simpleReaction2);
    simpleReaction2.addReactant(speciesContexts[FREE_SPECIES_INDEX], 1);
    simpleReaction2.addReactant(speciesContexts[BS_SPECIES_INDEX], 1);
    simpleReaction2.addProduct(speciesContexts[COMPLEX_SPECIES_INDEX], 1);
    MassActionKinetics massActionKinetics = new MassActionKinetics(simpleReaction2);
    simpleReaction2.setKinetics(massActionKinetics);
    KineticsParameter kforward = massActionKinetics.getForwardRateParameter();
    KineticsParameter kreverse = massActionKinetics.getReverseRateParameter();
    simpleReaction2.getKinetics().setParameterValue(kforward, new Expression(new Double(onRate)));
    simpleReaction2.getKinetics().setParameterValue(kreverse, new Expression(new Double(offRate)));
    // create simulation context
    SimulationContext simContext = new SimulationContext(bioModel.getModel(), geometry);
    bioModel.addSimulationContext(simContext);
    FeatureMapping cytosolFeatureMapping = (FeatureMapping) simContext.getGeometryContext().getStructureMapping(cytosol);
    FeatureMapping extracellularFeatureMapping = (FeatureMapping) simContext.getGeometryContext().getStructureMapping(extracellular);
    // Membrane plasmaMembrane = model.getStructureTopology().getMembrane(cytosol, extracellular);
    // MembraneMapping plasmaMembraneMapping = (MembraneMapping)simContext.getGeometryContext().getStructureMapping(plasmaMembrane);
    SubVolume cytSubVolume = geometry.getGeometrySpec().getSubVolume(CYTOSOL_NAME);
    SubVolume exSubVolume = geometry.getGeometrySpec().getSubVolume(EXTRACELLULAR_NAME);
    SurfaceClass pmSurfaceClass = geometry.getGeometrySurfaceDescription().getSurfaceClass(exSubVolume, cytSubVolume);
    cytosolFeatureMapping.setGeometryClass(cytSubVolume);
    extracellularFeatureMapping.setGeometryClass(exSubVolume);
    // plasmaMembraneMapping.setGeometryClass(pmSurfaceClass);
    cytosolFeatureMapping.getUnitSizeParameter().setExpression(new Expression(1.0));
    extracellularFeatureMapping.getUnitSizeParameter().setExpression(new Expression(1.0));
    for (int i = 0; i < speciesContexts.length; i++) {
        SpeciesContextSpec scs = simContext.getReactionContext().getSpeciesContextSpec(speciesContexts[i]);
        scs.getInitialConditionParameter().setExpression(initialConditions[i]);
        scs.getDiffusionParameter().setExpression(diffusionConstants[i]);
    }
    MathMapping mathMapping = simContext.createNewMathMapping();
    MathDescription mathDesc = mathMapping.getMathDescription();
    // Add total fluorescence as function of mobile(optional: and slower mobile) and immobile fractions
    mathDesc.addVariable(new Function(FRAPStudy.SPECIES_NAME_PREFIX_COMBINED, new Expression(species[FREE_SPECIES_INDEX].getCommonName() + "+" + species[COMPLEX_SPECIES_INDEX].getCommonName() + "+" + species[IMMOBILE_SPECIES_INDEX].getCommonName()), null));
    simContext.setMathDescription(mathDesc);
    SimulationVersion simVersion = new SimulationVersion(simKey, "sim1", owner, new GroupAccessNone(), new KeyValue("0"), new BigDecimal(0), new Date(), VersionFlag.Current, "", null);
    Simulation newSimulation = new Simulation(simVersion, mathDesc);
    simContext.addSimulation(newSimulation);
    newSimulation.getSolverTaskDescription().setTimeBounds(timeBounds);
    newSimulation.getMeshSpecification().setSamplingSize(cellROI_2D.getISize());
    // newSimulation.getSolverTaskDescription().setTimeStep(timeStep); // Sundials doesn't need time step
    newSimulation.getSolverTaskDescription().setSolverDescription(SolverDescription.SundialsPDE);
    // use exp time step as output time spec
    newSimulation.getSolverTaskDescription().setOutputTimeSpec(new UniformOutputTimeSpec(timeStepVal));
    return bioModel;
}
Also used : ImageException(cbit.image.ImageException) KeyValue(org.vcell.util.document.KeyValue) Extent(org.vcell.util.Extent) SurfaceClass(cbit.vcell.geometry.SurfaceClass) MathDescription(cbit.vcell.math.MathDescription) VCImage(cbit.image.VCImage) SpeciesContext(cbit.vcell.model.SpeciesContext) SpeciesContextSpec(cbit.vcell.mapping.SpeciesContextSpec) Feature(cbit.vcell.model.Feature) TimeBounds(cbit.vcell.solver.TimeBounds) Function(cbit.vcell.math.Function) GroupAccessNone(org.vcell.util.document.GroupAccessNone) SimulationVersion(org.vcell.util.document.SimulationVersion) KineticsParameter(cbit.vcell.model.Kinetics.KineticsParameter) FeatureMapping(cbit.vcell.mapping.FeatureMapping) SubVolume(cbit.vcell.geometry.SubVolume) ImageSubVolume(cbit.vcell.geometry.ImageSubVolume) Species(cbit.vcell.model.Species) ImageSubVolume(cbit.vcell.geometry.ImageSubVolume) SimpleReaction(cbit.vcell.model.SimpleReaction) UniformOutputTimeSpec(cbit.vcell.solver.UniformOutputTimeSpec) FieldFunctionArguments(cbit.vcell.field.FieldFunctionArguments) VCImageUncompressed(cbit.image.VCImageUncompressed) SimulationContext(cbit.vcell.mapping.SimulationContext) ROI(cbit.vcell.VirtualMicroscopy.ROI) ImageException(cbit.image.ImageException) UserCancelException(org.vcell.util.UserCancelException) 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) Model(cbit.vcell.model.Model) BioModel(cbit.vcell.biomodel.BioModel) MathMapping(cbit.vcell.mapping.MathMapping) MassActionKinetics(cbit.vcell.model.MassActionKinetics)

Example 19 with MathMapping

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

the class ModelOptimizationMapping method computeOptimizationSpec.

/**
 * Insert the method's description here.
 * Creation date: (8/22/2005 9:26:52 AM)
 * @return cbit.vcell.opt.OptimizationSpec
 * @param modelOptimizationSpec cbit.vcell.modelopt.ModelOptimizationSpec
 */
MathSymbolMapping computeOptimizationSpec() throws MathException, MappingException {
    if (getModelOptimizationSpec().getReferenceData() == null) {
        System.out.println("no referenced data defined");
        return null;
    }
    OptimizationSpec optSpec = new OptimizationSpec();
    optSpec.setComputeProfileDistributions(modelOptimizationSpec.isComputeProfileDistributions());
    parameterMappings = null;
    // 
    // get original MathDescription (later to be substituted for local/global parameters).
    // 
    SimulationContext simContext = modelOptimizationSpec.getSimulationContext();
    MathMapping mathMapping = simContext.createNewMathMapping();
    MathDescription origMathDesc = null;
    mathSymbolMapping = null;
    try {
        origMathDesc = mathMapping.getMathDescription();
        mathSymbolMapping = mathMapping.getMathSymbolMapping();
    } catch (MatrixException e) {
        e.printStackTrace(System.out);
        throw new MappingException(e.getMessage());
    } catch (ModelException e) {
        e.printStackTrace(System.out);
        throw new MappingException(e.getMessage());
    } catch (ExpressionException e) {
        e.printStackTrace(System.out);
        throw new MathException(e.getMessage());
    }
    // 
    // create objective function (mathDesc and data)
    // 
    ReferenceData referenceData = getRemappedReferenceData(mathMapping);
    if (referenceData == null) {
        throw new RuntimeException("no referenced data defined");
    }
    // 
    // get parameter mappings
    // 
    ParameterMappingSpec[] parameterMappingSpecs = modelOptimizationSpec.getParameterMappingSpecs();
    Vector<ParameterMapping> parameterMappingList = new Vector<ParameterMapping>();
    Variable[] allVars = (Variable[]) BeanUtils.getArray(origMathDesc.getVariables(), Variable.class);
    for (int i = 0; i < parameterMappingSpecs.length; i++) {
        cbit.vcell.model.Parameter modelParameter = parameterMappingSpecs[i].getModelParameter();
        String mathSymbol = null;
        Variable mathVariable = null;
        if (mathSymbolMapping != null) {
            Variable variable = mathSymbolMapping.getVariable(modelParameter);
            if (variable != null) {
                mathSymbol = variable.getName();
            }
            if (mathSymbol != null) {
                mathVariable = origMathDesc.getVariable(mathSymbol);
            }
        }
        if (mathVariable != null) {
            if (parameterMappingSpecs[i].isSelected()) {
                if (parameterMappingSpecs[i].getHigh() < parameterMappingSpecs[i].getLow()) {
                    throw new MathException("The lower bound for Parameter '" + parameterMappingSpecs[i].getModelParameter().getName() + "' is greater than its upper bound.");
                }
                if (parameterMappingSpecs[i].getCurrent() < parameterMappingSpecs[i].getLow()) {
                    throw new MathException("The initial guess of '" + parameterMappingSpecs[i].getModelParameter().getName() + "' is smaller than its lower bound.");
                }
                if (parameterMappingSpecs[i].getCurrent() > parameterMappingSpecs[i].getHigh()) {
                    throw new MathException("The initial guess of '" + parameterMappingSpecs[i].getModelParameter().getName() + "' is greater than its upper bound.");
                }
                if (parameterMappingSpecs[i].getLow() < 0) {
                    throw new MathException("The lower bound for Parameter '" + parameterMappingSpecs[i].getModelParameter().getName() + "' is negative. All lower bounds must not be negative.");
                }
                if (Double.isInfinite(parameterMappingSpecs[i].getLow())) {
                    throw new MathException("The lower bound for Parameter '" + parameterMappingSpecs[i].getModelParameter().getName() + "' is infinity. Lower bounds must not be infinity.");
                }
                if (parameterMappingSpecs[i].getHigh() <= 0) {
                    throw new MathException("The upper bound for Parameter '" + parameterMappingSpecs[i].getModelParameter().getName() + "' is negative. All upper bounds must be positive.");
                }
                if (Double.isInfinite(parameterMappingSpecs[i].getHigh())) {
                    throw new MathException("The upper bound for Parameter '" + parameterMappingSpecs[i].getModelParameter().getName() + "' is infinity. Upper bounds must not be infinity.");
                }
            }
            double low = parameterMappingSpecs[i].isSelected() && parameterMappingSpecs[i].getLow() == 0 ? 1e-8 : parameterMappingSpecs[i].getLow();
            double high = parameterMappingSpecs[i].getHigh();
            double scale = Math.abs(parameterMappingSpecs[i].getCurrent()) < 1.0E-10 ? 1.0 : Math.abs(parameterMappingSpecs[i].getCurrent());
            double current = parameterMappingSpecs[i].getCurrent();
            low = Math.min(low, current);
            high = Math.max(high, current);
            Parameter optParameter = new Parameter(mathSymbol, low, high, scale, current);
            ParameterMapping parameterMapping = new ParameterMapping(modelParameter, optParameter, mathVariable);
            // 
            if (mathVariable instanceof Constant) {
                Constant origConstant = (Constant) mathVariable;
                for (int j = 0; j < allVars.length; j++) {
                    if (allVars[j].equals(origConstant)) {
                        if (parameterMappingSpecs[i].isSelected()) {
                            allVars[j] = new ParameterVariable(origConstant.getName());
                        } else {
                            allVars[j] = new Constant(origConstant.getName(), new Expression(optParameter.getInitialGuess()));
                        }
                        break;
                    }
                }
            }
            // 
            if (parameterMappingSpecs[i].isSelected()) {
                parameterMappingList.add(parameterMapping);
            }
        }
    }
    parameterMappings = (ParameterMapping[]) BeanUtils.getArray(parameterMappingList, ParameterMapping.class);
    try {
        origMathDesc.setAllVariables(allVars);
    } catch (ExpressionBindingException e) {
        e.printStackTrace(System.out);
        throw new MathException(e.getMessage());
    }
    // 
    for (int i = 0; i < parameterMappings.length; i++) {
        optSpec.addParameter(parameterMappings[i].getOptParameter());
    }
    Vector<Issue> issueList = new Vector<Issue>();
    IssueContext issueContext = new IssueContext();
    optSpec.gatherIssues(issueContext, issueList);
    for (int i = 0; i < issueList.size(); i++) {
        Issue issue = issueList.elementAt(i);
        if (issue.getSeverity() == Issue.SEVERITY_ERROR) {
            throw new RuntimeException(issue.getMessage());
        }
    }
    // 
    // 
    // 
    optimizationSpec = optSpec;
    return mathSymbolMapping;
}
Also used : ParameterVariable(cbit.vcell.math.ParameterVariable) Variable(cbit.vcell.math.Variable) Issue(org.vcell.util.Issue) MathDescription(cbit.vcell.math.MathDescription) Constant(cbit.vcell.math.Constant) ParameterVariable(cbit.vcell.math.ParameterVariable) ExpressionException(cbit.vcell.parser.ExpressionException) MappingException(cbit.vcell.mapping.MappingException) MatrixException(cbit.vcell.matrix.MatrixException) IssueContext(org.vcell.util.IssueContext) OptimizationSpec(cbit.vcell.opt.OptimizationSpec) Vector(java.util.Vector) ModelException(cbit.vcell.model.ModelException) SimulationContext(cbit.vcell.mapping.SimulationContext) ExpressionBindingException(cbit.vcell.parser.ExpressionBindingException) SimpleReferenceData(cbit.vcell.opt.SimpleReferenceData) ReferenceData(cbit.vcell.opt.ReferenceData) Expression(cbit.vcell.parser.Expression) MathException(cbit.vcell.math.MathException) MathMapping(cbit.vcell.mapping.MathMapping) Parameter(cbit.vcell.opt.Parameter)

Example 20 with MathMapping

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

the class ModelOptimizationSpec method removeUncoupledParameters.

public void removeUncoupledParameters() {
    try {
        localIssueList.clear();
        MathMapping mathMapping = getSimulationContext().createNewMathMapping();
        MathDescription mathDesc = mathMapping.getMathDescription();
        MathSystemHash mathSystemHash = fromMath(mathDesc);
        Graph graph = mathSystemHash.getDependencyGraph(mathSystemHash.getSymbols());
        Tree[] spanningTrees = graph.getSpanningForest();
        // 
        for (int i = 0; i < spanningTrees.length; i++) {
            Node[] treeNodes = spanningTrees[i].getNodes();
            boolean bHasStateVariables = false;
            for (int j = 0; j < treeNodes.length; j++) {
                Node node = treeNodes[j];
                Variable var = mathDesc.getVariable(node.getName());
                if (var instanceof VolVariable || var instanceof MemVariable || var instanceof FilamentVariable || var instanceof VolumeRegionVariable || var instanceof MembraneRegionVariable || var instanceof FilamentRegionVariable) {
                    bHasStateVariables = true;
                    break;
                }
            }
            if (!bHasStateVariables) {
                spanningTrees = (Tree[]) BeanUtils.removeElement(spanningTrees, spanningTrees[i]);
                i--;
            }
        }
        // 
        // remove parameters not mapped to a surviving tree (not coupled to any state variables
        // 
        ArrayList<ParameterMappingSpec> paramMappingSpecsList = new ArrayList<ParameterMappingSpec>();
        paramMappingSpecsList.addAll(Arrays.asList(fieldParameterMappingSpecs));
        for (int i = 0; i < paramMappingSpecsList.size(); i++) {
            Parameter parameter = paramMappingSpecsList.get(i).getModelParameter();
            String mathName = mathMapping.getMathSymbolMapping().getVariable(parameter).getName();
            boolean bFoundInTree = false;
            for (int j = 0; j < spanningTrees.length; j++) {
                Node node = spanningTrees[j].getNode(mathName);
                if (node != null) {
                    bFoundInTree = true;
                }
            }
            if (!bFoundInTree) {
                paramMappingSpecsList.remove(i);
                i--;
            }
        }
        ParameterMappingSpec[] parameterMappingSpecs = new ParameterMappingSpec[paramMappingSpecsList.size()];
        paramMappingSpecsList.toArray(parameterMappingSpecs);
        setParameterMappingSpecs(parameterMappingSpecs);
    } catch (Exception e) {
        e.printStackTrace(System.out);
        localIssueList.add(new Issue(this, localIssueContext, IssueCategory.ParameterEstimationGeneralWarning, e.getMessage(), Issue.SEVERITY_WARNING));
    // throw new RuntimeException(e.getMessage());
    }
}
Also used : MembraneRegionVariable(cbit.vcell.math.MembraneRegionVariable) FilamentVariable(cbit.vcell.math.FilamentVariable) VolVariable(cbit.vcell.math.VolVariable) VolumeRegionVariable(cbit.vcell.math.VolumeRegionVariable) MemVariable(cbit.vcell.math.MemVariable) FilamentRegionVariable(cbit.vcell.math.FilamentRegionVariable) Variable(cbit.vcell.math.Variable) Issue(org.vcell.util.Issue) MembraneRegionVariable(cbit.vcell.math.MembraneRegionVariable) MathDescription(cbit.vcell.math.MathDescription) Node(cbit.util.graph.Node) ArrayList(java.util.ArrayList) VolumeRegionVariable(cbit.vcell.math.VolumeRegionVariable) MemVariable(cbit.vcell.math.MemVariable) Tree(cbit.util.graph.Tree) VolVariable(cbit.vcell.math.VolVariable) FilamentRegionVariable(cbit.vcell.math.FilamentRegionVariable) PropertyVetoException(java.beans.PropertyVetoException) ExpressionException(cbit.vcell.parser.ExpressionException) Graph(cbit.util.graph.Graph) FilamentVariable(cbit.vcell.math.FilamentVariable) MathMapping(cbit.vcell.mapping.MathMapping) Parameter(cbit.vcell.model.Parameter) KineticsParameter(cbit.vcell.model.Kinetics.KineticsParameter) ModelParameter(cbit.vcell.model.Model.ModelParameter) KineticsProxyParameter(cbit.vcell.model.Kinetics.KineticsProxyParameter) SpeciesContextSpecParameter(cbit.vcell.mapping.SpeciesContextSpec.SpeciesContextSpecParameter)

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