Search in sources :

Example 41 with Function

use of cbit.vcell.math.Function in project vcell by virtualcell.

the class GibsonSolver method getStochSolverResultSet.

/**
 * Get data columns and function columns to be ready for plot.
 * Creation date: (8/15/2006 11:36:43 AM)
 * @return cbit.vcell.solver.stoch.StochSolverResultSet
 */
public ODESolverResultSet getStochSolverResultSet() {
    // read .stoch file, this funciton here equals to getODESolverRestultSet()+getStateVariableResultSet()  in ODE.
    ODESolverResultSet stSolverResultSet = new ODESolverResultSet();
    FileInputStream inputStream = null;
    try {
        inputStream = new FileInputStream(getBaseName() + IDA_DATA_EXTENSION);
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        // Read header
        String line = bufferedReader.readLine();
        if (line == null) {
            // throw exception
            System.out.println("There is no data in output file!");
            return null;
        }
        while (line.indexOf(':') > 0) {
            String name = line.substring(0, line.indexOf(':'));
            stSolverResultSet.addDataColumn(new ODESolverResultSetColumnDescription(name));
            line = line.substring(line.indexOf(':') + 1);
        }
        // Read data
        while ((line = bufferedReader.readLine()) != null) {
            line = line + "\t";
            double[] values = new double[stSolverResultSet.getDataColumnCount()];
            boolean bCompleteRow = true;
            for (int i = 0; i < stSolverResultSet.getDataColumnCount(); i++) {
                if (line.indexOf('\t') == -1) {
                    bCompleteRow = false;
                    break;
                } else {
                    String value = line.substring(0, line.indexOf('\t')).trim();
                    values[i] = Double.valueOf(value).doubleValue();
                    line = line.substring(line.indexOf('\t') + 1);
                }
            }
            if (bCompleteRow) {
                stSolverResultSet.addRow(values);
            } else {
                break;
            }
        }
    // 
    } catch (Exception e) {
        e.printStackTrace(System.out);
        return null;
    } finally {
        try {
            if (inputStream != null) {
                inputStream.close();
            }
        } catch (Exception ex) {
            lg.error(ex.getMessage(), ex);
        }
    }
    /*
	Add appropriate Function columns to result set if the stochastic simulation is to display the trajectory.
	No function columns for the results of multiple stochastic trials
	*/
    SimulationSymbolTable simSymbolTable = simTask.getSimulationJob().getSimulationSymbolTable();
    if (simSymbolTable.getSimulation().getSolverTaskDescription().getStochOpt().getNumOfTrials() == 1) {
        Function[] functions = simSymbolTable.getFunctions();
        for (int i = 0; i < functions.length; i++) {
            if (SimulationSymbolTable.isFunctionSaved(functions[i])) {
                Expression exp1 = new Expression(functions[i].getExpression());
                try {
                    exp1 = simSymbolTable.substituteFunctions(exp1);
                } catch (MathException e) {
                    e.printStackTrace(System.out);
                    throw new RuntimeException("Substitute function failed on function " + functions[i].getName() + " " + e.getMessage());
                } catch (ExpressionException e) {
                    e.printStackTrace(System.out);
                    throw new RuntimeException("Substitute function failed on function " + functions[i].getName() + " " + e.getMessage());
                }
                try {
                    FunctionColumnDescription cd = new FunctionColumnDescription(exp1.flatten(), functions[i].getName(), null, functions[i].getName(), false);
                    stSolverResultSet.addFunctionColumn(cd);
                } catch (ExpressionException e) {
                    e.printStackTrace(System.out);
                }
            }
        }
    }
    return stSolverResultSet;
}
Also used : InputStreamReader(java.io.InputStreamReader) SimulationSymbolTable(cbit.vcell.solver.SimulationSymbolTable) FileInputStream(java.io.FileInputStream) IOException(java.io.IOException) ExpressionException(cbit.vcell.parser.ExpressionException) FileNotFoundException(java.io.FileNotFoundException) SolverException(cbit.vcell.solver.SolverException) MathException(cbit.vcell.math.MathException) ExpressionException(cbit.vcell.parser.ExpressionException) Function(cbit.vcell.math.Function) Expression(cbit.vcell.parser.Expression) MathException(cbit.vcell.math.MathException) BufferedReader(java.io.BufferedReader) ODESolverResultSet(cbit.vcell.solver.ode.ODESolverResultSet) ODESolverResultSetColumnDescription(cbit.vcell.math.ODESolverResultSetColumnDescription) FunctionColumnDescription(cbit.vcell.math.FunctionColumnDescription)

