Search in sources :

Example 41 with VCImage

use of cbit.image.VCImage in project vcell by virtualcell.

the class ClientRequestManager method createSelectLoadGeomTask.

private AsynchClientTask createSelectLoadGeomTask(final TopLevelWindowManager requester) {
    AsynchClientTask selectLoadGeomTask = new AsynchClientTask("Select/Load geometry...", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {

        @Override
        public void run(Hashtable<String, Object> hashTable) throws Exception {
            VersionInfo vcVersionInfo = (VersionInfo) hashTable.get(VERSIONINFO_KEY);
            Geometry geom = null;
            if (vcVersionInfo instanceof VCDocumentInfo) {
                geom = getGeometryFromDocumentSelection(requester.getComponent(), (VCDocumentInfo) vcVersionInfo, false);
            } else if (vcVersionInfo instanceof VCImageInfo) {
                VCImage img = getDocumentManager().getImage((VCImageInfo) vcVersionInfo);
                geom = new Geometry("createSelectLoadGeomTask", img);
            } else {
                throw new Exception("Unexpected versioninfo type.");
            }
            // pregenerate sampled image, cpu intensive
            geom.precomputeAll(new GeometryThumbnailImageFactoryAWT());
            hashTable.put(GEOMETRY_KEY, geom);
        }
    };
    return selectLoadGeomTask;
}
Also used : Geometry(cbit.vcell.geometry.Geometry) VersionInfo(org.vcell.util.document.VersionInfo) GeometryThumbnailImageFactoryAWT(cbit.vcell.geometry.GeometryThumbnailImageFactoryAWT) AsynchClientTask(cbit.vcell.client.task.AsynchClientTask) VCDocumentInfo(org.vcell.util.document.VCDocumentInfo) Hashtable(java.util.Hashtable) VCImage(cbit.image.VCImage) VCImageInfo(cbit.image.VCImageInfo) ProgrammingException(org.vcell.util.ProgrammingException) GeometryException(cbit.vcell.geometry.GeometryException) IOException(java.io.IOException) DataAccessException(org.vcell.util.DataAccessException) PropertyVetoException(java.beans.PropertyVetoException) ImageException(cbit.image.ImageException) UtilCancelException(org.vcell.util.UtilCancelException) DataFormatException(java.util.zip.DataFormatException) UserCancelException(org.vcell.util.UserCancelException)

Example 42 with VCImage

use of cbit.image.VCImage 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 43 with VCImage

use of cbit.image.VCImage in project vcell by virtualcell.

the class SimulationData method createPostProcessingMesh.

private CartesianMesh createPostProcessingMesh(String varName, OutputContext outputContext) throws DataAccessException {
    try {
        refreshDataProcessingOutputInfo(outputContext);
        // create mesh here because we know the variablename
        ISize varISize = dataProcessingOutputInfo.getVariableISize(varName);
        Extent varExtent = dataProcessingOutputInfo.getVariableExtent(varName);
        Origin varOrigin = dataProcessingOutputInfo.getVariableOrigin(varName);
        VCImage vcImage = new VCImageUncompressed(null, new byte[varISize.getXYZ()], varExtent, varISize.getX(), varISize.getY(), varISize.getZ());
        RegionImage regionImage = new RegionImage(vcImage, 1 + (varISize.getY() > 0 ? 1 : 0) + (varISize.getZ() > 0 ? 1 : 0), varExtent, varOrigin, RegionImage.NO_SMOOTHING);
        return CartesianMesh.createSimpleCartesianMesh(dataProcessingOutputInfo.getVariableOrigin(varName), varExtent, varISize, regionImage);
    } catch (DataAccessException dae) {
        throw dae;
    } catch (Exception e) {
        throw new DataAccessException(e.getMessage(), (e.getCause() == null ? e : e.getCause()));
    }
}
Also used : Origin(org.vcell.util.Origin) Extent(org.vcell.util.Extent) ISize(org.vcell.util.ISize) RegionImage(cbit.vcell.geometry.RegionImage) VCImage(cbit.image.VCImage) VCImageUncompressed(cbit.image.VCImageUncompressed) DataAccessException(org.vcell.util.DataAccessException) FileNotFoundException(java.io.FileNotFoundException) XmlParseException(cbit.vcell.xml.XmlParseException) IOException(java.io.IOException) DataAccessException(org.vcell.util.DataAccessException) ExpressionException(cbit.vcell.parser.ExpressionException) MathException(cbit.vcell.math.MathException)

Example 44 with VCImage

use of cbit.image.VCImage in project vcell by virtualcell.

the class SBMLExporter method addGeometry.

private void addGeometry() throws SbmlException {
    SpatialModelPlugin mplugin = (SpatialModelPlugin) sbmlModel.getPlugin(SBMLUtils.SBML_SPATIAL_NS_PREFIX);
    // Creates a geometry object via SpatialModelPlugin object.
    org.sbml.jsbml.ext.spatial.Geometry sbmlGeometry = mplugin.createGeometry();
    sbmlGeometry.setCoordinateSystem(GeometryKind.cartesian);
    sbmlGeometry.setSpatialId("vcell");
    Geometry vcGeometry = getSelectedSimContext().getGeometry();
    Model vcModel = getSelectedSimContext().getModel();
    // 
    // list of CoordinateComponents : 1 if geometry is 1-d, 2 if geometry is 2-d, 3 if geometry is 3-d
    // 
    int dimension = vcGeometry.getDimension();
    Extent vcExtent = vcGeometry.getExtent();
    Origin vcOrigin = vcGeometry.getOrigin();
    // add x coordinate component
    CoordinateComponent xComp = sbmlGeometry.createCoordinateComponent();
    xComp.setSpatialId(vcModel.getX().getName());
    xComp.setType(CoordinateKind.cartesianX);
    final UnitDefinition sbmlUnitDef_length = getOrCreateSBMLUnit(vcModel.getUnitSystem().getLengthUnit());
    xComp.setUnits(sbmlUnitDef_length);
    Boundary minX = new Boundary();
    xComp.setBoundaryMinimum(minX);
    minX.setSpatialId("Xmin");
    minX.setValue(vcOrigin.getX());
    Boundary maxX = new Boundary();
    xComp.setBoundaryMaximum(maxX);
    maxX.setSpatialId("Xmax");
    maxX.setValue(vcOrigin.getX() + (vcExtent.getX()));
    org.sbml.jsbml.Parameter pX = sbmlModel.createParameter();
    pX.setId(vcModel.getX().getName());
    pX.setValue(0.0);
    pX.setConstant(false);
    pX.setUnits(sbmlUnitDef_length);
    SpatialParameterPlugin spPluginPx = (SpatialParameterPlugin) pX.getPlugin(SBMLUtils.SBML_SPATIAL_NS_PREFIX);
    SpatialSymbolReference spSymRefPx = new SpatialSymbolReference();
    spPluginPx.setParamType(spSymRefPx);
    spSymRefPx.setSpatialRef(xComp.getSpatialId());
    // add y coordinate component
    if (dimension == 2 || dimension == 3) {
        CoordinateComponent yComp = sbmlGeometry.createCoordinateComponent();
        yComp.setSpatialId(vcModel.getY().getName());
        yComp.setType(CoordinateKind.cartesianY);
        yComp.setUnits(sbmlUnitDef_length);
        Boundary minY = new Boundary();
        yComp.setBoundaryMinimum(minY);
        minY.setSpatialId("Ymin");
        minY.setValue(vcOrigin.getY());
        Boundary maxY = new Boundary();
        yComp.setBoundaryMaximum(maxY);
        maxY.setSpatialId("Ymax");
        maxY.setValue(vcOrigin.getY() + (vcExtent.getY()));
        org.sbml.jsbml.Parameter pY = sbmlModel.createParameter();
        pY.setId(vcModel.getY().getName());
        pY.setValue(0.0);
        pY.setConstant(false);
        pY.setUnits(sbmlUnitDef_length);
        SpatialParameterPlugin spPluginPy = (SpatialParameterPlugin) pY.getPlugin(SBMLUtils.SBML_SPATIAL_NS_PREFIX);
        SpatialSymbolReference spSymRefPy = new SpatialSymbolReference();
        spPluginPy.setParamType(spSymRefPy);
        spSymRefPy.setSpatialRef(yComp.getSpatialId());
    }
    // add z coordinate component
    if (dimension == 3) {
        CoordinateComponent zComp = sbmlGeometry.createCoordinateComponent();
        zComp.setSpatialId(vcModel.getZ().getName());
        zComp.setType(CoordinateKind.cartesianZ);
        zComp.setUnits(sbmlUnitDef_length);
        Boundary minZ = new Boundary();
        zComp.setBoundaryMinimum(minZ);
        minZ.setSpatialId("Zmin");
        minZ.setValue(vcOrigin.getZ());
        Boundary maxZ = new Boundary();
        zComp.setBoundaryMaximum(maxZ);
        maxZ.setSpatialId("Zmax");
        maxZ.setValue(vcOrigin.getZ() + (vcExtent.getZ()));
        org.sbml.jsbml.Parameter pZ = sbmlModel.createParameter();
        pZ.setId(vcModel.getZ().getName());
        pZ.setValue(0.0);
        pZ.setConstant(false);
        pZ.setUnits(sbmlUnitDef_length);
        SpatialParameterPlugin spPluginPz = (SpatialParameterPlugin) pZ.getPlugin(SBMLUtils.SBML_SPATIAL_NS_PREFIX);
        SpatialSymbolReference spSymRefPz = new SpatialSymbolReference();
        spPluginPz.setParamType(spSymRefPz);
        spSymRefPz.setSpatialRef(zComp.getSpatialId());
    }
    // 
    // list of compartmentMappings : VC structureMappings
    // 
    GeometryContext vcGeoContext = getSelectedSimContext().getGeometryContext();
    StructureMapping[] vcStrucMappings = vcGeoContext.getStructureMappings();
    for (int i = 0; i < vcStrucMappings.length; i++) {
        StructureMapping vcStructMapping = vcStrucMappings[i];
        String structName = vcStructMapping.getStructure().getName();
        Compartment comp = sbmlModel.getCompartment(TokenMangler.mangleToSName(structName));
        SpatialCompartmentPlugin cplugin = (SpatialCompartmentPlugin) comp.getPlugin(SBMLUtils.SBML_SPATIAL_NS_PREFIX);
        GeometryClass gc = vcStructMapping.getGeometryClass();
        if (!goodPointer(gc, GeometryClass.class, structName)) {
            continue;
        }
        CompartmentMapping compMapping = new CompartmentMapping();
        cplugin.setCompartmentMapping(compMapping);
        String geomClassName = gc.getName();
        String id = TokenMangler.mangleToSName(geomClassName + structName);
        compMapping.setSpatialId(id);
        compMapping.setDomainType(TokenMangler.mangleToSName(DOMAIN_TYPE_PREFIX + geomClassName));
        try {
            StructureMappingParameter usp = vcStructMapping.getUnitSizeParameter();
            Expression e = usp.getExpression();
            if (goodPointer(e, Expression.class, id)) {
                compMapping.setUnitSize(e.evaluateConstant());
            }
        } catch (ExpressionException e) {
            e.printStackTrace(System.out);
            throw new RuntimeException("Unable to create compartment mapping for structureMapping '" + compMapping.getId() + "' : " + e.getMessage());
        }
    }
    // 
    // list of domain types : subvolumes and surface classes from VC
    // 
    boolean bAnyAnalyticSubvolumes = false;
    boolean bAnyImageSubvolumes = false;
    boolean bAnyCSGSubvolumes = false;
    GeometryClass[] vcGeomClasses = vcGeometry.getGeometryClasses();
    int numSubVols = 0;
    for (int i = 0; i < vcGeomClasses.length; i++) {
        DomainType domainType = sbmlGeometry.createDomainType();
        domainType.setSpatialId(DOMAIN_TYPE_PREFIX + vcGeomClasses[i].getName());
        if (vcGeomClasses[i] instanceof SubVolume) {
            if (((SubVolume) vcGeomClasses[i]) instanceof AnalyticSubVolume) {
                bAnyAnalyticSubvolumes = true;
            } else if (((SubVolume) vcGeomClasses[i]) instanceof ImageSubVolume) {
                bAnyImageSubvolumes = true;
            } else if (((SubVolume) vcGeomClasses[i]) instanceof CSGObject) {
                bAnyCSGSubvolumes = true;
            }
            domainType.setSpatialDimensions(3);
            numSubVols++;
        } else if (vcGeomClasses[i] instanceof SurfaceClass) {
            domainType.setSpatialDimensions(2);
        }
    }
    // 
    // list of domains, adjacent domains : from VC geometricRegions
    // 
    GeometrySurfaceDescription vcGSD = vcGeometry.getGeometrySurfaceDescription();
    if (vcGSD.getRegionImage() == null) {
        try {
            vcGSD.updateAll();
        } catch (Exception e) {
            e.printStackTrace(System.out);
            throw new RuntimeException("Unable to generate region images for geometry");
        }
    }
    GeometricRegion[] vcGeometricRegions = vcGSD.getGeometricRegions();
    ISize sampleSize = vcGSD.getVolumeSampleSize();
    int numX = sampleSize.getX();
    int numY = sampleSize.getY();
    int numZ = sampleSize.getZ();
    double ox = vcOrigin.getX();
    double oy = vcOrigin.getY();
    double oz = vcOrigin.getZ();
    RegionInfo[] regionInfos = vcGSD.getRegionImage().getRegionInfos();
    for (int i = 0; i < vcGeometricRegions.length; i++) {
        // domains
        Domain domain = sbmlGeometry.createDomain();
        domain.setSpatialId(vcGeometricRegions[i].getName());
        if (vcGeometricRegions[i] instanceof VolumeGeometricRegion) {
            domain.setDomainType(DOMAIN_TYPE_PREFIX + ((VolumeGeometricRegion) vcGeometricRegions[i]).getSubVolume().getName());
            // 
            // get a list of interior points ... should probably use the distance map to find a point
            // furthest inside (or several points associated with the morphological skeleton).
            // 
            InteriorPoint interiorPt = domain.createInteriorPoint();
            int regionID = ((VolumeGeometricRegion) vcGeometricRegions[i]).getRegionID();
            boolean bFound = false;
            int regInfoIndx = 0;
            for (int j = 0; j < regionInfos.length; j++) {
                regInfoIndx = j;
                if (regionInfos[j].getRegionIndex() == regionID) {
                    int volIndx = 0;
                    for (int z = 0; z < numZ && !bFound; z++) {
                        for (int y = 0; y < numY && !bFound; y++) {
                            for (int x = 0; x < numX && !bFound; x++) {
                                if (regionInfos[j].isIndexInRegion(volIndx)) {
                                    bFound = true;
                                    double unit_z = (numZ > 1) ? ((double) z) / (numZ - 1) : 0.5;
                                    double coordZ = oz + vcExtent.getZ() * unit_z;
                                    double unit_y = (numY > 1) ? ((double) y) / (numY - 1) : 0.5;
                                    double coordY = oy + vcExtent.getY() * unit_y;
                                    double unit_x = (numX > 1) ? ((double) x) / (numX - 1) : 0.5;
                                    double coordX = ox + vcExtent.getX() * unit_x;
                                    interiorPt.setCoord1(coordX);
                                    interiorPt.setCoord2(coordY);
                                    interiorPt.setCoord3(coordZ);
                                }
                                volIndx++;
                            }
                        // end - for x
                        }
                    // end - for y
                    }
                // end - for z
                }
            // end if
            }
            // end for regionInfos
            if (!bFound) {
                throw new RuntimeException("Unable to find interior point for region '" + regionInfos[regInfoIndx].toString());
            }
        } else if (vcGeometricRegions[i] instanceof SurfaceGeometricRegion) {
            SurfaceGeometricRegion vcSurfaceGeomReg = (SurfaceGeometricRegion) vcGeometricRegions[i];
            GeometricRegion geomRegion0 = vcSurfaceGeomReg.getAdjacentGeometricRegions()[0];
            GeometricRegion geomRegion1 = vcSurfaceGeomReg.getAdjacentGeometricRegions()[1];
            SurfaceClass surfaceClass = vcGSD.getSurfaceClass(((VolumeGeometricRegion) geomRegion0).getSubVolume(), ((VolumeGeometricRegion) geomRegion1).getSubVolume());
            domain.setDomainType(DOMAIN_TYPE_PREFIX + surfaceClass.getName());
            // adjacent domains : 2 adjacent domain objects for each surfaceClass in VC.
            // adjacent domain 1
            GeometricRegion adjGeomRegion0 = vcSurfaceGeomReg.getAdjacentGeometricRegions()[0];
            GeometricRegion adjGeomRegion1 = vcSurfaceGeomReg.getAdjacentGeometricRegions()[1];
            AdjacentDomains adjDomain = new AdjacentDomains();
            adjDomain.setSpatialId(TokenMangler.mangleToSName(vcSurfaceGeomReg.getName() + "_" + adjGeomRegion0.getName()));
            adjDomain.setDomain1(vcSurfaceGeomReg.getName());
            adjDomain.setDomain2(adjGeomRegion0.getName());
            sbmlGeometry.addAdjacentDomain(adjDomain);
            // adj domain 2
            adjDomain = new AdjacentDomains();
            adjDomain.setSpatialId(TokenMangler.mangleToSName(vcSurfaceGeomReg.getName() + "_" + adjGeomRegion1.getName()));
            adjDomain.setDomain1(vcSurfaceGeomReg.getName());
            adjDomain.setDomain2(adjGeomRegion1.getName());
            sbmlGeometry.addAdjacentDomain(adjDomain);
        }
    }
    // 
    if (bAnyAnalyticSubvolumes && !bAnyImageSubvolumes && !bAnyCSGSubvolumes) {
        AnalyticGeometry sbmlAnalyticGeomDefinition = sbmlGeometry.createAnalyticGeometry();
        sbmlAnalyticGeomDefinition.setSpatialId(TokenMangler.mangleToSName("Analytic_" + vcGeometry.getName()));
        sbmlAnalyticGeomDefinition.setIsActive(true);
        for (int i = 0; i < vcGeomClasses.length; i++) {
            if (vcGeomClasses[i] instanceof AnalyticSubVolume) {
                AnalyticVolume analyticVol = sbmlAnalyticGeomDefinition.createAnalyticVolume();
                analyticVol.setSpatialId(vcGeomClasses[i].getName());
                analyticVol.setDomainType(DOMAIN_TYPE_PREFIX + vcGeomClasses[i].getName());
                analyticVol.setFunctionType(FunctionKind.layered);
                analyticVol.setOrdinal(numSubVols - (i + 1));
                Expression expr = ((AnalyticSubVolume) vcGeomClasses[i]).getExpression();
                try {
                    String mathMLStr = ExpressionMathMLPrinter.getMathML(expr, true, MathType.BOOLEAN);
                    ASTNode mathMLNode = ASTNode.readMathMLFromString(mathMLStr);
                    analyticVol.setMath(mathMLNode);
                } catch (Exception e) {
                    e.printStackTrace(System.out);
                    throw new RuntimeException("Error converting VC subvolume expression to mathML" + e.getMessage());
                }
            }
        }
    }
    // 
    if (!bAnyAnalyticSubvolumes && !bAnyImageSubvolumes && bAnyCSGSubvolumes) {
        CSGeometry sbmlCSGeomDefinition = new CSGeometry();
        sbmlGeometry.addGeometryDefinition(sbmlCSGeomDefinition);
        sbmlCSGeomDefinition.setSpatialId(TokenMangler.mangleToSName("CSG_" + vcGeometry.getName()));
        for (int i = 0; i < vcGeomClasses.length; i++) {
            if (vcGeomClasses[i] instanceof CSGObject) {
                CSGObject vcellCSGObject = (CSGObject) vcGeomClasses[i];
                org.sbml.jsbml.ext.spatial.CSGObject sbmlCSGObject = new org.sbml.jsbml.ext.spatial.CSGObject();
                sbmlCSGeomDefinition.addCSGObject(sbmlCSGObject);
                sbmlCSGObject.setSpatialId(vcellCSGObject.getName());
                sbmlCSGObject.setDomainType(DOMAIN_TYPE_PREFIX + vcellCSGObject.getName());
                // the ordinal should the the least for the default/background subVolume
                sbmlCSGObject.setOrdinal(numSubVols - (i + 1));
                org.sbml.jsbml.ext.spatial.CSGNode sbmlcsgNode = getSBMLCSGNode(vcellCSGObject.getRoot());
                sbmlCSGObject.setCSGNode(sbmlcsgNode);
            }
        }
    }
    // 
    // add "Segmented" and "DistanceMap" SampledField Geometries
    // 
    final boolean bVCGeometryIsImage = bAnyImageSubvolumes && !bAnyAnalyticSubvolumes && !bAnyCSGSubvolumes;
    // 55if (bAnyAnalyticSubvolumes || bAnyImageSubvolumes || bAnyCSGSubvolumes){
    if (bVCGeometryIsImage) {
        // 
        // add "Segmented" SampledFieldGeometry
        // 
        SampledFieldGeometry segmentedImageSampledFieldGeometry = sbmlGeometry.createSampledFieldGeometry();
        segmentedImageSampledFieldGeometry.setSpatialId(TokenMangler.mangleToSName("SegmentedImage_" + vcGeometry.getName()));
        segmentedImageSampledFieldGeometry.setIsActive(true);
        // 55boolean bVCGeometryIsImage = bAnyImageSubvolumes && !bAnyAnalyticSubvolumes && !bAnyCSGSubvolumes;
        Geometry vcImageGeometry = null;
        {
            if (bVCGeometryIsImage) {
                // make a resampled image;
                if (dimension == 3) {
                    try {
                        ISize imageSize = vcGeometry.getGeometrySpec().getDefaultSampledImageSize();
                        vcGeometry.precomputeAll(new GeometryThumbnailImageFactoryAWT());
                        vcImageGeometry = RayCaster.resampleGeometry(new GeometryThumbnailImageFactoryAWT(), vcGeometry, imageSize);
                    } catch (Throwable e) {
                        e.printStackTrace(System.out);
                        throw new RuntimeException("Unable to convert the original analytic or constructed solid geometry to image-based geometry : " + e.getMessage());
                    }
                } else {
                    try {
                        vcGeometry.precomputeAll(new GeometryThumbnailImageFactoryAWT(), true, false);
                        GeometrySpec origGeometrySpec = vcGeometry.getGeometrySpec();
                        VCImage newVCImage = origGeometrySpec.getSampledImage().getCurrentValue();
                        // 
                        // construct the new geometry with the sampled VCImage.
                        // 
                        vcImageGeometry = new Geometry(vcGeometry.getName() + "_asImage", newVCImage);
                        vcImageGeometry.getGeometrySpec().setExtent(vcGeometry.getExtent());
                        vcImageGeometry.getGeometrySpec().setOrigin(vcGeometry.getOrigin());
                        vcImageGeometry.setDescription(vcGeometry.getDescription());
                        vcImageGeometry.getGeometrySurfaceDescription().setFilterCutoffFrequency(vcGeometry.getGeometrySurfaceDescription().getFilterCutoffFrequency());
                        vcImageGeometry.precomputeAll(new GeometryThumbnailImageFactoryAWT(), true, true);
                    } catch (Exception e) {
                        e.printStackTrace(System.out);
                        throw new RuntimeException("Unable to convert the original analytic or constructed solid geometry to image-based geometry : " + e.getMessage());
                    }
                }
                GeometryClass[] vcImageGeomClasses = vcImageGeometry.getGeometryClasses();
                for (int j = 0; j < vcImageGeomClasses.length; j++) {
                    if (vcImageGeomClasses[j] instanceof ImageSubVolume) {
                        SampledVolume sampledVol = segmentedImageSampledFieldGeometry.createSampledVolume();
                        sampledVol.setSpatialId(vcGeomClasses[j].getName());
                        sampledVol.setDomainType(DOMAIN_TYPE_PREFIX + vcGeomClasses[j].getName());
                        sampledVol.setSampledValue(((ImageSubVolume) vcImageGeomClasses[j]).getPixelValue());
                    }
                }
                // add sampledField to sampledFieldGeometry
                SampledField segmentedImageSampledField = sbmlGeometry.createSampledField();
                VCImage vcImage = vcImageGeometry.getGeometrySpec().getImage();
                segmentedImageSampledField.setSpatialId("SegmentedImageSampledField");
                segmentedImageSampledField.setNumSamples1(vcImage.getNumX());
                segmentedImageSampledField.setNumSamples2(vcImage.getNumY());
                segmentedImageSampledField.setNumSamples3(vcImage.getNumZ());
                segmentedImageSampledField.setInterpolationType(InterpolationKind.nearestneighbor);
                segmentedImageSampledField.setCompression(CompressionKind.uncompressed);
                segmentedImageSampledField.setDataType(DataKind.UINT8);
                segmentedImageSampledFieldGeometry.setSampledField(segmentedImageSampledField.getId());
                try {
                    byte[] vcImagePixelsBytes = vcImage.getPixels();
                    // imageData.setCompression("");
                    StringBuffer sb = new StringBuffer();
                    for (int i = 0; i < vcImagePixelsBytes.length; i++) {
                        int uint8_sample = ((int) vcImagePixelsBytes[i]) & 0xff;
                        sb.append(uint8_sample + " ");
                    }
                    segmentedImageSampledField.setSamplesLength(vcImage.getNumXYZ());
                    segmentedImageSampledField.setSamples(sb.toString().trim());
                } catch (ImageException e) {
                    e.printStackTrace(System.out);
                    throw new RuntimeException("Unable to export image from VCell to SBML : " + e.getMessage());
                }
            }
        }
    /*		
		//
		// add "DistanceMap" SampledFieldGeometry if there are exactly two subvolumes (else need more fields) and geometry is 3d.
		//
		if (numSubVols==2 && dimension == 3){
			SignedDistanceMap[] distanceMaps = null;
			try {
				distanceMaps = DistanceMapGenerator.computeDistanceMaps(vcImageGeometry, vcImageGeometry.getGeometrySpec().getImage(), false, false);
			} catch (ImageException e) {
				e.printStackTrace(System.out);
				System.err.println("Unable to export distance map sampled field from VCell to SBML : " + e.getMessage());
				// throw new RuntimeException("Unable to export distance map sampled field from VCell to SBML : " + e.getMessage());
				
				// don't want to throw an exception and stop export because distance map geometry couldn't be exported. 
				// just 'return' from method (since this is the last thing that is being done in this method).
				return;
			}
			//
			// the two distanceMaps should be redundant (one is negation of the other) ... so choose first one for field.
			//
			double[] signedDistances = distanceMaps[0].getSignedDistances();
			SampledFieldGeometry distanceMapSampledFieldGeometry = sbmlGeometry.createSampledFieldGeometry();
			distanceMapSampledFieldGeometry.setSpatialId(TokenMangler.mangleToSName("DistanceMap_"+vcGeometry.getName()));
			SampledField distanceMapSampledField = distanceMapSampledFieldGeometry.createSampledField();
			distanceMapSampledField.setSpatialId("DistanceMapSampledField");
			distanceMapSampledField.setNumSamples1(distanceMaps[0].getSamplesX().length);
			distanceMapSampledField.setNumSamples2(distanceMaps[0].getSamplesY().length);
			distanceMapSampledField.setNumSamples3(distanceMaps[0].getSamplesZ().length);
			distanceMapSampledField.setDataType("real");
System.err.println("do we need distanceMapSampleField.setDataType()?");
			distanceMapSampledField.setInterpolationType("linear");
			ImageData distanceMapImageData = distanceMapSampledField.createImageData();
			distanceMapImageData.setDataType("int16");
System.err.println("should be:\n  distanceMapImageData.setDataType(\"float32\")");
//					distanceMapImageData.setCompression("");

			double maxAbsValue = 0;
			for (int i = 0; i < signedDistances.length; i++) {
				maxAbsValue = Math.max(maxAbsValue,Math.abs(signedDistances[i]));
			}
			if (maxAbsValue==0.0){
				throw new RuntimeException("computed distance map all zeros");
			}
			double scale = (Short.MAX_VALUE-1)/maxAbsValue;
			int[] scaledIntegerDistanceMap = new int[signedDistances.length];
			for (int i = 0; i < signedDistances.length; i++) {
				scaledIntegerDistanceMap[i] = (int)(scale * signedDistances[i]);
			}
			distanceMapImageData.setSamples(scaledIntegerDistanceMap, signedDistances.length);
System.err.println("should be:\n  distanceMapImageData.setSamples((float[])signedDistances,signedDistances.length)");
			SampledVolume sampledVol = distanceMapSampledFieldGeometry.createSampledVolume();
			sampledVol.setSpatialId(distanceMaps[0].getInsideSubvolumeName());
			sampledVol.setDomainType(DOMAIN_TYPE_PREFIX+distanceMaps[0].getInsideSubvolumeName());
			sampledVol.setSampledValue(255);
			sampledVol = distanceMapSampledFieldGeometry.createSampledVolume();
			sampledVol.setSpatialId(distanceMaps[1].getInsideSubvolumeName());
			sampledVol.setDomainType(DOMAIN_TYPE_PREFIX+distanceMaps[1].getInsideSubvolumeName());
			sampledVol.setSampledValue(1);
		}
*/
    }
// 
// add "SurfaceMesh" ParametricGeometry
// 
// if (bAnyAnalyticSubvolumes || bAnyImageSubvolumes || bAnyCSGSubvolumes){
// ParametricGeometry sbmlParametricGeomDefinition = sbmlGeometry.createParametricGeometry();
// sbmlParametricGeomDefinition.setSpatialId(TokenMangler.mangleToSName("SurfaceMesh_"+vcGeometry.getName()));
// xxxx
// }
}
Also used : Origin(org.vcell.util.Origin) CompartmentMapping(org.sbml.jsbml.ext.spatial.CompartmentMapping) Compartment(org.sbml.jsbml.Compartment) SpatialParameterPlugin(org.sbml.jsbml.ext.spatial.SpatialParameterPlugin) StructureMappingParameter(cbit.vcell.mapping.StructureMapping.StructureMappingParameter) AnalyticGeometry(org.sbml.jsbml.ext.spatial.AnalyticGeometry) ExpressionException(cbit.vcell.parser.ExpressionException) Boundary(org.sbml.jsbml.ext.spatial.Boundary) GeometrySpec(cbit.vcell.geometry.GeometrySpec) DomainType(org.sbml.jsbml.ext.spatial.DomainType) SampledVolume(org.sbml.jsbml.ext.spatial.SampledVolume) SubVolume(cbit.vcell.geometry.SubVolume) ImageSubVolume(cbit.vcell.geometry.ImageSubVolume) AnalyticSubVolume(cbit.vcell.geometry.AnalyticSubVolume) GeometryContext(cbit.vcell.mapping.GeometryContext) SpatialCompartmentPlugin(org.sbml.jsbml.ext.spatial.SpatialCompartmentPlugin) CoordinateComponent(org.sbml.jsbml.ext.spatial.CoordinateComponent) SimulationContext(cbit.vcell.mapping.SimulationContext) SpeciesContext(cbit.vcell.model.SpeciesContext) GeometryContext(cbit.vcell.mapping.GeometryContext) VolumeGeometricRegion(cbit.vcell.geometry.surface.VolumeGeometricRegion) SurfaceGeometricRegion(cbit.vcell.geometry.surface.SurfaceGeometricRegion) VolumeGeometricRegion(cbit.vcell.geometry.surface.VolumeGeometricRegion) GeometricRegion(cbit.vcell.geometry.surface.GeometricRegion) SpatialSymbolReference(org.sbml.jsbml.ext.spatial.SpatialSymbolReference) AnalyticVolume(org.sbml.jsbml.ext.spatial.AnalyticVolume) InteriorPoint(org.sbml.jsbml.ext.spatial.InteriorPoint) SampledField(org.sbml.jsbml.ext.spatial.SampledField) Domain(org.sbml.jsbml.ext.spatial.Domain) AnalyticSubVolume(cbit.vcell.geometry.AnalyticSubVolume) GeometryClass(cbit.vcell.geometry.GeometryClass) ImageException(cbit.image.ImageException) GeometrySurfaceDescription(cbit.vcell.geometry.surface.GeometrySurfaceDescription) Extent(org.vcell.util.Extent) SurfaceClass(cbit.vcell.geometry.SurfaceClass) ISize(org.vcell.util.ISize) CSGeometry(org.sbml.jsbml.ext.spatial.CSGeometry) RegionInfo(cbit.vcell.geometry.RegionImage.RegionInfo) VCImage(cbit.image.VCImage) StructureMapping(cbit.vcell.mapping.StructureMapping) GeometryThumbnailImageFactoryAWT(cbit.vcell.geometry.GeometryThumbnailImageFactoryAWT) ASTNode(org.sbml.jsbml.ASTNode) CSGObject(cbit.vcell.geometry.CSGObject) VCUnitDefinition(cbit.vcell.units.VCUnitDefinition) UnitDefinition(org.sbml.jsbml.UnitDefinition) ImageSubVolume(cbit.vcell.geometry.ImageSubVolume) SurfaceGeometricRegion(cbit.vcell.geometry.surface.SurfaceGeometricRegion) SampledFieldGeometry(org.sbml.jsbml.ext.spatial.SampledFieldGeometry) SpatialModelPlugin(org.sbml.jsbml.ext.spatial.SpatialModelPlugin) InteriorPoint(org.sbml.jsbml.ext.spatial.InteriorPoint) XMLStreamException(javax.xml.stream.XMLStreamException) SbmlException(org.vcell.sbml.SbmlException) ImageException(cbit.image.ImageException) SBMLException(org.sbml.jsbml.SBMLException) ExpressionException(cbit.vcell.parser.ExpressionException) AdjacentDomains(org.sbml.jsbml.ext.spatial.AdjacentDomains) Geometry(cbit.vcell.geometry.Geometry) SampledFieldGeometry(org.sbml.jsbml.ext.spatial.SampledFieldGeometry) AnalyticGeometry(org.sbml.jsbml.ext.spatial.AnalyticGeometry) CSGeometry(org.sbml.jsbml.ext.spatial.CSGeometry) Expression(cbit.vcell.parser.Expression) Model(cbit.vcell.model.Model) BioModel(cbit.vcell.biomodel.BioModel)

Example 45 with VCImage

use of cbit.image.VCImage in project vcell by virtualcell.

the class ServerDocumentManager method saveSimulation.

/**
 * Insert the method's description here.
 * Creation date: (10/28/00 12:08:30 AM)
 * @deprecated for testing purposes only.
 */
public String saveSimulation(QueryHashtable dbc, User user, String simulationXML, boolean bForceIndependent) throws DataAccessException, java.sql.SQLException, java.beans.PropertyVetoException, cbit.vcell.xml.XmlParseException {
    // 
    // this invokes "update" on the database layer
    // 
    Simulation simulation = XmlHelper.XMLToSim(simulationXML);
    forceDeepDirtyIfForeign(user, simulation);
    Version oldVersion = simulation.getVersion();
    Simulation origSimulation = null;
    if (oldVersion != null) {
        try {
            origSimulation = dbServer.getDBTopLevel().getSimulation(dbc, user, oldVersion.getVersionKey());
        } catch (ObjectNotFoundException e) {
        }
    }
    boolean bSomethingChanged = false;
    // 
    // UPDATE AND SUBSTITUTE FROM BOTTOM UP
    // 
    // Image->Geometry
    // Geometry->MathDescription
    // MathDescription->Simulation
    // 
    // 
    // if this simulation has an image:
    // save if necessary (only once) and store saved instance in hashTable
    // 
    Hashtable<Versionable, Versionable> memoryToDatabaseHash = new Hashtable<Versionable, Versionable>();
    {
        VCImage memoryImage = simulation.getMathDescription().getGeometry().getGeometrySpec().getImage();
        if (memoryImage != null) {
            // defaults to unchanged
            memoryToDatabaseHash.put(memoryImage, memoryImage);
            if (memoryImage.getKey() != null && memoryImage.getVersion().getName().equals(memoryImage.getName())) {
                // 
                // if image had previously been saved, not been forced 'dirty', and name not changed
                // compare with original image to see if "update" is required.
                // 
                VCImage databaseImage = null;
                if (origSimulation != null) {
                    VCImage origImage = origSimulation.getMathDescription().getGeometry().getGeometrySpec().getImage();
                    if (origImage != null && origImage.getKey().equals(memoryImage.getKey())) {
                        databaseImage = origImage;
                    }
                }
                if (databaseImage == null) {
                    // 
                    // saved image not found in origMathModel (too bad), get from database.
                    // 
                    databaseImage = dbServer.getDBTopLevel().getVCImage(dbc, user, memoryImage.getKey(), false);
                }
                if (databaseImage != null && !databaseImage.compareEqual(memoryImage)) {
                    KeyValue updatedImageKey = dbServer.getDBTopLevel().updateVersionable(user, memoryImage, false, true);
                    VCImage updatedImage = dbServer.getDBTopLevel().getVCImage(dbc, user, updatedImageKey, false);
                    memoryToDatabaseHash.put(memoryImage, updatedImage);
                    bSomethingChanged = true;
                }
            } else {
                // 
                // Image hasn't been saved, has been renamed, or has been forced 'dirty'
                // insert it with a unique name
                // 
                int count = 0;
                fixNullImageName(memoryImage);
                while (dbServer.getDBTopLevel().isNameUsed(user, VersionableType.VCImage, memoryImage.getName(), true)) {
                    try {
                        memoryImage.setName(TokenMangler.getNextRandomToken(memoryImage.getName()));
                    } catch (java.beans.PropertyVetoException e) {
                        e.printStackTrace(System.out);
                    }
                    if (count++ > 5) {
                        throw new DataAccessException("failed to find unique image name '" + memoryImage.getName() + "' is last name tried");
                    }
                }
                KeyValue updatedImageKey = dbServer.getDBTopLevel().insertVersionable(user, memoryImage, memoryImage.getName(), false, true);
                VCImage updatedImage = dbServer.getDBTopLevel().getVCImage(dbc, user, updatedImageKey, false);
                memoryToDatabaseHash.put(memoryImage, updatedImage);
                bSomethingChanged = true;
            }
        }
    }
    // 
    // for the Geometry:
    // substitute saved Image into Geometry and
    // save Geometry if necessary (only once) and store saved instance in hashtable.
    // 
    {
        Geometry memoryGeometry = simulation.getMathDescription().getGeometry();
        // defaults to unchanged
        memoryToDatabaseHash.put(memoryGeometry, memoryGeometry);
        boolean bMustSaveGeometry = false;
        VCImage geometryImage = memoryGeometry.getGeometrySpec().getImage();
        if (geometryImage != null && memoryToDatabaseHash.get(geometryImage) != geometryImage) {
            // 
            // image had changed and was saved, load saved image into geometry and force a save of this geometry.
            // 
            memoryGeometry.getGeometrySpec().setImage((VCImage) memoryToDatabaseHash.get(geometryImage));
            geometryImage = (VCImage) memoryToDatabaseHash.get(geometryImage);
            bMustSaveGeometry = true;
        }
        if (memoryGeometry.getKey() != null && memoryGeometry.getVersion().getName().equals(memoryGeometry.getName())) {
            if (!bMustSaveGeometry) {
                // 
                // if geometry had previously been saved, not been forced 'dirty', and name not changed
                // compare with original geometry to see if "update" is required.
                // 
                Geometry databaseGeometry = null;
                if (origSimulation != null) {
                    Geometry origGeometry = origSimulation.getMathDescription().getGeometry();
                    if (origGeometry.getKey().equals(memoryGeometry.getKey())) {
                        databaseGeometry = origGeometry;
                    }
                }
                if (databaseGeometry == null) {
                    // 
                    // saved geometry not found in origMathModel (too bad), get from database.
                    // 
                    databaseGeometry = dbServer.getDBTopLevel().getGeometry(dbc, user, memoryGeometry.getKey(), false);
                }
                if (databaseGeometry != null && !databaseGeometry.compareEqual(memoryGeometry)) {
                    bMustSaveGeometry = true;
                }
            }
            if (bMustSaveGeometry) {
                KeyValue updatedImageKey = (geometryImage != null) ? (geometryImage.getKey()) : (null);
                KeyValue updatedGeometryKey = dbServer.getDBTopLevel().updateVersionable(dbc, user, memoryGeometry, updatedImageKey, false, true);
                Geometry updatedGeometry = dbServer.getDBTopLevel().getGeometry(dbc, user, updatedGeometryKey, false);
                memoryToDatabaseHash.put(memoryGeometry, updatedGeometry);
                bSomethingChanged = true;
            }
        } else {
            // 
            // Geometry hasn't been saved, has been renamed, or has been forced 'dirty'
            // insert it with a unique name
            // 
            int count = 0;
            while (dbServer.getDBTopLevel().isNameUsed(user, VersionableType.Geometry, memoryGeometry.getName(), true)) {
                try {
                    memoryGeometry.setName(TokenMangler.getNextRandomToken(memoryGeometry.getName()));
                } catch (java.beans.PropertyVetoException e) {
                    e.printStackTrace(System.out);
                }
                if (count++ > 5) {
                    throw new DataAccessException("failed to find unique geometry name '" + memoryGeometry.getName() + "' is last name tried");
                }
            }
            KeyValue updatedImageKey = (geometryImage != null) ? (geometryImage.getKey()) : (null);
            KeyValue updatedGeometryKey = dbServer.getDBTopLevel().insertVersionable(dbc, user, memoryGeometry, updatedImageKey, memoryGeometry.getName(), false, true);
            Geometry updatedGeometry = dbServer.getDBTopLevel().getGeometry(dbc, user, updatedGeometryKey, false);
            memoryToDatabaseHash.put(memoryGeometry, updatedGeometry);
            bSomethingChanged = true;
        }
    }
    // 
    // for the MathDescription:
    // substitute saved geometry into MathDescription
    // save MathDescription if necessary (only once) and store saved instance in hashtable.
    // 
    MathCompareResults mathCompareResults = null;
    {
        MathDescription memoryMathDescription = simulation.getMathDescription();
        // defaults to unchanged
        memoryToDatabaseHash.put(memoryMathDescription, memoryMathDescription);
        boolean bMustSaveMathDescription = false;
        Geometry scGeometry = memoryMathDescription.getGeometry();
        if (scGeometry != null && memoryToDatabaseHash.get(scGeometry) != scGeometry) {
            // 
            // geometry had changed and was saved, load saved geometry into SimulationContext (and it's MathDescription) and force a save of this SimulationContext.
            // 
            memoryMathDescription.setGeometry((Geometry) memoryToDatabaseHash.get(scGeometry));
            bMustSaveMathDescription = true;
        }
        if (memoryMathDescription.getKey() != null && memoryMathDescription.getVersion().getName().equals(memoryMathDescription.getName())) {
            if (!bMustSaveMathDescription) {
                // 
                // if MathDescription had previously been saved, not been forced 'dirty', and name not changed
                // compare with original MathDescription to see if "update" is required.
                // 
                MathDescription databaseMathDescription = null;
                if (origSimulation != null) {
                    MathDescription origMathDescription = origSimulation.getMathDescription();
                    if (origMathDescription.getKey().equals(memoryMathDescription.getKey())) {
                        databaseMathDescription = origMathDescription;
                    }
                }
                if (databaseMathDescription == null) {
                    // 
                    // saved mathDescription not found in origMathModel (too bad), get from database.
                    // 
                    databaseMathDescription = dbServer.getDBTopLevel().getMathDescription(dbc, user, memoryMathDescription.getKey());
                }
                if (databaseMathDescription != null) {
                    mathCompareResults = MathDescription.testEquivalency(SimulationSymbolTable.createMathSymbolTableFactory(), memoryMathDescription, databaseMathDescription);
                    if (!mathCompareResults.decision.equals(Decision.MathEquivalent_SAME_MATHDESC_AS_IN_DB)) {
                        bMustSaveMathDescription = true;
                    }
                }
            }
            if (bMustSaveMathDescription) {
                KeyValue updatedGeometryKey = memoryMathDescription.getGeometry().getKey();
                KeyValue updatedMathDescriptionKey = dbServer.getDBTopLevel().updateVersionable(user, memoryMathDescription, updatedGeometryKey, false, true);
                MathDescription updatedMathDescription = dbServer.getDBTopLevel().getMathDescription(dbc, user, updatedMathDescriptionKey);
                memoryToDatabaseHash.put(memoryMathDescription, updatedMathDescription);
                bSomethingChanged = true;
            }
        } else {
            // 
            // MathDescription hasn't been saved, has been renamed, or has been forced 'dirty'
            // insert it with a any name (doens't have to be unique ... mathDescription is not a top-level versionable).
            // 
            KeyValue updatedGeometryKey = memoryMathDescription.getGeometry().getKey();
            KeyValue updatedMathDescriptionKey = dbServer.getDBTopLevel().insertVersionable(user, memoryMathDescription, updatedGeometryKey, memoryMathDescription.getName(), false, true);
            MathDescription updatedMathDescription = dbServer.getDBTopLevel().getMathDescription(dbc, user, updatedMathDescriptionKey);
            memoryToDatabaseHash.put(memoryMathDescription, updatedMathDescription);
            bSomethingChanged = true;
        }
    }
    // 
    // for each Simulation in document:
    // substitute saved MathDescriptions into Simulation and
    // save Simulation if necessary (only once) and store saved instance in hashtable.
    // 
    Simulation memorySimulation = simulation;
    // 
    // didn't evaluate this Simulation yet.
    // 
    // defaults to unchanged
    memoryToDatabaseHash.put(memorySimulation, memorySimulation);
    boolean bMustSaveSimulation = false;
    MathDescription simMathDescription = memorySimulation.getMathDescription();
    if (simMathDescription != null && memoryToDatabaseHash.get(simMathDescription) != simMathDescription) {
        if (memoryToDatabaseHash.get(simMathDescription) != null) {
            // make sure mathDescription hasn't already propagated (newer math won't be in hashtable)
            // 
            // mathDescription had changed and was saved, load saved mathDescription into SimulationContext (and force a save)
            // 
            memorySimulation.setMathDescription((MathDescription) memoryToDatabaseHash.get(simMathDescription));
            bMustSaveSimulation = true;
        }
    }
    Simulation databaseSimulation = null;
    // 
    if (memorySimulation.getKey() != null) {
        databaseSimulation = origSimulation;
        if (databaseSimulation != null && !databaseSimulation.compareEqual(memorySimulation)) {
            bMustSaveSimulation = true;
        }
        if (!memorySimulation.getVersion().getName().equals(memorySimulation.getName())) {
            // name was changed.
            bMustSaveSimulation = true;
        }
    } else {
        // never been saved.
        bMustSaveSimulation = true;
    }
    if (bMustSaveSimulation) {
        KeyValue updatedMathDescriptionKey = memorySimulation.getMathDescription().getKey();
        KeyValue updatedSimulationKey = null;
        boolean bMathEquivalent = false;
        if (origSimulation != null) {
            bMathEquivalent = !bForceIndependent && Simulation.testEquivalency(memorySimulation, origSimulation, mathCompareResults);
        }
        if (memorySimulation.getKey() != null && memorySimulation.getVersion().getName().equals(memorySimulation.getName())) {
            // name not changed, update simulation (but pass in database Simulation to check for parent-equivalence)
            updatedSimulationKey = dbServer.getDBTopLevel().updateVersionable(user, memorySimulation, updatedMathDescriptionKey, false, bMathEquivalent, true);
        } else {
            // name changed, insert simulation (but pass in database Simulation to check for parent-equivalence)
            updatedSimulationKey = dbServer.getDBTopLevel().insertVersionable(user, memorySimulation, updatedMathDescriptionKey, memorySimulation.getName(), false, bMathEquivalent, true);
        }
        Simulation updatedSimulation = dbServer.getDBTopLevel().getSimulation(dbc, user, updatedSimulationKey);
        memoryToDatabaseHash.put(memorySimulation, updatedSimulation);
        bSomethingChanged = true;
        simulationXML = XmlHelper.simToXML(updatedSimulation);
        return simulationXML;
    } else {
        return simulationXML;
    }
}
Also used : KeyValue(org.vcell.util.document.KeyValue) MathDescription(cbit.vcell.math.MathDescription) Hashtable(java.util.Hashtable) QueryHashtable(cbit.sql.QueryHashtable) VCImage(cbit.image.VCImage) Versionable(org.vcell.util.document.Versionable) PropertyVetoException(java.beans.PropertyVetoException) Geometry(cbit.vcell.geometry.Geometry) Simulation(cbit.vcell.solver.Simulation) Version(org.vcell.util.document.Version) ObjectNotFoundException(org.vcell.util.ObjectNotFoundException) MathCompareResults(cbit.vcell.math.MathCompareResults) DataAccessException(org.vcell.util.DataAccessException)

Aggregations

VCImage (cbit.image.VCImage)54 Geometry (cbit.vcell.geometry.Geometry)22 Extent (org.vcell.util.Extent)20 ISize (org.vcell.util.ISize)19 VCImageUncompressed (cbit.image.VCImageUncompressed)18 ImageException (cbit.image.ImageException)16 PropertyVetoException (java.beans.PropertyVetoException)15 DataAccessException (org.vcell.util.DataAccessException)15 KeyValue (org.vcell.util.document.KeyValue)15 SubVolume (cbit.vcell.geometry.SubVolume)14 Origin (org.vcell.util.Origin)13 RegionImage (cbit.vcell.geometry.RegionImage)11 SurfaceClass (cbit.vcell.geometry.SurfaceClass)11 ObjectNotFoundException (org.vcell.util.ObjectNotFoundException)11 UserCancelException (org.vcell.util.UserCancelException)11 ImageSubVolume (cbit.vcell.geometry.ImageSubVolume)10 Expression (cbit.vcell.parser.Expression)10 VCPixelClass (cbit.image.VCPixelClass)9 BioModel (cbit.vcell.biomodel.BioModel)8 FieldDataFileOperationSpec (cbit.vcell.field.io.FieldDataFileOperationSpec)8