use of cbit.vcell.mapping.StructureMapping in project vcell by virtualcell.
the class ModelUnitConverter method createBioModelWithNewUnitSystem.
public static BioModel createBioModelWithNewUnitSystem(BioModel oldBioModel, ModelUnitSystem newUnitSystem) throws ExpressionException, XmlParseException {
// new BioModel has new unit system applied to all built-in units ... but expressions still need to be corrected (see below).
String biomodelXMLString = XmlHelper.bioModelToXML(oldBioModel);
XMLSource newXMLSource = new XMLSource(biomodelXMLString);
BioModel newBioModel = XmlHelper.XMLToBioModel(newXMLSource, true, newUnitSystem);
Model newModel = newBioModel.getModel();
Model oldModel = oldBioModel.getModel();
for (Parameter p : newBioModel.getModel().getModelParameters()) {
convertVarsWithUnitFactors(oldBioModel.getModel(), newBioModel.getModel(), p);
}
for (ReactionStep reactionStep : newBioModel.getModel().getReactionSteps()) {
SymbolTable oldSymbolTable = oldBioModel.getModel().getReactionStep(reactionStep.getName());
SymbolTable newSymbolTable = reactionStep;
for (Parameter p : reactionStep.getKinetics().getUnresolvedParameters()) {
convertVarsWithUnitFactors(oldSymbolTable, newSymbolTable, p);
}
for (Parameter p : reactionStep.getKinetics().getKineticsParameters()) {
convertVarsWithUnitFactors(oldSymbolTable, newSymbolTable, p);
}
Kinetics kinetics = reactionStep.getKinetics();
KineticsParameter kineticsParameter = null;
if (kinetics.getKineticsParameterFromRole(Kinetics.ROLE_ReactionRate) != null) {
kineticsParameter = kinetics.getKineticsParameterFromRole(Kinetics.ROLE_ReactionRate);
} else if (kinetics.getKineticsParameterFromRole(Kinetics.ROLE_LumpedReactionRate) != null) {
kineticsParameter = kinetics.getKineticsParameterFromRole(Kinetics.ROLE_LumpedReactionRate);
} else {
throw new RuntimeException("Role 'reaction rate' or role 'lumped reaction rate' expected");
}
Expression rateExpression = kineticsParameter.getExpression();
jscl.math.Expression jsclExpression = null;
String jsclExpressionString = rateExpression.infix_JSCL();
try {
jsclExpression = jscl.math.Expression.valueOf(jsclExpressionString);
} catch (jscl.text.ParseException e) {
e.printStackTrace(System.out);
System.out.println("JSCL couldn't parse \"" + jsclExpressionString + "\"");
return null;
}
jscl.math.Generic g1 = jsclExpression.expand().simplify();
Expression newRate = new Expression(SymbolUtils.getRestoredStringJSCL(g1.toString()));
newRate.bindExpression(reactionStep);
// reactionStep.getKinetics().getKineticsParameterFromRole(Kinetics.ROLE_ReactionRate).setExpression(newRate.flatten());
if (reactionStep.getKinetics().getKineticsParameterFromRole(Kinetics.ROLE_ReactionRate) != null) {
reactionStep.getKinetics().getKineticsParameterFromRole(Kinetics.ROLE_ReactionRate).setExpression(newRate.flatten());
}
}
for (ReactionRule reactionRule : newBioModel.getModel().getRbmModelContainer().getReactionRuleList()) {
SymbolTable oldSymbolTable = oldBioModel.getModel().getRbmModelContainer().getReactionRule(reactionRule.getName()).getKineticLaw().getScopedSymbolTable();
SymbolTable newSymbolTable = reactionRule.getKineticLaw().getScopedSymbolTable();
for (Parameter p : reactionRule.getKineticLaw().getUnresolvedParameters()) {
convertVarsWithUnitFactors(oldSymbolTable, newSymbolTable, p);
}
for (Parameter p : reactionRule.getKineticLaw().getLocalParameters()) {
convertVarsWithUnitFactors(oldSymbolTable, newSymbolTable, p);
}
}
for (SimulationContext simContext : newBioModel.getSimulationContexts()) {
SimulationContext oldSimContext = oldBioModel.getSimulationContext(simContext.getName());
// ArrayList<Parameter> parameterList = new ArrayList<Parameter>();
for (StructureMapping mapping : simContext.getGeometryContext().getStructureMappings()) {
Structure oldStructure = oldModel.getStructure(mapping.getStructure().getName());
StructureMapping oldMapping = oldSimContext.getGeometryContext().getStructureMapping(oldStructure);
for (Parameter p : mapping.computeApplicableParameterList()) {
convertVarsWithUnitFactors(oldMapping, mapping, p);
}
}
for (SpeciesContextSpec spec : simContext.getReactionContext().getSpeciesContextSpecs()) {
SpeciesContext oldSpeciesContext = oldModel.getSpeciesContext(spec.getSpeciesContext().getName());
SpeciesContextSpec oldSpec = oldSimContext.getReactionContext().getSpeciesContextSpec(oldSpeciesContext);
for (Parameter p : spec.computeApplicableParameterList()) {
convertVarsWithUnitFactors(oldSpec, spec, p);
}
}
for (int i = 0; i < simContext.getElectricalStimuli().length; i++) {
ElectricalStimulus newElectricalStimulus = simContext.getElectricalStimuli()[i];
ElectricalStimulus oldElectricalStimulus = oldSimContext.getElectricalStimuli()[i];
for (Parameter p : newElectricalStimulus.getParameters()) {
convertVarsWithUnitFactors(oldElectricalStimulus.getNameScope().getScopedSymbolTable(), newElectricalStimulus.getNameScope().getScopedSymbolTable(), p);
}
}
// convert events : trigger and delay parameters and event assignments
for (int i = 0; simContext.getBioEvents() != null && oldSimContext.getBioEvents() != null && i < simContext.getBioEvents().length; i++) {
BioEvent newBioEvent = simContext.getBioEvents()[i];
BioEvent oldBioEvent = oldSimContext.getBioEvent(newBioEvent.getName());
for (Parameter p : newBioEvent.getEventParameters()) {
convertVarsWithUnitFactors(oldBioEvent.getNameScope().getScopedSymbolTable(), newBioEvent.getNameScope().getScopedSymbolTable(), p);
}
// for each event assignment expression
for (int e = 0; e < newBioEvent.getEventAssignments().size(); e++) {
ScopedSymbolTable newSymbolTable = newBioEvent.getNameScope().getScopedSymbolTable();
ScopedSymbolTable oldSymbolTable = oldBioEvent.getNameScope().getScopedSymbolTable();
EventAssignment newEventAssignment = newBioEvent.getEventAssignments().get(e);
EventAssignment oldEventAssignment = oldBioEvent.getEventAssignments().get(e);
VCUnitDefinition oldTargetUnit = oldEventAssignment.getTarget().getUnitDefinition();
VCUnitDefinition newTargetUnit = newEventAssignment.getTarget().getUnitDefinition();
Expression eventAssgnExpr = newEventAssignment.getAssignmentExpression();
convertExprWithUnitFactors(oldSymbolTable, newSymbolTable, oldTargetUnit, newTargetUnit, eventAssgnExpr);
}
}
/**
* @TODO: If rate rule variable unit is TBD, we still need to handle the rate expression unit.
*/
// convert rate rules
RateRule[] rateRules = simContext.getRateRules();
if (rateRules != null && rateRules.length > 0) {
for (RateRule rateRule : rateRules) {
RateRule oldRateRule = oldSimContext.getRateRule(rateRule.getName());
ScopedSymbolTable oldSymbolTable = oldRateRule.getSimulationContext();
ScopedSymbolTable newSymbolTable = rateRule.getSimulationContext();
VCUnitDefinition oldTargetUnit = oldRateRule.getRateRuleVar().getUnitDefinition();
VCUnitDefinition newTargetUnit = rateRule.getRateRuleVar().getUnitDefinition();
Expression rateRuleExpr = rateRule.getRateRuleExpression();
convertExprWithUnitFactors(oldSymbolTable, newSymbolTable, oldTargetUnit, newTargetUnit, rateRuleExpr);
}
}
AssignmentRule[] assignmentRules = simContext.getAssignmentRules();
if (assignmentRules != null && assignmentRules.length > 0) {
for (AssignmentRule assignmentRule : assignmentRules) {
AssignmentRule oldAssignRule = oldSimContext.getAssignmentRule(assignmentRule.getName());
ScopedSymbolTable oldSymbolTable = oldAssignRule.getSimulationContext();
ScopedSymbolTable newSymbolTable = assignmentRule.getSimulationContext();
VCUnitDefinition oldTargetUnit = oldAssignRule.getAssignmentRuleVar().getUnitDefinition();
VCUnitDefinition newTargetUnit = assignmentRule.getAssignmentRuleVar().getUnitDefinition();
Expression assignmentRuleExpr = assignmentRule.getAssignmentRuleExpression();
convertExprWithUnitFactors(oldSymbolTable, newSymbolTable, oldTargetUnit, newTargetUnit, assignmentRuleExpr);
}
}
}
// end for - simulationContext
return newBioModel;
}
use of cbit.vcell.mapping.StructureMapping in project vcell by virtualcell.
the class SBMLExporter method addSpecies.
/**
* addSpecies comment.
* @throws XMLStreamException
* @throws SbmlException
*/
protected void addSpecies() throws XMLStreamException, SbmlException {
Model vcModel = vcBioModel.getModel();
SpeciesContext[] vcSpeciesContexts = vcModel.getSpeciesContexts();
for (int i = 0; i < vcSpeciesContexts.length; i++) {
org.sbml.jsbml.Species sbmlSpecies = sbmlModel.createSpecies();
sbmlSpecies.setId(vcSpeciesContexts[i].getName());
if (vcSpeciesContexts[i].getSbmlName() != null) {
sbmlSpecies.setName(vcSpeciesContexts[i].getSbmlName());
}
// Assuming that at this point, the compartment(s) for the model are already filled in.
Compartment compartment = sbmlModel.getCompartment(TokenMangler.mangleToSName(vcSpeciesContexts[i].getStructure().getName()));
if (compartment != null) {
sbmlSpecies.setCompartment(compartment.getId());
}
// 'hasSubstanceOnly' field will be 'true', since export to SBML is done by converting to initial amounts.
sbmlSpecies.setHasOnlySubstanceUnits(true);
// Get (and set) the initial concentration value
if (getSelectedSimContext() == null) {
throw new RuntimeException("No simcontext (application) specified; Cannot proceed.");
}
// Get the speciesContextSpec in the simContext corresponding to the 'speciesContext'; and extract its initial concentration value.
SpeciesContextSpec vcSpeciesContextsSpec = getSelectedSimContext().getReactionContext().getSpeciesContextSpec(vcSpeciesContexts[i]);
// since we are setting the substance units for species to 'molecule' or 'item', a unit that is originally in uM (or molecules/um2),
// we need to convert concentration from uM -> molecules/um3; this can be achieved by dividing by KMOLE.
// for now we don't do this here and defer to the mechanisms built into the SimContext to convert and set amount instead of concentration
// TO-DO: change to export either concentrations or amounts depending on the type of SimContext and setting
SpeciesContextSpecParameter initCount = vcSpeciesContextsSpec.getInitialCountParameter();
if (initCount.getExpression() == null) {
try {
getSelectedSimContext().convertSpeciesIniCondition(false);
} catch (MappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new RuntimeException(e.getMessage());
} catch (PropertyVetoException e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new RuntimeException(e.getMessage());
}
}
Expression initCountExpr = initCount.getExpression();
try {
sbmlSpecies.setInitialAmount(initCountExpr.evaluateConstant());
} catch (cbit.vcell.parser.ExpressionException e) {
// If exporting to L2V3, if species concentration is not an expr with x, y, z or other species, add as InitialAssignment, else complain.
if (initCountExpr != null) {
if ((sbmlLevel == 2 && sbmlVersion >= 3) || (sbmlLevel > 2)) {
// L2V3 and above - add expression as init assignment
cbit.vcell.mapping.AssignmentRule vcellAs = getSelectedSimContext().getAssignmentRule(vcSpeciesContexts[i]);
if (vcellAs == null) {
// we don't create InitialAssignment for an AssignmentRule variable (Reference: L3V1 Section 4.8)
ASTNode initAssgnMathNode = getFormulaFromExpression(initCountExpr);
InitialAssignment initAssignment = sbmlModel.createInitialAssignment();
initAssignment.setSymbol(vcSpeciesContexts[i].getName());
initAssignment.setMath(initAssgnMathNode);
}
} else {
// L2V1 (or L1V2 also??)
// do nothing - we no longer support export to level <3
// // L2V1 (and L1V2?) and species is 'fixed' (constant), and not fn of x,y,z, other sp, add expr as assgn rule
// ASTNode assgnRuleMathNode = getFormulaFromExpression(initCountExpr);
// AssignmentRule assgnRule = sbmlModel.createAssignmentRule();
// assgnRule.setVariable(vcSpeciesContexts[i].getName());
// assgnRule.setMath(assgnRuleMathNode);
}
}
}
// Get (and set) the boundary condition value
boolean bBoundaryCondition = getBoundaryCondition(vcSpeciesContexts[i]);
sbmlSpecies.setBoundaryCondition(bBoundaryCondition);
// mandatory for L3, optional for L2
sbmlSpecies.setConstant(false);
// set species substance units as 'molecules' - same as defined in the model; irrespective of it is in surface or volume.
UnitDefinition unitDefn = getOrCreateSBMLUnit(sbmlExportSpec.getSubstanceUnits());
sbmlSpecies.setSubstanceUnits(unitDefn);
// need to do the following if exporting to SBML spatial
if (bSpatial) {
// Required for setting BoundaryConditions : structureMapping for vcSpeciesContext[i] & sbmlGeometry.coordinateComponents
StructureMapping sm = getSelectedSimContext().getGeometryContext().getStructureMapping(vcSpeciesContexts[i].getStructure());
SpatialModelPlugin mplugin = (SpatialModelPlugin) sbmlModel.getPlugin(SBMLUtils.SBML_SPATIAL_NS_PREFIX);
org.sbml.jsbml.ext.spatial.Geometry sbmlGeometry = mplugin.getGeometry();
CoordinateComponent ccX = sbmlGeometry.getListOfCoordinateComponents().get(vcModel.getX().getName());
CoordinateComponent ccY = sbmlGeometry.getListOfCoordinateComponents().get(vcModel.getY().getName());
CoordinateComponent ccZ = sbmlGeometry.getListOfCoordinateComponents().get(vcModel.getZ().getName());
// add diffusion, advection, boundary condition parameters for species, if they exist
Parameter[] scsParams = vcSpeciesContextsSpec.getParameters();
if (scsParams != null) {
for (int j = 0; j < scsParams.length; j++) {
if (scsParams[j] != null) {
SpeciesContextSpecParameter scsParam = (SpeciesContextSpecParameter) scsParams[j];
// no need to add parameters in SBML for init conc or init count
int role = scsParam.getRole();
switch(role) {
case SpeciesContextSpec.ROLE_BoundaryValueXm:
{
break;
}
case SpeciesContextSpec.ROLE_BoundaryValueXp:
{
break;
}
case SpeciesContextSpec.ROLE_BoundaryValueYm:
{
break;
}
case SpeciesContextSpec.ROLE_BoundaryValueYp:
{
break;
}
case SpeciesContextSpec.ROLE_BoundaryValueZm:
{
break;
}
case SpeciesContextSpec.ROLE_BoundaryValueZp:
{
break;
}
case SpeciesContextSpec.ROLE_DiffusionRate:
{
break;
}
case SpeciesContextSpec.ROLE_InitialConcentration:
{
// done elsewhere??
continue;
// break;
}
case SpeciesContextSpec.ROLE_InitialCount:
{
// done elsewhere??
continue;
// break;
}
case SpeciesContextSpec.ROLE_VelocityX:
{
break;
}
case SpeciesContextSpec.ROLE_VelocityY:
{
break;
}
case SpeciesContextSpec.ROLE_VelocityZ:
{
break;
}
default:
{
throw new RuntimeException("SpeciesContext Specification parameter with role " + SpeciesContextSpec.RoleNames[role] + " not yet supported for SBML export");
}
}
// if diffusion is 0 && vel terms are not specified, boundary condition not present
if (vcSpeciesContextsSpec.isAdvecting() || vcSpeciesContextsSpec.isDiffusing()) {
Expression diffExpr = vcSpeciesContextsSpec.getDiffusionParameter().getExpression();
boolean bDiffExprNull = (diffExpr == null);
boolean bDiffExprIsZero = false;
if (!bDiffExprNull && diffExpr.isNumeric()) {
try {
bDiffExprIsZero = (diffExpr.evaluateConstant() == 0.0);
} catch (Exception e) {
e.printStackTrace(System.out);
throw new RuntimeException("Unable to evalute numeric value of diffusion parameter for speciesContext '" + vcSpeciesContexts[i] + "'.");
}
}
boolean bDiffusionZero = (bDiffExprNull || bDiffExprIsZero);
Expression velX_Expr = vcSpeciesContextsSpec.getVelocityXParameter().getExpression();
SpatialQuantity[] velX_Quantities = vcSpeciesContextsSpec.getVelocityQuantities(QuantityComponent.X);
boolean bVelX_ExprIsNull = (velX_Expr == null && velX_Quantities.length == 0);
Expression velY_Expr = vcSpeciesContextsSpec.getVelocityYParameter().getExpression();
SpatialQuantity[] velY_Quantities = vcSpeciesContextsSpec.getVelocityQuantities(QuantityComponent.Y);
boolean bVelY_ExprIsNull = (velY_Expr == null && velY_Quantities.length == 0);
Expression velZ_Expr = vcSpeciesContextsSpec.getVelocityZParameter().getExpression();
SpatialQuantity[] velZ_Quantities = vcSpeciesContextsSpec.getVelocityQuantities(QuantityComponent.Z);
boolean bVelZ_ExprIsNull = (velZ_Expr == null && velZ_Quantities.length == 0);
boolean bAdvectionNull = (bVelX_ExprIsNull && bVelY_ExprIsNull && bVelZ_ExprIsNull);
if (bDiffusionZero && bAdvectionNull) {
continue;
}
}
// for example, if scsParam is BC_Zm and if coordinateComponent 'ccZ' is null, no SBML parameter should be created for BC_Zm
if ((((role == SpeciesContextSpec.ROLE_BoundaryValueXm) || (role == SpeciesContextSpec.ROLE_BoundaryValueXp)) && (ccX == null)) || (((role == SpeciesContextSpec.ROLE_BoundaryValueYm) || (role == SpeciesContextSpec.ROLE_BoundaryValueYp)) && (ccY == null)) || (((role == SpeciesContextSpec.ROLE_BoundaryValueZm) || (role == SpeciesContextSpec.ROLE_BoundaryValueZp)) && (ccZ == null))) {
continue;
}
org.sbml.jsbml.Parameter sbmlParam = createSBMLParamFromSpeciesParam(vcSpeciesContexts[i], (SpeciesContextSpecParameter) scsParams[j]);
if (sbmlParam != null) {
BoundaryConditionType vcBCType_Xm = vcSelectedSimContext.getGeometryContext().getStructureMapping(vcSpeciesContexts[i].getStructure()).getBoundaryConditionTypeXm();
BoundaryConditionType vcBCType_Xp = vcSelectedSimContext.getGeometryContext().getStructureMapping(vcSpeciesContexts[i].getStructure()).getBoundaryConditionTypeXp();
BoundaryConditionType vcBCType_Ym = vcSelectedSimContext.getGeometryContext().getStructureMapping(vcSpeciesContexts[i].getStructure()).getBoundaryConditionTypeYm();
BoundaryConditionType vcBCType_Yp = vcSelectedSimContext.getGeometryContext().getStructureMapping(vcSpeciesContexts[i].getStructure()).getBoundaryConditionTypeYp();
BoundaryConditionType vcBCType_Zm = vcSelectedSimContext.getGeometryContext().getStructureMapping(vcSpeciesContexts[i].getStructure()).getBoundaryConditionTypeZm();
BoundaryConditionType vcBCType_Zp = vcSelectedSimContext.getGeometryContext().getStructureMapping(vcSpeciesContexts[i].getStructure()).getBoundaryConditionTypeZp();
SpatialParameterPlugin spplugin = (SpatialParameterPlugin) sbmlParam.getPlugin(SBMLUtils.SBML_SPATIAL_NS_PREFIX);
if (role == SpeciesContextSpec.ROLE_DiffusionRate) {
// set diffusionCoefficient element in SpatialParameterPlugin for param
DiffusionCoefficient sbmlDiffCoeff = new DiffusionCoefficient();
sbmlDiffCoeff.setVariable(vcSpeciesContexts[i].getName());
sbmlDiffCoeff.setDiffusionKind(DiffusionKind.isotropic);
sbmlDiffCoeff.setSpeciesRef(vcSpeciesContexts[i].getName());
spplugin.setParamType(sbmlDiffCoeff);
}
if ((role == SpeciesContextSpec.ROLE_BoundaryValueXm) && (ccX != null)) {
// set BoundaryCondn Xm element in SpatialParameterPlugin for param
BoundaryCondition sbmlBCXm = new BoundaryCondition();
spplugin.setParamType(sbmlBCXm);
sbmlBCXm.setType(getBoundaryConditionKind(vcBCType_Xm));
sbmlBCXm.setVariable(vcSpeciesContexts[i].getName());
sbmlBCXm.setCoordinateBoundary(ccX.getBoundaryMinimum().getId());
}
if ((role == SpeciesContextSpec.ROLE_BoundaryValueXp) && (ccX != null)) {
// set BoundaryCondn Xp element in SpatialParameterPlugin for param
BoundaryCondition sbmlBCXp = new BoundaryCondition();
spplugin.setParamType(sbmlBCXp);
sbmlBCXp.setType(getBoundaryConditionKind(vcBCType_Xp));
sbmlBCXp.setVariable(vcSpeciesContexts[i].getName());
// sbmlBCXp.setType(sm.getBoundaryConditionTypeXp().boundaryTypeStringValue());
sbmlBCXp.setCoordinateBoundary(ccX.getBoundaryMaximum().getId());
}
if ((role == SpeciesContextSpec.ROLE_BoundaryValueYm) && (ccY != null)) {
// set BoundaryCondn Ym element in SpatialParameterPlugin for param
BoundaryCondition sbmlBCYm = new BoundaryCondition();
spplugin.setParamType(sbmlBCYm);
sbmlBCYm.setType(getBoundaryConditionKind(vcBCType_Yp));
sbmlBCYm.setVariable(vcSpeciesContexts[i].getName());
// sbmlBCYm.setType(sm.getBoundaryConditionTypeYm().boundaryTypeStringValue());
sbmlBCYm.setCoordinateBoundary(ccY.getBoundaryMinimum().getId());
}
if ((role == SpeciesContextSpec.ROLE_BoundaryValueYp) && (ccY != null)) {
// set BoundaryCondn Yp element in SpatialParameterPlugin for param
BoundaryCondition sbmlBCYp = new BoundaryCondition();
spplugin.setParamType(sbmlBCYp);
sbmlBCYp.setType(getBoundaryConditionKind(vcBCType_Yp));
sbmlBCYp.setVariable(vcSpeciesContexts[i].getName());
// sbmlBCYp.setType(sm.getBoundaryConditionTypeYp().boundaryTypeStringValue());
sbmlBCYp.setCoordinateBoundary(ccY.getBoundaryMaximum().getId());
}
if ((role == SpeciesContextSpec.ROLE_BoundaryValueZm) && (ccZ != null)) {
// set BoundaryCondn Zm element in SpatialParameterPlugin for param
BoundaryCondition sbmlBCZm = new BoundaryCondition();
spplugin.setParamType(sbmlBCZm);
sbmlBCZm.setType(getBoundaryConditionKind(vcBCType_Zm));
sbmlBCZm.setVariable(vcSpeciesContexts[i].getName());
// sbmlBCZm.setType(sm.getBoundaryConditionTypeZm().boundaryTypeStringValue());
sbmlBCZm.setCoordinateBoundary(ccZ.getBoundaryMinimum().getId());
}
if ((role == SpeciesContextSpec.ROLE_BoundaryValueZp) && (ccZ != null)) {
// set BoundaryCondn Zp element in SpatialParameterPlugin for param
BoundaryCondition sbmlBCZp = new BoundaryCondition();
spplugin.setParamType(sbmlBCZp);
sbmlBCZp.setType(getBoundaryConditionKind(vcBCType_Zp));
sbmlBCZp.setVariable(vcSpeciesContexts[i].getName());
// sbmlBCZp.setType(sm.getBoundaryConditionTypeZp().boundaryTypeStringValue());
sbmlBCZp.setCoordinateBoundary(ccZ.getBoundaryMaximum().getId());
}
if (role == SpeciesContextSpec.ROLE_VelocityX) {
// set advectionCoeff X element in SpatialParameterPlugin for param
AdvectionCoefficient sbmlAdvCoeffX = new AdvectionCoefficient();
spplugin.setParamType(sbmlAdvCoeffX);
sbmlAdvCoeffX.setVariable(vcSpeciesContexts[i].getName());
sbmlAdvCoeffX.setCoordinate(CoordinateKind.cartesianX);
}
if (role == SpeciesContextSpec.ROLE_VelocityY) {
// set advectionCoeff Y element in SpatialParameterPlugin for param
AdvectionCoefficient sbmlAdvCoeffY = new AdvectionCoefficient();
spplugin.setParamType(sbmlAdvCoeffY);
sbmlAdvCoeffY.setVariable(vcSpeciesContexts[i].getName());
sbmlAdvCoeffY.setCoordinate(CoordinateKind.cartesianY);
}
if (role == SpeciesContextSpec.ROLE_VelocityZ) {
// set advectionCoeff Z element in SpatialParameterPlugin for param
AdvectionCoefficient sbmlAdvCoeffZ = new AdvectionCoefficient();
spplugin.setParamType(sbmlAdvCoeffZ);
sbmlAdvCoeffZ.setVariable(vcSpeciesContexts[i].getName());
sbmlAdvCoeffZ.setCoordinate(CoordinateKind.cartesianZ);
}
}
// if sbmlParam != null
}
// if scsParams[j] != null
}
// end for scsParams
}
// end scsParams != null
}
// end if (bSpatial)
// Add the common name of species to annotation, and add an annotation element to the species.
// This is required later while trying to read in fluxes ...
// new Element(XMLTags.VCellRelatedInfoTag, sbml_vcml_ns);
Element sbmlImportRelatedElement = null;
// Element speciesElement = new Element(XMLTags.SpeciesTag, sbml_vcml_ns);
// speciesElement.setAttribute(XMLTags.NameAttrTag, TokenMangler.mangleToSName(vcSpeciesContexts[i].getSpecies().getCommonName()));
// sbmlImportRelatedElement.addContent(speciesElement);
// Get RDF annotation for species from SBMLAnnotationUtils
sbmlAnnotationUtil.writeAnnotation(vcSpeciesContexts[i].getSpecies(), sbmlSpecies, sbmlImportRelatedElement);
// Now set notes,
sbmlAnnotationUtil.writeNotes(vcSpeciesContexts[i].getSpecies(), sbmlSpecies);
}
}
use of cbit.vcell.mapping.StructureMapping 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
// }
}
use of cbit.vcell.mapping.StructureMapping in project vcell by virtualcell.
the class SBMLExporter method createSBMLParamFromSpeciesParam.
/**
* createSBMLParamFromSpeciesParam : creates an SBML parameter for each speciesContextSpecParameter (diffusion coefficient,
* advection coeffs, boundary conditions (X,Y,Z).
*
* @param spContext
* @param scsParam
* @return
* @throws SbmlException
*/
org.sbml.jsbml.Parameter createSBMLParamFromSpeciesParam(SpeciesContext spContext, SpeciesContextSpecParameter scsParam) throws SbmlException {
try {
Expression paramExpr = scsParam.getExpression();
// if scsParam is diff, Vel X, Y, Z parameter and if its expression is null or 0.0, don't create parameter.
int role = scsParam.getRole();
if (((role == SpeciesContextSpec.ROLE_DiffusionRate) || (role == SpeciesContextSpec.ROLE_VelocityX) || (role == SpeciesContextSpec.ROLE_VelocityY) || (role == SpeciesContextSpec.ROLE_VelocityZ)) && ((paramExpr == null) || (paramExpr.isNumeric() && (scsParam.getConstantValue() == 0.0)))) {
return null;
}
// if scsParam is a BoundaryCondition, and paramExpr is null, values are set based on boundary condition type.
if (((role == SpeciesContextSpec.ROLE_BoundaryValueXm) || (role == SpeciesContextSpec.ROLE_BoundaryValueXp) || (role == SpeciesContextSpec.ROLE_BoundaryValueYm) || (role == SpeciesContextSpec.ROLE_BoundaryValueYp) || (role == SpeciesContextSpec.ROLE_BoundaryValueZm) || (role == SpeciesContextSpec.ROLE_BoundaryValueZp)) && (paramExpr == null)) {
StructureMapping sm = getSelectedSimContext().getGeometryContext().getStructureMapping(spContext.getStructure());
Expression initCondnExpr = getSelectedSimContext().getReactionContext().getSpeciesContextSpec(spContext).getInitialConditionParameter().getExpression();
// if BC type is Neumann (flux), its value is 0.0
if ((role == SpeciesContextSpec.ROLE_BoundaryValueXm)) {
if (sm.getBoundaryConditionTypeXm().isDIRICHLET()) {
paramExpr = new Expression(initCondnExpr);
} else if (sm.getBoundaryConditionTypeXm().isNEUMANN()) {
paramExpr = new Expression(0.0);
}
}
if ((role == SpeciesContextSpec.ROLE_BoundaryValueXp)) {
if (sm.getBoundaryConditionTypeXp().isDIRICHLET()) {
paramExpr = new Expression(initCondnExpr);
} else if (sm.getBoundaryConditionTypeXp().isNEUMANN()) {
paramExpr = new Expression(0.0);
}
}
if ((role == SpeciesContextSpec.ROLE_BoundaryValueYm)) {
if (sm.getBoundaryConditionTypeYm().isDIRICHLET()) {
paramExpr = new Expression(initCondnExpr);
} else if (sm.getBoundaryConditionTypeYm().isNEUMANN()) {
paramExpr = new Expression(0.0);
}
}
if ((role == SpeciesContextSpec.ROLE_BoundaryValueYp)) {
if (sm.getBoundaryConditionTypeYp().isDIRICHLET()) {
paramExpr = new Expression(initCondnExpr);
} else if (sm.getBoundaryConditionTypeYp().isNEUMANN()) {
paramExpr = new Expression(0.0);
}
}
if ((role == SpeciesContextSpec.ROLE_BoundaryValueZm)) {
if (sm.getBoundaryConditionTypeZm().isDIRICHLET()) {
paramExpr = new Expression(initCondnExpr);
} else if (sm.getBoundaryConditionTypeZm().isNEUMANN()) {
paramExpr = new Expression(0.0);
}
}
if ((role == SpeciesContextSpec.ROLE_BoundaryValueZp)) {
if (sm.getBoundaryConditionTypeZp().isDIRICHLET()) {
paramExpr = new Expression(initCondnExpr);
} else if (sm.getBoundaryConditionTypeZp().isNEUMANN()) {
paramExpr = new Expression(0.0);
}
}
}
// create SBML parameter
org.sbml.jsbml.Parameter param = sbmlModel.createParameter();
param.setId(TokenMangler.mangleToSName(spContext.getName() + "_" + scsParam.getName()));
UnitDefinition unitDefn = getOrCreateSBMLUnit(scsParam.getUnitDefinition());
param.setUnits(unitDefn);
param.setConstant(scsParam.isConstant());
if (paramExpr.isNumeric()) {
param.setValue(paramExpr.evaluateConstant());
param.setConstant(true);
} else {
// we need to create a parameter and a rule for the non-numeric expr of diffParam
param.setValue(0.0);
param.setConstant(false);
// now add assignment rule in SBML for the diff param
ASTNode assgnRuleMathNode = getFormulaFromExpression(paramExpr);
AssignmentRule assgnRule = sbmlModel.createAssignmentRule();
assgnRule.setVariable(param.getId());
assgnRule.setMath(assgnRuleMathNode);
}
return param;
} catch (ExpressionException e) {
e.printStackTrace(System.out);
throw new RuntimeException("Unable to interpret parameter '" + scsParam.getName() + "' of species : " + spContext.getName());
}
}
use of cbit.vcell.mapping.StructureMapping in project vcell by virtualcell.
the class SEDMLExporter method translateBioModelToSedML.
private void translateBioModelToSedML(String savePath, String sBaseFileName, boolean bForceVCML, boolean bHasDataOnly, boolean bFromOmex) {
// true if invoked for omex export, false if for sedml
sbmlFilePathStrAbsoluteList.clear();
// models
try {
SimulationContext[] simContexts = vcBioModel.getSimulationContexts();
cbit.vcell.model.Model vcModel = vcBioModel.getModel();
// "urn:sedml:language:sbml";
String sbmlLanguageURN = SUPPORTED_LANGUAGE.SBML_GENERIC.getURN();
// "urn:sedml:language:vcml";
String vcmlLanguageURN = SUPPORTED_LANGUAGE.VCELL_GENERIC.getURN();
String bioModelName = vcBioModel.getName();
String bioModelID = TokenMangler.mangleToSName(bioModelName);
// String usrHomeDirPath = ResourceUtil.getUserHomeDir().getAbsolutePath();
// to get Xpath string for variables.
SBMLSupport sbmlSupport = new SBMLSupport();
// for model count, task subcount
int simContextCnt = 0;
boolean bSpeciesAddedAsDataGens = false;
String sedmlNotesStr = "";
for (SimulationContext simContext : simContexts) {
// Export the application itself to SBML, with default overrides
String sbmlString = null;
int level = 3;
int version = 1;
boolean isSpatial = simContext.getGeometry().getDimension() > 0 ? true : false;
// local to global translation map
Map<Pair<String, String>, String> l2gMap = null;
boolean sbmlExportFailed = false;
if (!bForceVCML) {
// we try to save to SBML
try {
// to compute and set the sizes of the remaining structures.
if (!simContext.getGeometryContext().isAllSizeSpecifiedPositive()) {
Structure structure = simContext.getModel().getStructure(0);
double structureSize = 1.0;
StructureMapping structMapping = simContext.getGeometryContext().getStructureMapping(structure);
StructureSizeSolver.updateAbsoluteStructureSizes(simContext, structure, structureSize, structMapping.getSizeParameter().getUnitDefinition());
// StructureMapping structureMapping = simContext.getGeometryContext().getStructureMappings()[0];
// StructureSizeSolver.updateAbsoluteStructureSizes(simContext, structureMapping.getStructure(), 1.0, structureMapping.getSizeParameter().getUnitDefinition());
}
SBMLExporter sbmlExporter = new SBMLExporter(vcBioModel, level, version, isSpatial);
sbmlExporter.setSelectedSimContext(simContext);
// no sim job
sbmlExporter.setSelectedSimulationJob(null);
sbmlString = sbmlExporter.getSBMLString();
l2gMap = sbmlExporter.getLocalToGlobalTranslationMap();
} catch (Exception e) {
sbmlExportFailed = true;
}
} else {
// we want to force VCML, we act as if saving to SBML failed
sbmlExportFailed = true;
}
// marked as failed, even if exporting to sbml didn't throw any exception
if (simContext.getGeometry().getDimension() > 0 && simContext.getApplicationType() == Application.NETWORK_STOCHASTIC) {
sbmlExportFailed = true;
} else if (simContext.getApplicationType() == Application.RULE_BASED_STOCHASTIC) {
sbmlExportFailed = true;
}
String simContextName = simContext.getName();
String filePathStrAbsolute = null;
String filePathStrRelative = null;
String urn = null;
String simContextId = null;
if (sbmlExportFailed) {
// filePathStrAbsolute = Paths.get(savePath, bioModelName + ".vcml").toString();
filePathStrAbsolute = Paths.get(savePath, sBaseFileName + ".vcml").toString();
// filePathStrRelative = bioModelName + ".vcml";
filePathStrRelative = sBaseFileName + ".vcml";
if (!bFromOmex) {
// the vcml file is managed elsewhere when called for omex
String vcmlString = XmlHelper.bioModelToXML(vcBioModel);
XmlUtil.writeXMLStringToFile(vcmlString, filePathStrAbsolute, true);
sbmlFilePathStrAbsoluteList.add(filePathStrRelative);
}
urn = vcmlLanguageURN;
sedmlModel.addModel(new Model(bioModelID, bioModelName, urn, filePathStrRelative));
} else {
// filePathStrAbsolute = Paths.get(savePath, bioModelName + "_" + TokenMangler.mangleToSName(simContextName) + ".xml").toString();
filePathStrAbsolute = Paths.get(savePath, sBaseFileName + "_" + TokenMangler.mangleToSName(simContextName) + ".xml").toString();
// filePathStrRelative = bioModelName + "_" + TokenMangler.mangleToSName(simContextName) + ".xml";
filePathStrRelative = sBaseFileName + "_" + TokenMangler.mangleToSName(simContextName) + ".xml";
XmlUtil.writeXMLStringToFile(sbmlString, filePathStrAbsolute, true);
urn = sbmlLanguageURN;
sbmlFilePathStrAbsoluteList.add(filePathStrRelative);
simContextId = TokenMangler.mangleToSName(simContextName);
sedmlModel.addModel(new Model(simContextId, simContextName, urn, filePathStrRelative));
}
MathMapping mathMapping = simContext.createNewMathMapping();
MathSymbolMapping mathSymbolMapping = mathMapping.getMathSymbolMapping();
// -------
// create sedml objects (simulation, task, datagenerators, report, plot) for each simulation in simcontext
// -------
int simCount = 0;
String taskRef = null;
int overrideCount = 0;
for (Simulation vcSimulation : simContext.getSimulations()) {
if (bHasDataOnly) {
// skip simulations not present in hash
if (!simsToExport.contains(vcSimulation))
continue;
}
// 1 -------> check compatibility
// if simContext is non-spatial stochastic, check if sim is histogram; if so, skip it, it can't be encoded in sedml 1.x
SolverTaskDescription simTaskDesc = vcSimulation.getSolverTaskDescription();
if (simContext.getGeometry().getDimension() == 0 && simContext.isStoch()) {
long numOfTrials = simTaskDesc.getStochOpt().getNumOfTrials();
if (numOfTrials > 1) {
String msg = "\n\t" + simContextName + " ( " + vcSimulation.getName() + " ) : export of non-spatial stochastic simulation with histogram option to SEDML not supported at this time.";
sedmlNotesStr += msg;
continue;
}
}
// 2 ------->
// create Algorithm and sedmlSimulation (UniformtimeCourse)
SolverDescription vcSolverDesc = simTaskDesc.getSolverDescription();
String kiSAOIdStr = vcSolverDesc.getKisao();
Algorithm sedmlAlgorithm = new Algorithm(kiSAOIdStr);
TimeBounds vcSimTimeBounds = simTaskDesc.getTimeBounds();
double startingTime = vcSimTimeBounds.getStartingTime();
String simName = vcSimulation.getName();
UniformTimeCourse utcSim = new UniformTimeCourse(TokenMangler.mangleToSName(simName), simName, startingTime, startingTime, vcSimTimeBounds.getEndingTime(), (int) simTaskDesc.getExpectedNumTimePoints(), sedmlAlgorithm);
// --------- deal with error tolerance
boolean enableAbsoluteErrorTolerance;
boolean enableRelativeErrorTolerance;
if (vcSolverDesc.isSemiImplicitPdeSolver() || vcSolverDesc.isChomboSolver()) {
enableAbsoluteErrorTolerance = false;
enableRelativeErrorTolerance = true;
} else if (vcSolverDesc.hasErrorTolerance()) {
enableAbsoluteErrorTolerance = true;
enableRelativeErrorTolerance = true;
} else {
enableAbsoluteErrorTolerance = false;
enableRelativeErrorTolerance = false;
}
if (enableAbsoluteErrorTolerance) {
ErrorTolerance et = simTaskDesc.getErrorTolerance();
String kisaoStr = ErrorTolerance.ErrorToleranceDescription.Absolute.getKisao();
AlgorithmParameter sedmlAlgorithmParameter = new AlgorithmParameter(kisaoStr, et.getAbsoluteErrorTolerance() + "");
sedmlAlgorithm.addAlgorithmParameter(sedmlAlgorithmParameter);
}
if (enableRelativeErrorTolerance) {
ErrorTolerance et = simTaskDesc.getErrorTolerance();
String kisaoStr = ErrorTolerance.ErrorToleranceDescription.Relative.getKisao();
AlgorithmParameter sedmlAlgorithmParameter = new AlgorithmParameter(kisaoStr, et.getRelativeErrorTolerance() + "");
sedmlAlgorithm.addAlgorithmParameter(sedmlAlgorithmParameter);
}
// ---------- deal with time step (code adapted from TimeSpecPanel.refresh()
boolean enableDefaultTimeStep;
boolean enableMinTimeStep;
boolean enableMaxTimeStep;
if (vcSolverDesc.compareEqual(SolverDescription.StochGibson)) {
// stochastic time
enableDefaultTimeStep = false;
enableMinTimeStep = false;
enableMaxTimeStep = false;
} else if (vcSolverDesc.compareEqual(SolverDescription.NFSim)) {
enableDefaultTimeStep = false;
enableMinTimeStep = false;
enableMaxTimeStep = false;
} else {
// fixed time step solvers and non spatial stochastic solvers only show default time step.
if (!vcSolverDesc.hasVariableTimestep() || vcSolverDesc.isNonSpatialStochasticSolver()) {
enableDefaultTimeStep = true;
enableMinTimeStep = false;
enableMaxTimeStep = false;
} else {
// variable time step solvers shows min and max, but sundials solvers don't show min
enableDefaultTimeStep = false;
enableMinTimeStep = true;
enableMaxTimeStep = true;
if (vcSolverDesc.hasSundialsTimeStepping()) {
enableMinTimeStep = false;
}
}
}
TimeStep ts = simTaskDesc.getTimeStep();
if (enableDefaultTimeStep) {
String kisaoStr = TimeStep.TimeStepDescription.Default.getKisao();
AlgorithmParameter sedmlAlgorithmParameter = new AlgorithmParameter(kisaoStr, ts.getDefaultTimeStep() + "");
sedmlAlgorithm.addAlgorithmParameter(sedmlAlgorithmParameter);
}
if (enableMinTimeStep) {
String kisaoStr = TimeStep.TimeStepDescription.Minimum.getKisao();
AlgorithmParameter sedmlAlgorithmParameter = new AlgorithmParameter(kisaoStr, ts.getMinimumTimeStep() + "");
sedmlAlgorithm.addAlgorithmParameter(sedmlAlgorithmParameter);
}
if (enableMaxTimeStep) {
String kisaoStr = TimeStep.TimeStepDescription.Maximum.getKisao();
AlgorithmParameter sedmlAlgorithmParameter = new AlgorithmParameter(kisaoStr, ts.getMaximumTimeStep() + "");
sedmlAlgorithm.addAlgorithmParameter(sedmlAlgorithmParameter);
}
if (simTaskDesc.getSimulation().getMathDescription().isNonSpatialStoch()) {
// ------- deal with seed
NonspatialStochSimOptions nssso = simTaskDesc.getStochOpt();
if (nssso.isUseCustomSeed()) {
// 488
String kisaoStr = SolverDescription.AlgorithmParameterDescription.Seed.getKisao();
AlgorithmParameter sedmlAlgorithmParameter = new AlgorithmParameter(kisaoStr, nssso.getCustomSeed() + "");
sedmlAlgorithm.addAlgorithmParameter(sedmlAlgorithmParameter);
}
} else {
// (... isRuleBased(), isSpatial(), isMovingMembrane(), isSpatialHybrid() ...
;
}
if (// -------- deal with hybrid solvers (non-spatial)
vcSolverDesc == SolverDescription.HybridEuler || vcSolverDesc == SolverDescription.HybridMilAdaptive || vcSolverDesc == SolverDescription.HybridMilstein) {
NonspatialStochHybridOptions nssho = simTaskDesc.getStochHybridOpt();
String kisaoStr = SolverDescription.AlgorithmParameterDescription.Epsilon.getKisao();
AlgorithmParameter sedmlAlgorithmParameter = new AlgorithmParameter(kisaoStr, nssho.getEpsilon() + "");
sedmlAlgorithm.addAlgorithmParameter(sedmlAlgorithmParameter);
kisaoStr = SolverDescription.AlgorithmParameterDescription.Lambda.getKisao();
sedmlAlgorithmParameter = new AlgorithmParameter(kisaoStr, nssho.getLambda() + "");
sedmlAlgorithm.addAlgorithmParameter(sedmlAlgorithmParameter);
kisaoStr = SolverDescription.AlgorithmParameterDescription.MSRTolerance.getKisao();
sedmlAlgorithmParameter = new AlgorithmParameter(kisaoStr, nssho.getMSRTolerance() + "");
sedmlAlgorithm.addAlgorithmParameter(sedmlAlgorithmParameter);
}
if (vcSolverDesc == SolverDescription.HybridMilAdaptive) {
// --------- one more param for hybrid-adaptive
NonspatialStochHybridOptions nssho = simTaskDesc.getStochHybridOpt();
String kisaoStr = SolverDescription.AlgorithmParameterDescription.SDETolerance.getKisao();
AlgorithmParameter sedmlAlgorithmParameter = new AlgorithmParameter(kisaoStr, nssho.getSDETolerance() + "");
sedmlAlgorithm.addAlgorithmParameter(sedmlAlgorithmParameter);
}
// TODO: consider adding notes for the algorithm parameters, to provide human-readable description of kisao terms
// sedmlAlgorithm.addNote(createNotesElement(algorithmNotesStr));
// TODO: even better, AlgorithmParameter in sed-ml should also have a human readable "name" field
// add a note to utcSim to indicate actual solver name
String simNotesStr = "Actual Solver Name : '" + vcSolverDesc.getDisplayLabel() + "'.";
utcSim.addNote(createNotesElement(simNotesStr));
sedmlModel.addSimulation(utcSim);
// 3 ------->
// create Tasks
MathOverrides mathOverrides = vcSimulation.getMathOverrides();
if ((sbmlExportFailed == false) && mathOverrides != null && mathOverrides.hasOverrides()) {
String[] overridenConstantNames = mathOverrides.getOverridenConstantNames();
String[] scannedConstantsNames = mathOverrides.getScannedConstantNames();
HashMap<String, String> scannedParamHash = new HashMap<String, String>();
HashMap<String, String> unscannedParamHash = new HashMap<String, String>();
for (String name : scannedConstantsNames) {
scannedParamHash.put(name, name);
}
for (String name : overridenConstantNames) {
if (!scannedParamHash.containsKey(name)) {
unscannedParamHash.put(name, name);
}
}
if (!unscannedParamHash.isEmpty() && scannedParamHash.isEmpty()) {
// only parameters with simple overrides (numeric/expression) no scans
// create new model with change for each parameter that has override; add simple task
String overriddenSimContextId = simContextId + "_" + overrideCount;
String overriddenSimContextName = simContextName + " modified";
Model sedModel = new Model(overriddenSimContextId, overriddenSimContextName, sbmlLanguageURN, simContextId);
overrideCount++;
for (String unscannedParamName : unscannedParamHash.values()) {
SymbolTableEntry ste = getSymbolTableEntryForModelEntity(mathSymbolMapping, unscannedParamName);
Expression unscannedParamExpr = mathOverrides.getActualExpression(unscannedParamName, 0);
if (unscannedParamExpr.isNumeric()) {
// if expression is numeric, add ChangeAttribute to model created above
XPathTarget targetXpath = getTargetAttributeXPath(ste, l2gMap);
ChangeAttribute changeAttribute = new ChangeAttribute(targetXpath, unscannedParamExpr.infix());
sedModel.addChange(changeAttribute);
} else {
// non-numeric expression : add 'computeChange' to modified model
ASTNode math = Libsedml.parseFormulaString(unscannedParamExpr.infix());
XPathTarget targetXpath = getTargetXPath(ste, l2gMap);
ComputeChange computeChange = new ComputeChange(targetXpath, math);
String[] exprSymbols = unscannedParamExpr.getSymbols();
// }
for (String symbol : exprSymbols) {
String symbolName = TokenMangler.mangleToSName(symbol);
SymbolTableEntry ste1 = vcModel.getEntry(symbol);
if (ste != null) {
if (ste1 instanceof SpeciesContext || ste1 instanceof Structure || ste1 instanceof ModelParameter) {
XPathTarget ste1_XPath = getTargetXPath(ste1, l2gMap);
org.jlibsedml.Variable sedmlVar = new org.jlibsedml.Variable(symbolName, symbolName, taskRef, ste1_XPath.getTargetAsString());
computeChange.addVariable(sedmlVar);
} else {
double doubleValue = 0.0;
if (ste1 instanceof ReservedSymbol) {
doubleValue = getReservedSymbolValue(ste1);
}
Parameter sedmlParameter = new Parameter(symbolName, symbolName, doubleValue);
computeChange.addParameter(sedmlParameter);
}
} else {
throw new RuntimeException("Symbol '" + symbol + "' used in expression for '" + unscannedParamName + "' not found in model.");
}
}
sedModel.addChange(computeChange);
}
}
sedmlModel.addModel(sedModel);
String taskId = "tsk_" + simContextCnt + "_" + simCount;
Task sedmlTask = new Task(taskId, vcSimulation.getName(), sedModel.getId(), utcSim.getId());
sedmlModel.addTask(sedmlTask);
// to be used later to add dataGenerators : one set of DGs per model (simContext).
taskRef = taskId;
} else if (!scannedParamHash.isEmpty() && unscannedParamHash.isEmpty()) {
// only parameters with scans : only add 1 Task and 1 RepeatedTask
String taskId = "tsk_" + simContextCnt + "_" + simCount;
Task sedmlTask = new Task(taskId, vcSimulation.getName(), simContextId, utcSim.getId());
sedmlModel.addTask(sedmlTask);
String repeatedTaskId = "repTsk_" + simContextCnt + "_" + simCount;
// TODO: temporary solution - we use as range here the first range
String scn = scannedConstantsNames[0];
String rId = "range_" + simContextCnt + "_" + simCount + "_" + scn;
RepeatedTask rt = new RepeatedTask(repeatedTaskId, repeatedTaskId, true, rId);
// to be used later to add dataGenerators - in our case it has to be the repeated task
taskRef = repeatedTaskId;
SubTask subTask = new SubTask("0", taskId);
rt.addSubtask(subTask);
for (String scannedConstName : scannedConstantsNames) {
ConstantArraySpec constantArraySpec = mathOverrides.getConstantArraySpec(scannedConstName);
String rangeId = "range_" + simContextCnt + "_" + simCount + "_" + scannedConstName;
// list of Ranges, if sim is parameter scan.
if (constantArraySpec != null) {
Range r = null;
// System.out.println(" " + constantArraySpec.toString());
if (constantArraySpec.getType() == ConstantArraySpec.TYPE_INTERVAL) {
// ------ Uniform Range
r = new UniformRange(rangeId, constantArraySpec.getMinValue(), constantArraySpec.getMaxValue(), constantArraySpec.getNumValues());
rt.addRange(r);
} else {
// ----- Vector Range
cbit.vcell.math.Constant[] cs = constantArraySpec.getConstants();
ArrayList<Double> values = new ArrayList<Double>();
for (int i = 0; i < cs.length; i++) {
String value = cs[i].getExpression().infix();
values.add(Double.parseDouble(value));
}
r = new VectorRange(rangeId, values);
rt.addRange(r);
}
// list of Changes
SymbolTableEntry ste = getSymbolTableEntryForModelEntity(mathSymbolMapping, scannedConstName);
XPathTarget target = getTargetXPath(ste, l2gMap);
// ASTNode math1 = new ASTCi(r.getId()); // was scannedConstName
ASTNode math1 = Libsedml.parseFormulaString(r.getId());
SetValue setValue = new SetValue(target, r.getId(), simContextId);
setValue.setMath(math1);
rt.addChange(setValue);
} else {
throw new RuntimeException("No scan ranges found for scanned parameter : '" + scannedConstName + "'.");
}
}
sedmlModel.addTask(rt);
} else {
// both scanned and simple parameters : create new model with change for each simple override; add RepeatedTask
// create new model with change for each unscanned parameter that has override
String overriddenSimContextId = simContextId + "_" + overrideCount;
String overriddenSimContextName = simContextName + " modified";
Model sedModel = new Model(overriddenSimContextId, overriddenSimContextName, sbmlLanguageURN, simContextId);
overrideCount++;
String taskId = "tsk_" + simContextCnt + "_" + simCount;
Task sedmlTask = new Task(taskId, vcSimulation.getName(), overriddenSimContextId, utcSim.getId());
sedmlModel.addTask(sedmlTask);
// scanned parameters
String repeatedTaskId = "repTsk_" + simContextCnt + "_" + simCount;
// TODO: temporary solution - we use as range here the first range
String scn = scannedConstantsNames[0];
String rId = "range_" + simContextCnt + "_" + simCount + "_" + scn;
RepeatedTask rt = new RepeatedTask(repeatedTaskId, repeatedTaskId, true, rId);
// to be used later to add dataGenerators - in our case it has to be the repeated task
taskRef = repeatedTaskId;
SubTask subTask = new SubTask("0", taskId);
rt.addSubtask(subTask);
for (String scannedConstName : scannedConstantsNames) {
ConstantArraySpec constantArraySpec = mathOverrides.getConstantArraySpec(scannedConstName);
String rangeId = "range_" + simContextCnt + "_" + simCount + "_" + scannedConstName;
// list of Ranges, if sim is parameter scan.
if (constantArraySpec != null) {
Range r = null;
// System.out.println(" " + constantArraySpec.toString());
if (constantArraySpec.getType() == ConstantArraySpec.TYPE_INTERVAL) {
// ------ Uniform Range
r = new UniformRange(rangeId, constantArraySpec.getMinValue(), constantArraySpec.getMaxValue(), constantArraySpec.getNumValues());
rt.addRange(r);
} else {
// ----- Vector Range
cbit.vcell.math.Constant[] cs = constantArraySpec.getConstants();
ArrayList<Double> values = new ArrayList<Double>();
for (int i = 0; i < cs.length; i++) {
String value = cs[i].getExpression().infix() + ", ";
values.add(Double.parseDouble(value));
}
r = new VectorRange(rangeId, values);
rt.addRange(r);
}
// use scannedParamHash to store rangeId for that param, since it might be needed if unscanned param has a scanned param in expr.
if (scannedParamHash.get(scannedConstName).equals(scannedConstName)) {
// the hash was originally populated as <scannedParamName, scannedParamName>. Replace 'value' with rangeId for scannedParam
scannedParamHash.put(scannedConstName, r.getId());
}
// create setValue for scannedConstName
SymbolTableEntry ste2 = getSymbolTableEntryForModelEntity(mathSymbolMapping, scannedConstName);
XPathTarget target1 = getTargetXPath(ste2, l2gMap);
ASTNode math1 = new ASTCi(scannedConstName);
SetValue setValue1 = new SetValue(target1, r.getId(), sedModel.getId());
setValue1.setMath(math1);
rt.addChange(setValue1);
} else {
throw new RuntimeException("No scan ranges found for scanned parameter : '" + scannedConstName + "'.");
}
}
// for unscanned parameter overrides
for (String unscannedParamName : unscannedParamHash.values()) {
SymbolTableEntry ste = getSymbolTableEntryForModelEntity(mathSymbolMapping, unscannedParamName);
Expression unscannedParamExpr = mathOverrides.getActualExpression(unscannedParamName, 0);
if (unscannedParamExpr.isNumeric()) {
// if expression is numeric, add ChangeAttribute to model created above
XPathTarget targetXpath = getTargetAttributeXPath(ste, l2gMap);
ChangeAttribute changeAttribute = new ChangeAttribute(targetXpath, unscannedParamExpr.infix());
sedModel.addChange(changeAttribute);
} else {
// check for any scanned parameter in unscanned parameter expression
ASTNode math = Libsedml.parseFormulaString(unscannedParamExpr.infix());
String[] exprSymbols = unscannedParamExpr.getSymbols();
boolean bHasScannedParameter = false;
String scannedParamNameInUnscannedParamExp = null;
for (String symbol : exprSymbols) {
if (scannedParamHash.get(symbol) != null) {
bHasScannedParameter = true;
scannedParamNameInUnscannedParamExp = new String(symbol);
// @TODO check for multiple scannedParameters in expression.
break;
}
}
// (scanned parameter in expr) ? (add setValue for unscanned param in repeatedTask) : (add computeChange to modifiedModel)
if (bHasScannedParameter && scannedParamNameInUnscannedParamExp != null) {
// create setValue for unscannedParamName (which contains a scanned param in its expression)
SymbolTableEntry entry = getSymbolTableEntryForModelEntity(mathSymbolMapping, unscannedParamName);
XPathTarget target = getTargetXPath(entry, l2gMap);
String rangeId = scannedParamHash.get(scannedParamNameInUnscannedParamExp);
// @TODO: we have no range??
SetValue setValue = new SetValue(target, rangeId, sedModel.getId());
setValue.setMath(math);
rt.addChange(setValue);
} else {
// non-numeric expression : add 'computeChange' to modified model
XPathTarget targetXpath = getTargetXPath(ste, l2gMap);
ComputeChange computeChange = new ComputeChange(targetXpath, math);
for (String symbol : exprSymbols) {
String symbolName = TokenMangler.mangleToSName(symbol);
SymbolTableEntry ste1 = vcModel.getEntry(symbol);
// ste1 could be a math parameter, hence the above could return null
if (ste1 == null) {
ste1 = simContext.getMathDescription().getEntry(symbol);
}
if (ste1 != null) {
if (ste1 instanceof SpeciesContext || ste1 instanceof Structure || ste1 instanceof ModelParameter) {
XPathTarget ste1_XPath = getTargetXPath(ste1, l2gMap);
org.jlibsedml.Variable sedmlVar = new org.jlibsedml.Variable(symbolName, symbolName, taskRef, ste1_XPath.getTargetAsString());
computeChange.addVariable(sedmlVar);
} else {
double doubleValue = 0.0;
if (ste1 instanceof ReservedSymbol) {
doubleValue = getReservedSymbolValue(ste1);
} else if (ste instanceof Function) {
try {
doubleValue = ste.getExpression().evaluateConstant();
} catch (Exception e) {
e.printStackTrace(System.out);
throw new RuntimeException("Unable to evaluate function '" + ste.getName() + "' used in '" + unscannedParamName + "' expression : ", e);
}
} else {
doubleValue = ste.getConstantValue();
}
// TODO: shouldn't be s1_init_uM which is a math symbol, should be s0 (so use the ste-something from above)
// TODO: revert to Variable, not Parameter
Parameter sedmlParameter = new Parameter(symbolName, symbolName, doubleValue);
computeChange.addParameter(sedmlParameter);
}
} else {
throw new RuntimeException("Symbol '" + symbol + "' used in expression for '" + unscannedParamName + "' not found in model.");
}
}
sedModel.addChange(computeChange);
}
}
}
sedmlModel.addModel(sedModel);
sedmlModel.addTask(rt);
}
} else {
// no math overrides, add basic task.
String taskId = "tsk_" + simContextCnt + "_" + simCount;
// temporary workaround
// TODO better fix
simContextId = sbmlExportFailed ? bioModelID : simContextId;
Task sedmlTask = new Task(taskId, vcSimulation.getName(), simContextId, utcSim.getId());
sedmlModel.addTask(sedmlTask);
// to be used later to add dataGenerators : one set of DGs per model (simContext).
taskRef = taskId;
}
// 4 ------->
// Create DataGenerators
List<DataGenerator> dataGeneratorsOfSim = new ArrayList<DataGenerator>();
// add one DataGenerator for 'time'
String timeDataGenPrefix = DATAGENERATOR_TIME_NAME + "_" + taskRef;
DataGenerator timeDataGen = sedmlModel.getDataGeneratorWithId(timeDataGenPrefix);
org.jlibsedml.Variable timeVar = new org.jlibsedml.Variable(DATAGENERATOR_TIME_SYMBOL + "_" + taskRef, DATAGENERATOR_TIME_SYMBOL, taskRef, VariableSymbol.TIME);
ASTNode math = Libsedml.parseFormulaString(DATAGENERATOR_TIME_SYMBOL + "_" + taskRef);
timeDataGen = new DataGenerator(timeDataGenPrefix, timeDataGenPrefix, math);
timeDataGen.addVariable(timeVar);
sedmlModel.addDataGenerator(timeDataGen);
dataGeneratorsOfSim.add(timeDataGen);
// add dataGenerators for species
// get species list from SBML model.
// Map<String, String> name2IdMap = new LinkedHashMap<> ();
String dataGenIdPrefix = "dataGen_" + taskRef;
if (sbmlExportFailed) {
// we try vcml export
for (SpeciesContext sc : vcModel.getSpeciesContexts()) {
String varName = sc.getName();
String varId = varName + "_" + taskRef;
// name2IdMap.put(varName, varId);
ASTNode varMath = Libsedml.parseFormulaString(varId);
String dataGenId = dataGenIdPrefix + "_" + TokenMangler.mangleToSName(varName);
DataGenerator dataGen = new DataGenerator(dataGenId, dataGenId, varMath);
org.jlibsedml.Variable variable = new org.jlibsedml.Variable(varId, varName, taskRef, XmlHelper.getXPathForSpecies(varName));
dataGen.addVariable(variable);
sedmlModel.addDataGenerator(dataGen);
dataGeneratorsOfSim.add(dataGen);
}
} else {
String[] varNamesList = SimSpec.fromSBML(sbmlString).getVarsList();
for (String varName : varNamesList) {
String varId = varName + "_" + taskRef;
// name2IdMap.put(varName, varId);
org.jlibsedml.Variable sedmlVar = new org.jlibsedml.Variable(varId, varName, taskRef, sbmlSupport.getXPathForSpecies(varName));
ASTNode varMath = Libsedml.parseFormulaString(varId);
// "dataGen_" + varCount; - old code
String dataGenId = dataGenIdPrefix + "_" + TokenMangler.mangleToSName(varName);
DataGenerator dataGen = new DataGenerator(dataGenId, dataGenId, varMath);
dataGen.addVariable(sedmlVar);
sedmlModel.addDataGenerator(dataGen);
dataGeneratorsOfSim.add(dataGen);
}
}
// add DataGenerators for output functions here
ArrayList<AnnotatedFunction> outputFunctions = simContext.getOutputFunctionContext().getOutputFunctionsList();
for (AnnotatedFunction annotatedFunction : outputFunctions) {
// Expression originalFunctionExpression = annotatedFunction.getExpression();
// Expression modifiedFunctionExpr = new Expression(annotatedFunction.getExpression());
// System.out.println("Before: " + originalFunctionExpression);
// String[] symbols = modifiedFunctionExpr.getSymbols();
// for(String symbol : symbols) {
// String id = name2IdMap.get(symbol);
// if(id == null) {
// System.err.println("Could not find id for " + symbol);
// } else {
// modifiedFunctionExpr.substituteInPlace(new Expression(symbol), new Expression(id));
// }
// }
// System.out.println("After: " + modifiedFunctionExpr);
// ASTNode funcMath = Libsedml.parseFormulaString(modifiedFunctionExpr.infix());
// "dataGen_" + varCount; - old code
String dataGenId = dataGenIdPrefix + "_" + TokenMangler.mangleToSName(annotatedFunction.getName());
String varId = TokenMangler.mangleToSName(annotatedFunction.getName()) + taskRef;
if (sbmlExportFailed) {
// VCML
Expression exp = new Expression(varId);
ASTNode funcMath = Libsedml.parseFormulaString(exp.infix());
DataGenerator dataGen = new DataGenerator(dataGenId, dataGenId, funcMath);
org.jlibsedml.Variable sedmlVar = new org.jlibsedml.Variable(varId, annotatedFunction.getName(), taskRef, XmlHelper.getXPathForOutputFunction(simContextName, annotatedFunction.getName()));
dataGen.addVariable(sedmlVar);
sedmlModel.addDataGenerator(dataGen);
dataGeneratorsOfSim.add(dataGen);
} else {
// SBML
}
// String[] functionSymbols = originalFunctionExpression.getSymbols();
// for (String symbol : functionSymbols) {
// String symbolName = TokenMangler.mangleToSName(symbol);
// // try to get symbol from model, if null, try simContext.mathDesc
// SymbolTableEntry ste = vcModel.getEntry(symbol);
// if (ste == null) {
// ste = simContext.getMathDescription().getEntry(symbol);
// }
// if (ste instanceof SpeciesContext || ste instanceof Structure || ste instanceof ModelParameter) {
// XPathTarget targetXPath = getTargetXPath(ste, l2gMap);
// if(sbmlExportFailed) { // VCML
// if(ste instanceof SpeciesContext) {
// // String varId = symbolName + "_" + taskRef;
// // org.jlibsedml.Variable sedmlVar = new org.jlibsedml.Variable(varId, symbolName, taskRef, XmlHelper.getXPathForSpecies(symbolName));
// // dataGen.addVariable(sedmlVar);
// } else {
// System.err.println("Not a species");
// }
// } else { // SBML
// // String varId = symbolName + "_" + taskRef;
// // org.jlibsedml.Variable sedmlVar = new org.jlibsedml.Variable(varId, symbolName, taskRef, targetXPath.getTargetAsString());
// // dataGen.addVariable(sedmlVar);
// }
// } else {
// double value = 0.0;
// if (ste instanceof Function) {
// try {
// value = ste.getExpression().evaluateConstant();
// } catch (Exception e) {
// e.printStackTrace(System.out);
// throw new RuntimeException("Unable to evaluate function '" + ste.getName() + "' for output function '" + annotatedFunction.getName() + "'.", e);
// }
// } else {
// value = ste.getConstantValue();
// }
// Parameter sedmlParameter = new Parameter(symbolName, symbolName, value);
// dataGen.addParameter(sedmlParameter);
// }
// }
}
// ignoring output for spatial deterministic (spatial stochastic is not exported to SEDML) and non-spatial stochastic applications with histogram
if (!(simContext.getGeometry().getDimension() > 0)) {
String plot2dId = "plot2d_" + TokenMangler.mangleToSName(vcSimulation.getName());
String reportId = "report_" + TokenMangler.mangleToSName(vcSimulation.getName());
// String reportId = "__plot__" + plot2dId;
String plotName = simContextName + "_" + simName + "_plot";
Plot2D sedmlPlot2d = new Plot2D(plot2dId, plotName);
Report sedmlReport = new Report(reportId, plotName);
sedmlPlot2d.addNote(createNotesElement("Plot of all variables and output functions from application '" + simContext.getName() + "' ; simulation '" + vcSimulation.getName() + "' in VCell model"));
sedmlReport.addNote(createNotesElement("Report of all variables and output functions from application '" + simContext.getName() + "' ; simulation '" + vcSimulation.getName() + "' in VCell model"));
DataGenerator dgtime = sedmlModel.getDataGeneratorWithId(DATAGENERATOR_TIME_NAME + "_" + taskRef);
String xDataRef = dgtime.getId();
String xDatasetXId = "__data_set__" + plot2dId + dgtime.getId();
// id, name, label, data generator reference
DataSet dataSet = new DataSet(xDatasetXId, DATAGENERATOR_TIME_NAME, xDataRef, xDataRef);
sedmlReport.addDataSet(dataSet);
// add a curve for each dataGenerator in SEDML model
int curveCnt = 0;
// String id, String name, ASTNode math
for (DataGenerator dg : dataGeneratorsOfSim) {
// no curve for time, since time is xDateReference
if (dg.getId().equals(xDataRef)) {
continue;
}
String curveId = "curve_" + plot2dId + "_" + dg.getName();
String datasetYId = "__data_set__" + plot2dId + dg.getName();
Curve curve = new Curve(curveId, dg.getName(), false, false, xDataRef, dg.getId());
sedmlPlot2d.addCurve(curve);
// // id, name, label, dataRef
// // dataset id <- unique id
// // dataset name <- data generator name
// // dataset label <- dataset id
DataSet yDataSet = new DataSet(datasetYId, dg.getName(), dg.getId(), dg.getId());
sedmlReport.addDataSet(yDataSet);
curveCnt++;
}
sedmlModel.addOutput(sedmlPlot2d);
sedmlModel.addOutput(sedmlReport);
} else {
// spatial deterministic
if (simContext.getApplicationType().equals(Application.NETWORK_DETERMINISTIC)) {
// we ignore spatial stochastic (Smoldyn)
if (bForceVCML) {
String reportId = "_report_" + TokenMangler.mangleToSName(vcSimulation.getName());
Report sedmlReport = new Report(reportId, simContext.getName() + "plots");
String xDataRef = sedmlModel.getDataGeneratorWithId(DATAGENERATOR_TIME_NAME + "_" + taskRef).getId();
String xDatasetXId = "datasetX_" + DATAGENERATOR_TIME_NAME + "_" + timeDataGen.getId();
DataSet dataSetTime = new DataSet(xDatasetXId, xDataRef, xDatasetXId, xDataRef);
sedmlReport.addDataSet(dataSetTime);
int surfaceCnt = 0;
for (DataGenerator dg : dataGeneratorsOfSim) {
if (dg.getId().equals(xDataRef)) {
continue;
}
// String datasetYId = "datasetY_" + surfaceCnt;
String datasetYId = "__data_set__" + surfaceCnt + "_" + dg.getName();
DataSet yDataSet = new DataSet(datasetYId, dg.getName(), datasetYId, dg.getId());
sedmlReport.addDataSet(yDataSet);
surfaceCnt++;
}
sedmlModel.addOutput(sedmlReport);
} else {
// spatial deterministic SBML
// TODO: add surfaces to the plots
String plot3dId = "plot3d_" + TokenMangler.mangleToSName(vcSimulation.getName());
String reportId = "report_" + TokenMangler.mangleToSName(vcSimulation.getName());
String plotName = simContext.getName() + "plots";
Plot3D sedmlPlot3d = new Plot3D(plot3dId, plotName);
Report sedmlReport = new Report(reportId, plotName);
sedmlPlot3d.addNote(createNotesElement("Plot of all variables and output functions from application '" + simContext.getName() + "' ; simulation '" + vcSimulation.getName() + "' in VCell model"));
sedmlReport.addNote(createNotesElement("Report of all variables and output functions from application '" + simContext.getName() + "' ; simulation '" + vcSimulation.getName() + "' in VCell model"));
DataGenerator dgtime = sedmlModel.getDataGeneratorWithId(DATAGENERATOR_TIME_NAME + "_" + taskRef);
String xDataRef = dgtime.getId();
String xDatasetXId = "__data_set__" + plot3dId + dgtime.getId();
// id, name, label, data generator reference
DataSet dataSet = new DataSet(xDatasetXId, DATAGENERATOR_TIME_NAME, xDataRef, xDataRef);
sedmlReport.addDataSet(dataSet);
// add a curve for each dataGenerator in SEDML model
int curveCnt = 0;
// String id, String name, ASTNode math
for (DataGenerator dg : dataGeneratorsOfSim) {
// no curve for time, since time is xDateReference
if (dg.getId().equals(xDataRef)) {
continue;
}
String curveId = "curve_" + plot3dId + "_" + dg.getName();
String datasetYId = "__data_set__" + plot3dId + dg.getName();
DataSet yDataSet = new DataSet(datasetYId, dg.getName(), dg.getId(), dg.getId());
sedmlReport.addDataSet(yDataSet);
curveCnt++;
}
sedmlModel.addOutput(sedmlReport);
}
}
}
simCount++;
}
// end - for 'sims'
simContextCnt++;
}
// if sedmlNotesStr is not null, there were some applications that could not be exported to SEDML (eg., spatial stochastic). Create a notes element and add it to sedml Model.
if (sedmlNotesStr.length() > 0) {
sedmlNotesStr = "\n\tThe following applications in the VCell model were not exported to VCell : " + sedmlNotesStr;
sedmlModel.addNote(createNotesElement(sedmlNotesStr));
}
if (sedmlModel.getModels() != null && sedmlModel.getModels().size() > 1) {
System.out.println("Number of models in the sedml is " + sedmlModel.getModels().size());
}
} catch (Exception e) {
e.printStackTrace(System.out);
throw new RuntimeException("Error adding model to SEDML document : " + e.getMessage());
}
}
Aggregations