Example 42 with Function

use of cbit.vcell.math.Function in project vcell by virtualcell.

the class HybridSolver method getHybridSolverResultSet.

/**
 * Get data columns and function columns to be ready for plot.
 * Creation date: (8/15/2006 11:36:43 AM)
 * @return cbit.vcell.solver.stoch.StochSolverResultSet
 */
private ODESolverResultSet getHybridSolverResultSet() {
    // read .stoch file, this funciton here equals to getODESolverRestultSet()+getStateVariableResultSet()  in ODE.
    ODESolverResultSet stSolverResultSet = new ODESolverResultSet();
    try {
        String filename = getBaseName() + NETCDF_DATA_EXTENSION;
        NetCDFEvaluator ncEva = new NetCDFEvaluator();
        NetCDFReader ncReader = null;
        try {
            ncEva.setNetCDFTarget(filename);
            ncReader = ncEva.getNetCDFReader();
        } catch (Exception e) {
            e.printStackTrace(System.err);
            throw new RuntimeException("Cannot open simulation result file: " + filename + "!");
        }
        // Read result according to trial number
        if (ncReader.getNumTrials() == 1) {
            // Read header
            String[] varNames = ncReader.getSpeciesNames_val();
            // first column will be time t.
            stSolverResultSet.addDataColumn(new ODESolverResultSetColumnDescription("t"));
            // following columns are stoch variables
            for (int i = 0; i < varNames.length; i++) {
                stSolverResultSet.addDataColumn(new ODESolverResultSetColumnDescription(varNames[i]));
            }
            // Read data
            // data only, no time points
            ArrayDouble data = (ArrayDouble) ncEva.getTimeSeriesData(1);
            double[] timePoints = ncReader.getTimePoints();
            System.out.println("time points length is " + timePoints.length);
            // shape[0]:num of timepoints, shape[1]: num of species
            int[] shape = data.getShape();
            if (// one species
            shape.length == 1) {
                ArrayDouble.D1 temData = (ArrayDouble.D1) data;
                System.out.println("one species in time series data and size is " + temData.getSize());
                for (// rows
                int k = 0; // rows
                k < timePoints.length; // rows
                k++) {
                    double[] values = new double[stSolverResultSet.getDataColumnCount()];
                    values[0] = timePoints[k];
                    for (int i = 1; i < stSolverResultSet.getDataColumnCount(); i++) {
                        values[i] = temData.get(k);
                    }
                    stSolverResultSet.addRow(values);
                }
            }
            if (// more than one species
            shape.length == 2) {
                ArrayDouble.D2 temData = (ArrayDouble.D2) data;
                System.out.println("multiple species in time series, the length of time series is :" + data.getShape()[0] + ", and the total number of speceis is: " + data.getShape()[1]);
                for (// rows
                int k = 0; // rows
                k < timePoints.length; // rows
                k++) {
                    double[] values = new double[stSolverResultSet.getDataColumnCount()];
                    values[0] = timePoints[k];
                    for (int i = 1; i < stSolverResultSet.getDataColumnCount(); i++) {
                        values[i] = temData.get(k, i - 1);
                    }
                    stSolverResultSet.addRow(values);
                }
            }
        } else if (ncReader.getNumTrials() > 1) {
            // Read header
            String[] varNames = ncReader.getSpeciesNames_val();
            // first column will be time t.
            stSolverResultSet.addDataColumn(new ODESolverResultSetColumnDescription("TrialNo"));
            // following columns are stoch variables
            for (int i = 0; i < varNames.length; i++) {
                stSolverResultSet.addDataColumn(new ODESolverResultSetColumnDescription(varNames[i]));
            }
            // Read data
            // data only, no trial numbers
            ArrayDouble data = (ArrayDouble) ncEva.getDataOverTrials(ncReader.getTimePoints().length - 1);
            int[] trialNum = ncEva.getNetCDFReader().getTrialNumbers();
            // System.out.println("total trials are "+trialNum.length);
            // shape[0]:number of trials, shape[1]: num of species
            int[] shape = data.getShape();
            if (// one species
            shape.length == 1) {
                ArrayDouble.D1 temData = (ArrayDouble.D1) data;
                // System.out.println("one species over trials, size is: "+temData.getSize());
                for (// rows
                int k = 0; // rows
                k < trialNum.length; // rows
                k++) {
                    double[] values = new double[stSolverResultSet.getDataColumnCount()];
                    values[0] = trialNum[k];
                    for (int i = 1; i < stSolverResultSet.getDataColumnCount(); i++) {
                        values[i] = temData.get(k);
                    }
                    stSolverResultSet.addRow(values);
                }
            }
            if (// more than one species
            shape.length == 2) {
                ArrayDouble.D2 temData = (ArrayDouble.D2) data;
                // System.out.println("multiple species in multiple trials, the length of trials is :"+data.getShape()[0]+", and the total number of speceis is: "+data.getShape()[1]);
                for (// rows
                int k = 0; // rows
                k < trialNum.length; // rows
                k++) {
                    double[] values = new double[stSolverResultSet.getDataColumnCount()];
                    values[0] = trialNum[k];
                    for (int i = 1; i < stSolverResultSet.getDataColumnCount(); i++) {
                        values[i] = temData.get(k, i - 1);
                    }
                    stSolverResultSet.addRow(values);
                }
            }
        } else {
            throw new RuntimeException("Number of trials should be a countable positive value, from 1 to N.");
        }
    } catch (Exception e) {
        e.printStackTrace(System.err);
        throw new RuntimeException("Problem encountered in parsing hybrid simulation results.\n" + e.getMessage());
    }
    /*
	 *Add appropriate Function columns to result set if the stochastic simulation is to display the trajectory.
	 *No function columns for the results of multiple stochastic trials.
	 *In stochastic simulation the functions include probability functions and clamped variable.
	 */
    SimulationSymbolTable simSymbolTable = simTask.getSimulationJob().getSimulationSymbolTable();
    if (simSymbolTable.getSimulation().getSolverTaskDescription().getStochOpt().getNumOfTrials() == 1) {
        Function[] functions = simSymbolTable.getFunctions();
        for (int i = 0; i < functions.length; i++) {
            if (SimulationSymbolTable.isFunctionSaved(functions[i])) {
                Expression exp1 = new Expression(functions[i].getExpression());
                try {
                    exp1 = simSymbolTable.substituteFunctions(exp1);
                } catch (MathException e) {
                    e.printStackTrace(System.out);
                    throw new RuntimeException("Substitute function failed on function " + functions[i].getName() + " " + e.getMessage());
                } catch (ExpressionException e) {
                    e.printStackTrace(System.out);
                    throw new RuntimeException("Substitute function failed on function " + functions[i].getName() + " " + e.getMessage());
                }
                try {
                    FunctionColumnDescription cd = new FunctionColumnDescription(exp1.flatten(), functions[i].getName(), null, functions[i].getName(), false);
                    stSolverResultSet.addFunctionColumn(cd);
                } catch (ExpressionException e) {
                    e.printStackTrace(System.out);
                }
            }
        }
    }
    return stSolverResultSet;
}
Also used : SimulationSymbolTable(cbit.vcell.solver.SimulationSymbolTable) SolverException(cbit.vcell.solver.SolverException) IOException(java.io.IOException) ExpressionException(cbit.vcell.parser.ExpressionException) FileNotFoundException(java.io.FileNotFoundException) MathException(cbit.vcell.math.MathException) ExpressionException(cbit.vcell.parser.ExpressionException) Function(cbit.vcell.math.Function) ArrayDouble(ucar.ma2.ArrayDouble) Expression(cbit.vcell.parser.Expression) MathException(cbit.vcell.math.MathException) ODESolverResultSet(cbit.vcell.solver.ode.ODESolverResultSet) ODESolverResultSetColumnDescription(cbit.vcell.math.ODESolverResultSetColumnDescription) FunctionColumnDescription(cbit.vcell.math.FunctionColumnDescription)

