use of cbit.vcell.mapping.SimulationContext in project vcell by virtualcell.
the class ViewGeneratedReactionsPanel method updateShape.
public void updateShape(int selectedRow) {
GeneratedReactionTableRow reactionTableRow = tableModel.getValueAt(selectedRow);
String inputString = reactionTableRow.getExpression();
System.out.println(selectedRow + ": " + inputString);
// ReactionRule newReactionRule = (ReactionRule)RbmUtils.parseReactionRule(inputString, bioModel);
Model tempModel = null;
try {
tempModel = new Model("MyTempModel");
tempModel.addFeature("c0");
} catch (ModelException | PropertyVetoException e1) {
e1.printStackTrace();
}
if (owner != null && owner.getSimulationContext() != null) {
List<MolecularType> mtList = owner.getSimulationContext().getModel().getRbmModelContainer().getMolecularTypeList();
try {
tempModel.getRbmModelContainer().setMolecularTypeList(mtList);
} catch (PropertyVetoException e1) {
e1.printStackTrace();
throw new RuntimeException("Unexpected exception setting " + MolecularType.typeName + " list: " + e1.getMessage(), e1);
}
} else {
// This should not be possible
throw new RuntimeException("Owner or SimulationContext are null.");
}
int arrowIndex = inputString.indexOf("<->");
boolean bReversible = true;
if (arrowIndex < 0) {
arrowIndex = inputString.indexOf("->");
bReversible = false;
}
String left = inputString.substring(0, arrowIndex).trim();
String right = inputString.substring(arrowIndex + (bReversible ? 3 : 2)).trim();
if (left.length() == 0 && right.length() == 0) {
return;
}
// we recover the original rule that generated the flattened reaction we now try to transform back into a fake rule
BNGReaction reactionObject = reactionTableRow.getReactionObject();
String name = reactionObject.getRuleName();
if (name.contains(GeneratedReactionTableModel.reverse)) {
name = name.substring(GeneratedReactionTableModel.reverse.length());
}
if (name.endsWith(ReactionRule.DirectHalf)) {
name = name.substring(0, name.indexOf(ReactionRule.DirectHalf));
}
if (name.endsWith(ReactionRule.InverseHalf)) {
name = name.substring(0, name.indexOf(ReactionRule.InverseHalf));
}
// get the name of the original structure from the original rule and make here another structure with the same name
String strStructure = null;
Structure ruleStructure;
SimulationContext sc = owner.getSimulationContext();
ReactionRule rr = sc.getModel().getRbmModelContainer().getReactionRule(name);
if (rr != null && rr.getStructure() != null) {
strStructure = rr.getStructure().getName();
}
if (strStructure != null) {
if (tempModel.getStructure(strStructure) == null) {
try {
if (rr.getStructure().getTypeName().equals(Structure.TYPE_NAME_MEMBRANE)) {
tempModel.addMembrane(strStructure);
} else {
tempModel.addFeature(strStructure);
}
} catch (ModelException | PropertyVetoException e) {
e.printStackTrace();
}
}
ruleStructure = tempModel.getStructure(strStructure);
} else {
throw new RuntimeException("Failed to recover a Structure name from the Reaction Rule: " + name);
}
// making the fake rules just for display purpose, actually they are the flattened reactions resulted from bngl
// the name is probably not unique, it's likely that many flattened reactions are derived from the same rule
ReactionRule reactionRule = tempModel.getRbmModelContainer().createReactionRule(name, ruleStructure, bReversible);
String regex = "[^!]\\+";
String[] patterns = left.split(regex);
for (String spString : patterns) {
try {
spString = spString.trim();
// if compartments are present, we're cheating big time making some fake compartments just for compartment name display purposes
SpeciesPattern speciesPattern = (SpeciesPattern) RbmUtils.parseSpeciesPattern(spString, tempModel);
strStructure = RbmUtils.parseCompartment(spString, tempModel);
speciesPattern.resolveBonds();
Structure structure;
if (strStructure != null) {
if (tempModel.getStructure(strStructure) == null) {
if (sc.getModel().getStructure(strStructure).getTypeName().equals(Structure.TYPE_NAME_MEMBRANE)) {
tempModel.addMembrane(strStructure);
} else {
tempModel.addFeature(strStructure);
}
}
structure = tempModel.getStructure(strStructure);
} else {
// if nothing explicit for a participant, we use by default the structure of the rule
structure = ruleStructure;
}
reactionRule.addReactant(new ReactantPattern(speciesPattern, structure));
} catch (Throwable ex) {
ex.printStackTrace();
// error (red circle)
SpeciesPatternLargeShape spls = new SpeciesPatternLargeShape(20, 20, -1, shapePanel, true, issueManager);
reactantPatternShapeList.clear();
productPatternShapeList.clear();
reactantPatternShapeList.add(spls);
shapePanel.repaint();
return;
}
}
patterns = right.split(regex);
for (String spString : patterns) {
try {
spString = spString.trim();
SpeciesPattern speciesPattern = (SpeciesPattern) RbmUtils.parseSpeciesPattern(spString, tempModel);
strStructure = RbmUtils.parseCompartment(spString, tempModel);
speciesPattern.resolveBonds();
Structure structure;
if (strStructure != null) {
if (tempModel.getStructure(strStructure) == null) {
if (sc.getModel().getStructure(strStructure).getTypeName().equals(Structure.TYPE_NAME_MEMBRANE)) {
tempModel.addMembrane(strStructure);
} else {
tempModel.addFeature(strStructure);
}
}
structure = tempModel.getStructure(strStructure);
} else {
structure = ruleStructure;
}
// BNGLParser parser = new BNGLParser(new StringReader(sp));
// ASTSpeciesPattern astSpeciesPattern = parser.SpeciesPattern();
// BnglObjectConstructionVisitor constructionVisitor = new BnglObjectConstructionVisitor(tempModel, null, false);
// SpeciesPattern speciesPattern = (SpeciesPattern) astSpeciesPattern.jjtAccept(constructionVisitor, null);
// for(MolecularTypePattern mtp : speciesPattern.getMolecularTypePatterns()) {
// mtp.setParticipantMatchLabel("*");
// }
// System.out.println(speciesPattern.toString());
reactionRule.addProduct(new ProductPattern(speciesPattern, structure));
} catch (Throwable ex) {
ex.printStackTrace();
// error (red circle)
SpeciesPatternLargeShape spls = new SpeciesPatternLargeShape(20, 20, -1, shapePanel, true, issueManager);
reactantPatternShapeList.clear();
productPatternShapeList.clear();
reactantPatternShapeList.add(spls);
shapePanel.repaint();
return;
}
}
// ----------------------------------------------------------------------------------------------------
List<ReactantPattern> rpList = reactionRule.getReactantPatterns();
reactantPatternShapeList.clear();
int xOffset = 20;
int xOffsetRound = 20;
if (rpList != null && rpList.size() > 0) {
for (int i = 0; i < rpList.size(); i++) {
SpeciesPattern sp = rpList.get(i).getSpeciesPattern();
for (MolecularTypePattern mtp : sp.getMolecularTypePatterns()) {
mtp.setParticipantMatchLabel("*");
}
SpeciesPatternLargeShape sps = new SpeciesPatternLargeShape(xOffset, 20, -1, sp, shapePanel, reactionRule, issueManager);
// SpeciesPatternRoundShape sps = new SpeciesPatternRoundShape(xOffsetRound, 20, -1, sp, shapePanel, reactionRule);
if (i < rpList.size() - 1) {
sps.addEndText("+");
} else {
if (reactionRule.isReversible()) {
sps.addEndText("<->");
} else {
sps.addEndText("->");
}
}
xOffset = sps.getRightEnd() + 45;
xOffsetRound = sps.getRightEnd() + 45;
reactantPatternShapeList.add(sps);
}
}
// space for the <-> sign
xOffset += 15;
List<ProductPattern> ppList = reactionRule.getProductPatterns();
productPatternShapeList.clear();
if (ppList != null && ppList.size() > 0) {
for (int i = 0; i < ppList.size(); i++) {
SpeciesPattern sp = ppList.get(i).getSpeciesPattern();
for (MolecularTypePattern mtp : sp.getMolecularTypePatterns()) {
mtp.setParticipantMatchLabel("*");
}
SpeciesPatternLargeShape sps = new SpeciesPatternLargeShape(xOffset, 20, -1, sp, shapePanel, reactionRule, issueManager);
// SpeciesPatternRoundShape sps = new SpeciesPatternRoundShape(xOffset, 20, -1, sp, shapePanel, reactionRule);
if (i < ppList.size() - 1) {
sps.addEndText("+");
}
xOffset = sps.getRightEnd() + 45;
productPatternShapeList.add(sps);
}
}
Dimension preferredSize = new Dimension(xOffset + 90, 50);
shapePanel.setPreferredSize(preferredSize);
shapePanel.repaint();
}
use of cbit.vcell.mapping.SimulationContext in project vcell by virtualcell.
the class ParameterMappingPanel method jMenuItemPaste_ActionPerformed.
/**
* Comment
*/
private void jMenuItemPaste_ActionPerformed(java.awt.event.ActionEvent actionEvent) {
java.util.Vector<String> pasteDescriptionsV = new java.util.Vector<String>();
java.util.Vector<Expression> newExpressionsV = new java.util.Vector<Expression>();
java.util.Vector<ParameterMappingSpec> changedParametersV = new java.util.Vector<ParameterMappingSpec>();
try {
if (actionEvent.getSource() == getJMenuItemPaste() || actionEvent.getSource() == getJMenuItemPasteAll()) {
Object pasteThis = VCellTransferable.getFromClipboard(VCellTransferable.OBJECT_FLAVOR);
SimulationContext sc = getParameterEstimationTask().getModelOptimizationSpec().getSimulationContext();
MathSymbolMapping msm = null;
Exception mathMappingException = null;
try {
MathMapping mm = sc.createNewMathMapping();
msm = mm.getMathSymbolMapping();
} catch (Exception e) {
mathMappingException = e;
e.printStackTrace(System.out);
}
// if(msm == null){
// try{
// getParameterEstimationTask().refreshMappings();
// msm = getParameterEstimationTask().getMathSymbolMapping();
// }catch(Exception e){
// e.printStackTrace();
// }
// }
int[] rows = null;
if (actionEvent.getSource() == getJMenuItemPasteAll()) {
rows = new int[getScrollPaneTable().getRowCount()];
for (int i = 0; i < rows.length; i += 1) {
rows[i] = i;
}
} else {
rows = getScrollPaneTable().getSelectedRows();
}
//
// Check paste
//
StringBuffer errors = null;
for (int i = 0; i < rows.length; i += 1) {
ParameterMappingSpec pms = parameterMappingTableModel.getValueAt(rows[i]);
try {
if (pasteThis instanceof VCellTransferable.ResolvedValuesSelection) {
VCellTransferable.ResolvedValuesSelection rvs = (VCellTransferable.ResolvedValuesSelection) pasteThis;
for (int j = 0; j < rvs.getPrimarySymbolTableEntries().length; j += 1) {
ParameterMappingSpec pasteDestination = null;
Parameter clipboardBiologicalParameter = null;
if (rvs.getPrimarySymbolTableEntries()[j] instanceof Parameter) {
clipboardBiologicalParameter = (Parameter) rvs.getPrimarySymbolTableEntries()[j];
} else if (rvs.getAlternateSymbolTableEntries() != null && rvs.getAlternateSymbolTableEntries()[j] instanceof Parameter) {
clipboardBiologicalParameter = (Parameter) rvs.getAlternateSymbolTableEntries()[j];
}
if (clipboardBiologicalParameter == null) {
Variable pastedMathVariable = null;
if (rvs.getPrimarySymbolTableEntries()[j] instanceof Variable) {
pastedMathVariable = (Variable) rvs.getPrimarySymbolTableEntries()[j];
} else if (rvs.getAlternateSymbolTableEntries() != null && rvs.getAlternateSymbolTableEntries()[j] instanceof Variable) {
pastedMathVariable = (Variable) rvs.getAlternateSymbolTableEntries()[j];
}
if (pastedMathVariable != null) {
if (msm == null) {
throw mathMappingException;
}
Variable localMathVariable = msm.findVariableByName(pastedMathVariable.getName());
if (localMathVariable != null) {
SymbolTableEntry[] localBiologicalSymbolArr = msm.getBiologicalSymbol(localMathVariable);
for (int k = 0; k < localBiologicalSymbolArr.length; k += 1) {
if (localBiologicalSymbolArr[k] == pms.getModelParameter()) {
pasteDestination = pms;
break;
}
}
}
}
} else {
if (pms.getModelParameter().getName().equals(clipboardBiologicalParameter.getName()) && pms.getModelParameter().getClass().equals(clipboardBiologicalParameter.getClass()) && pms.getModelParameter().getNameScope().getName().equals(clipboardBiologicalParameter.getNameScope().getName())) {
pasteDestination = pms;
}
}
if (pasteDestination != null) {
changedParametersV.add(pasteDestination);
newExpressionsV.add(rvs.getExpressionValues()[j]);
pasteDescriptionsV.add(VCellCopyPasteHelper.formatPasteList(pms.getModelParameter().getNameScope().getName(), pms.getModelParameter().getName(), pasteDestination.getCurrent() + "", rvs.getExpressionValues()[j].infix()));
}
}
}
} catch (Throwable e) {
if (errors == null) {
errors = new StringBuffer();
}
errors.append(pms.getModelParameter().getName() + " (" + e.getClass().getName() + ") " + e.getMessage() + "\n");
}
}
if (errors != null) {
throw new Exception(errors.toString());
}
}
} catch (Throwable e) {
PopupGenerator.showErrorDialog(this, "Paste failed during pre-check (no changes made).\n" + e.getMessage(), e);
return;
}
// Do paste
try {
if (pasteDescriptionsV.size() > 0) {
String[] pasteDescriptionArr = new String[pasteDescriptionsV.size()];
pasteDescriptionsV.copyInto(pasteDescriptionArr);
ParameterMappingSpec[] changedParametersArr = new ParameterMappingSpec[changedParametersV.size()];
changedParametersV.copyInto(changedParametersArr);
Expression[] newExpressionsArr = new Expression[newExpressionsV.size()];
newExpressionsV.copyInto(newExpressionsArr);
VCellCopyPasteHelper.chooseApplyPaste(this, pasteDescriptionArr, changedParametersArr, newExpressionsArr);
} else {
PopupGenerator.showInfoDialog(this, "No paste items match the destination (no changes made).");
}
} catch (Throwable e) {
PopupGenerator.showErrorDialog(this, "Paste Error\n" + e.getMessage(), e);
}
}
use of cbit.vcell.mapping.SimulationContext in project vcell by virtualcell.
the class ObservablesGroupTableModel method getValueAt.
public Object getValueAt(int iRow, int iCol) {
ObservablesGroupTableRow observablesTableRow = getValueAt(iRow);
String obsName = observablesTableRow.getObservableGroupObject().getObservableGroupName();
RbmObservable obs = observablesTableRow.getObservable(obsName);
String obsDefinition = ObservablesGroupTableRow.toBnglString(obs);
switch(iCol) {
case iColOriginalName:
return obsName;
case iColStructure:
{
if (obsDefinition.startsWith("@") && obsDefinition.contains(":")) {
String structName = obsDefinition.substring(1, obsDefinition.indexOf(":"));
return structName;
} else {
SimulationContext sc = owner.getSimulationContext();
if (sc.getModel().getStructures().length > 1) {
// if we have more than 1 compartments
return "?";
} else {
Structure struct = sc.getModel().getStructure(0);
return struct.getName();
}
}
}
case iColDepiction:
return obsDefinition;
case iColDefinition:
switch(obs.getSequence()) {
case Multimolecular:
return obsDefinition;
case PolymerLengthEqual:
return obsDefinition + "=" + obs.getSequenceLength();
case PolymerLengthGreater:
return obsDefinition + ">" + obs.getSequenceLength();
default:
return obsDefinition;
}
case iColExpression:
String exp;
BNGSpecies[] speciesList = observablesTableRow.getObservableGroupObject().getListofSpecies();
if (speciesList == null || speciesList.length == 0) {
exp = "<html><font color=\"red\">No generated species</html>";
} else {
exp = getExpressionAsString(observablesTableRow.getObservableGroupObject());
}
return exp;
case iColCount:
return obs.getType().name();
default:
return null;
}
}
use of cbit.vcell.mapping.SimulationContext in project vcell by virtualcell.
the class DefaultScrollTableCellRenderer method getTableCellRendererComponent.
/**
* Insert the method's description here.
* Creation date: (3/27/2001 1:07:02 PM)
* @return java.awt.Component
* @param table javax.swing.JTable
* @param value java.lang.Object
* @param isSelected boolean
* @param hasFocus boolean
* @param row int
* @param column int
*/
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
defaultToolTipText = null;
super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
defaultToolTipText = getToolTipText();
setBorder(DEFAULT_GAP);
if (isSelected) {
setBackground(table.getSelectionBackground());
setForeground(table.getSelectionForeground());
} else {
if (table instanceof ScrollTable && ((ScrollTable) table).getHoverRow() == row) {
setBackground(hoverColor);
} else {
setBackground(row % 2 == 0 ? table.getBackground() : everyOtherRowColor);
}
if (table.getModel() instanceof SpatialProcessTableModel) /* && column == SpatialProcessTableModel.COLUMN_SpatialProcess_SPATIALOBJECTS */
{
boolean found = isMatchWithSelectedObject(table, row);
if (found == true) {
setBackground(Color.yellow);
}
} else if (table.getModel() instanceof SpatialObjectTableModel) /* && column == SpatialObjectTableModel.COLUMN_SpatialObject_NAME */
{
boolean found = isMatchWithSelectedProcess(table, row);
if (found == true) {
setBackground(Color.yellow);
}
}
setForeground(table.getForeground());
}
TableModel tableModel = table.getModel();
if (bEnableUneditableForeground && (!table.isEnabled() || !tableModel.isCellEditable(row, column))) {
if (!isSelected) {
setForeground(uneditableForeground);
if (tableModel instanceof NetworkConstraintsTableModel && column == NetworkConstraintsTableModel.iColValue) {
NetworkConstraintsTableModel tm = (NetworkConstraintsTableModel) tableModel;
String def = (String) tm.getValueAt(row, NetworkConstraintsTableModel.iColDefault);
String val = (String) value;
if (!val.equals(def)) {
value = "<html><b>" + value + "</b></html>";
setForeground(Color.red);
}
}
}
}
if (value instanceof Double) {
Double doubleValue = (Double) value;
setText(nicelyFormattedDouble(doubleValue));
} else if (value instanceof JComponent) {
JComponent jc = (JComponent) value;
if (hasFocus) {
jc.setBorder(focusHighlightBorder);
} else {
jc.setBorder(noFocusBorder);
}
return jc;
}
if (BioModelEditorRightSideTableModel.ADD_NEW_HERE_TEXT.equals(value)) {
setText(BioModelEditorRightSideTableModel.ADD_NEW_HERE_HTML);
} else if (value instanceof ModelProcessEquation && BioModelEditorRightSideTableModel.ADD_NEW_HERE_REACTION_TEXT.equals(((ModelProcessEquation) value).toString())) {
setText(BioModelEditorRightSideTableModel.ADD_NEW_REACTION_OR_RULE_HTML);
}
if (tableModel instanceof BioModelEditorApplicationsTableModel) {
// for the applications table we show the icons with the app type
Icon icon = null;
String toolTipSuffix = "";
BioModelEditorApplicationsTableModel bmeatm = (BioModelEditorApplicationsTableModel) tableModel;
SimulationContext simContext = (SimulationContext) (bmeatm.getValueAt(row));
if (simContext.isRuleBased()) {
if (simContext.getGeometry().getDimension() == 0) {
icon = VCellIcons.appRbmNonspIcon;
toolTipSuffix = "Rule Based / Non spatial";
}
} else if (simContext.isStoch()) {
if (simContext.getGeometry().getDimension() == 0) {
icon = VCellIcons.appStoNonspIcon;
toolTipSuffix = "Stochastic / Non spatial";
} else {
icon = VCellIcons.appStoSpatialIcon;
toolTipSuffix = "Stochastic / Spatial";
}
} else {
// deterministic
if (simContext.getGeometry().getDimension() == 0) {
icon = VCellIcons.appDetNonspIcon;
toolTipSuffix = "Deterministic / Non spatial";
} else {
icon = VCellIcons.appDetSpatialIcon;
toolTipSuffix = "Deterministic / Spatial";
}
}
String toolTipPrefix = "Application: ";
setToolTipText(toolTipPrefix + toolTipSuffix);
if (column == 0) {
setIcon(icon);
} else {
setIcon(null);
}
} else if (column == 2 && tableModel instanceof SpatialProcessTableModel) {
Icon icon = null;
SpatialProcess spatialProcess = (SpatialProcess) (((SpatialProcessTableModel) tableModel).getValueAt(row));
if (spatialProcess instanceof PointLocation) {
icon = VCellIcons.spatialPointIcon;
} else if (spatialProcess instanceof PointKinematics) {
icon = VCellIcons.spatialPointIcon;
} else if (spatialProcess instanceof SurfaceKinematics) {
icon = VCellIcons.spatialMembraneIcon;
} else {
icon = VCellIcons.spatialVolumeIcon;
}
setIcon(icon);
} else if (tableModel instanceof SortTableModel) {
// for most other tables we reserve the icon spot to display issues
DefaultScrollTableCellRenderer.issueRenderer(this, defaultToolTipText, table, row, column, (SortTableModel) tableModel);
}
return this;
}
use of cbit.vcell.mapping.SimulationContext in project vcell by virtualcell.
the class VCellSedMLSolver method doWork.
// everything is done here
public void doWork(ExternalDocInfo externalDocInfo, AbstractTask sedmlTask, SedML sedml) throws Exception {
// create the VCDocument (bioModel + application + simulation), do sanity checks
cbit.util.xml.VCLogger sedmlImportLogger = new LocalLogger();
List<AbstractTask> tasks = new ArrayList<AbstractTask>();
tasks.add(sedmlTask);
List<VCDocument> docs = XmlHelper.sedmlToBioModel(sedmlImportLogger, externalDocInfo, sedml, tasks, null, false);
VCDocument doc = docs.get(0);
sanityCheck(doc);
// create the work directory for this task, invoke the solver
String docName = doc.getName();
String outString = VCellSedMLSolver.OUT_ROOT_STRING + "/" + docName + "/" + sedmlTask.getId();
File outDir = new File(outString);
if (!outDir.exists()) {
outDir.mkdirs();
}
BioModel bioModel = (BioModel) doc;
SimulationContext simContext = bioModel.getSimulationContext(0);
MathDescription mathDesc = simContext.getMathDescription();
String vcml = mathDesc.getVCML();
try (PrintWriter pw = new PrintWriter(outString + "/vcmlTrace.xml")) {
pw.println(vcml);
}
Simulation sim = bioModel.getSimulation(0);
SolverTaskDescription std = sim.getSolverTaskDescription();
SolverDescription sd = std.getSolverDescription();
String kisao = sd.getKisao();
if (SolverDescription.CVODE.getKisao().contentEquals(kisao)) {
ODESolverResultSet odeSolverResultSet = solveCvode(outDir, bioModel);
System.out.println("Finished: " + docName + ": - task '" + sedmlTask.getId() + "'.");
} else if (SolverDescription.StochGibson.getKisao().contentEquals(kisao)) {
ODESolverResultSet odeSolverResultSet = solveGibson(outDir, bioModel);
System.out.println("Finished: " + docName + ": - task '" + sedmlTask.getId() + "'.");
} else if (SolverDescription.IDA.getKisao().contentEquals(kisao)) {
ODESolverResultSet odeSolverResultSet = solveIDA(outDir, bioModel);
System.out.println("Finished: " + docName + ": - task '" + sedmlTask.getId() + "'.");
} else {
System.out.println("Unsupported solver: " + kisao);
}
System.out.println("-------------------------------------------------------------------------");
}
Aggregations