Example 43 with Function

use of cbit.vcell.math.Function in project vcell by virtualcell.

the class CellQuanVCTranslator method addRateFunction.

private Function addRateFunction(Element varRef, String compName, String mangledName) {
    Element role;
    String stoich = null, roleAtt = null;
    // can only imply the delta function if the stoichiometry attribute is present also
    // not sure if there can be more than one, if not, could just pass in the 'role' element itself.
    @SuppressWarnings("unchecked") Iterator<Element> i = varRef.getChildren(CELLMLTags.ROLE, sNamespace).iterator();
    while (i.hasNext()) {
        role = i.next();
        stoich = role.getAttributeValue(CELLMLTags.stoichiometry, sAttNamespace);
        roleAtt = role.getAttributeValue(CELLMLTags.role, sAttNamespace);
        if (stoich != null)
            break;
    }
    if (stoich != null) {
        // Can only imply the function if a variable_ref with a role of "rate" exists
        JDOMTreeWalker reactionWalker = new JDOMTreeWalker((Element) varRef.getParent(), new ElementFilter(CELLMLTags.ROLE));
        Element rateRole = reactionWalker.getMatchingElement(CELLMLTags.role, sAttNamespace, CELLMLTags.rateRole);
        if (rateRole != null) {
            String rateVarName = ((Element) rateRole.getParent()).getAttributeValue(CELLMLTags.variable, sAttNamespace);
            StringBuffer formula = new StringBuffer("(");
            if (roleAtt.equals(CELLMLTags.productRole))
                formula.append("-(");
            formula.append(stoich + "*" + nm.getMangledName(compName, rateVarName));
            if (roleAtt.equals(CELLMLTags.productRole))
                formula.append(")");
            formula.append(")");
            try {
                Domain domain = null;
                return new Function(mangledName, new Expression(formula.toString()), domain);
            // fnsVector.add(function);
            // mathDescription.addVariable(function);
            } catch (Exception e) {
                e.printStackTrace(System.out);
                throw new RuntimeException("Error adding function (" + mangledName + ") to mathDexcription : " + e.getMessage());
            }
        }
    }
    return null;
}
Also used : Function(cbit.vcell.math.Function) Expression(cbit.vcell.parser.Expression) Element(org.jdom.Element) ElementFilter(org.jdom.filter.ElementFilter) CompartmentSubDomain(cbit.vcell.math.CompartmentSubDomain) Domain(cbit.vcell.math.Variable.Domain) ExpressionException(cbit.vcell.parser.ExpressionException) JDOMTreeWalker(cbit.util.xml.JDOMTreeWalker)

Example 44 with Function

use of cbit.vcell.math.Function 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 45 with Function

use of cbit.vcell.math.Function in project vcell by virtualcell.

the class OutputFunctionContext method propertyChange.

public void propertyChange(java.beans.PropertyChangeEvent event) {
    if (event.getSource() == simulationOwner && event.getPropertyName().equals("mathDescription")) {
        rebindAll();
    }
    if (event.getPropertyName().equals("geometry")) {
        Geometry oldGeometry = (Geometry) event.getOldValue();
        Geometry newGeometry = (Geometry) event.getNewValue();
        // changing from ode to pde
        if (oldGeometry != null && oldGeometry.getDimension() == 0 && newGeometry.getDimension() > 0) {
            ArrayList<AnnotatedFunction> newFuncList = new ArrayList<AnnotatedFunction>();
            for (AnnotatedFunction function : outputFunctionsList) {
                try {
                    Expression newexp = new Expression(function.getExpression());
                    // making sure that output function is not direct function of constant.
                    newexp.bindExpression(this);
                    // here use math description as symbol table because we allow
                    // new expression itself to be function of constant.
                    MathDescription mathDescription = getSimulationOwner().getMathDescription();
                    newexp = MathUtilities.substituteFunctions(newexp, mathDescription).flatten();
                    VariableType newFuncType = VariableType.VOLUME;
                    String[] symbols = newexp.getSymbols();
                    if (symbols != null) {
                        // figure out the function type
                        VariableType[] varTypes = new VariableType[symbols.length];
                        for (int i = 0; i < symbols.length; i++) {
                            Variable var = mathDescription.getVariable(symbols[i]);
                            varTypes[i] = VariableType.getVariableType(var);
                        }
                        // check with flattened expression to find out the variable type of the new expression
                        Function flattenedFunction = new Function(function.getName(), newexp, function.getDomain());
                        newFuncType = SimulationSymbolTable.getFunctionVariableType(flattenedFunction, getSimulationOwner().getMathDescription(), symbols, varTypes, true);
                    }
                    AnnotatedFunction newFunc = new AnnotatedFunction(function.getName(), function.getExpression(), function.getDomain(), "", newFuncType, FunctionCategory.OUTPUTFUNCTION);
                    newFuncList.add(newFunc);
                    newFunc.bind(this);
                } catch (ExpressionException ex) {
                    ex.printStackTrace();
                    throw new RuntimeException(ex.getMessage());
                } catch (InconsistentDomainException ex) {
                    ex.printStackTrace();
                    throw new RuntimeException(ex.getMessage());
                }
            }
            try {
                setOutputFunctions0(newFuncList);
            } catch (PropertyVetoException e) {
                e.printStackTrace();
                throw new RuntimeException(e.getMessage());
            }
        }
    }
}
Also used : ReservedVariable(cbit.vcell.math.ReservedVariable) InsideVariable(cbit.vcell.math.InsideVariable) OutsideVariable(cbit.vcell.math.OutsideVariable) Variable(cbit.vcell.math.Variable) VariableType(cbit.vcell.math.VariableType) MathDescription(cbit.vcell.math.MathDescription) ArrayList(java.util.ArrayList) ExpressionException(cbit.vcell.parser.ExpressionException) Geometry(cbit.vcell.geometry.Geometry) PropertyVetoException(java.beans.PropertyVetoException) Function(cbit.vcell.math.Function) Expression(cbit.vcell.parser.Expression) InconsistentDomainException(cbit.vcell.math.InconsistentDomainException)

Aggregations

Function (cbit.vcell.math.Function)52 Expression (cbit.vcell.parser.Expression)42 Variable (cbit.vcell.math.Variable)32 ExpressionException (cbit.vcell.parser.ExpressionException)26 Constant (cbit.vcell.math.Constant)24 VolVariable (cbit.vcell.math.VolVariable)22 CompartmentSubDomain (cbit.vcell.math.CompartmentSubDomain)18 MathException (cbit.vcell.math.MathException)16 MathDescription (cbit.vcell.math.MathDescription)15 InsideVariable (cbit.vcell.math.InsideVariable)13 MemVariable (cbit.vcell.math.MemVariable)13 OutsideVariable (cbit.vcell.math.OutsideVariable)13 ReservedVariable (cbit.vcell.math.ReservedVariable)13 Domain (cbit.vcell.math.Variable.Domain)13 MembraneRegionVariable (cbit.vcell.math.MembraneRegionVariable)12 SubDomain (cbit.vcell.math.SubDomain)12 VolumeRegionVariable (cbit.vcell.math.VolumeRegionVariable)12 Vector (java.util.Vector)12 Element (org.jdom.Element)11 SubVolume (cbit.vcell.geometry.SubVolume)9