Search in sources :

Example 11 with ExpressionBindingException

use of cbit.vcell.parser.ExpressionBindingException in project vcell by virtualcell.

the class ScopedExpressionTableCellRenderer method getTableCellRendererComponent.

/**
 *  This method is sent to the renderer by the drawing table to
 *  configure the renderer appropriately before drawing.  Return
 *  the Component used for drawing.
 *
 * @param	table		the JTable that is asking the renderer to draw.
 *				This parameter can be null.
 * @param	value		the value of the cell to be rendered.  It is
 *				up to the specific renderer to interpret
 *				and draw the value.  eg. if value is the
 *				String "true", it could be rendered as a
 *				string or it could be rendered as a check
 *				box that is checked.  null is a valid value.
 * @param	isSelected	true is the cell is to be renderer with
 *				selection highlighting
 * @param	row	        the row index of the cell being drawn.  When
 *				drawing the header the rowIndex is -1.
 * @param	column	        the column index of the cell being drawn
 */
public java.awt.Component getTableCellRendererComponent(javax.swing.JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
    try {
        TableModel tableModel = table.getModel();
        if (value == null) {
            templateJLabel.setIcon(null);
            templateJLabel.setText(null);
            templateJLabel.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
            if (tableModel instanceof VCellSortTableModel) {
                if (row < ((VCellSortTableModel<?>) tableModel).getRowCount()) {
                    Object rowObject = ((VCellSortTableModel<?>) tableModel).getValueAt(row);
                    if (rowObject instanceof SpeciesContextSpecParameter) {
                        templateJLabel.setText(((SpeciesContextSpecParameter) rowObject).getNullExpressionDescription());
                    }
                }
            }
            return templateJLabel;
        }
        if (!(value instanceof ScopedExpression)) {
            return stringRenderer.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
        }
        imageRenderer.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
        JLabel renderer = imageRenderer;
        ScopedExpression scopedExpression = (ScopedExpression) value;
        String scopedExpressInfix = scopedExpression.infix();
        ReusableExpressionIcon rei = scopedExpressionImageIconHash.get(scopedExpressInfix);
        if (rei != null && rei.background.equals(imageRenderer.getBackground()) && rei.foreground.equals(imageRenderer.getForeground())) {
            // Re-use existing ImageIcon is it exists and is same state
            imageRenderer.setIcon(rei.imageIcon);
        } else {
            // Create new ImageIcon
            try {
                ExpressionPrintFormatter epf = new ExpressionPrintFormatter(scopedExpression.getRenamedExpression());
                // 
                // Use graphicsContextProvider BufferedImage to get started because
                // theTable may have a null GC and epf needs a non-null GC
                // 
                java.awt.Graphics2D tempG2D = (java.awt.Graphics2D) graphicsContextProvider.getGraphics();
                // Must set here before epf.getSize is called
                tempG2D.setFont(italicFont);
                // Determine how big the expression image will be
                java.awt.Dimension dim = epf.getSize(tempG2D);
                // Create and render the expression image
                java.awt.image.BufferedImage bi = new java.awt.image.BufferedImage(dim.width, dim.height, java.awt.image.BufferedImage.TYPE_INT_RGB);
                java.awt.Graphics2D g2d = bi.createGraphics();
                // epf.paint needs a non-null clipBounds
                g2d.setClip(0, 0, dim.width, dim.height);
                // set the SAME font used in epf.getSize
                g2d.setFont(italicFont);
                if (table != null && imageRenderer != null) {
                    g2d.setBackground(imageRenderer.getBackground());
                    g2d.setColor(imageRenderer.getForeground());
                }
                // paint background
                g2d.clearRect(0, 0, dim.width, dim.height);
                // paint expression into image
                epf.paint(g2d);
                // Limit cacheing in case a large number of DIFFERENT expressions are being serviced by this TableCellRenderer.
                if ((scopedExpressionCacheSize + (dim.width * dim.height)) >= CACHE_SIZE_LIMIT) {
                    scopedExpressionImageIconHash.clear();
                    scopedExpressionCacheSize = 0;
                }
                javax.swing.ImageIcon newImageIcon = new javax.swing.ImageIcon(bi);
                rei = new ReusableExpressionIcon(newImageIcon, imageRenderer.getBackground(), imageRenderer.getForeground());
                if (scopedExpressionImageIconHash.put(scopedExpressInfix, rei) == null) {
                    scopedExpressionCacheSize += dim.width * dim.height;
                }
                imageRenderer.setIcon(newImageIcon);
            } catch (Exception e) {
                // Fallback to String
                e.printStackTrace();
                templateJLabel.setText(scopedExpression.infix());
                renderer = templateJLabel;
            }
        }
        ExpressionBindingException expressionBindingException = scopedExpression.getExpressionBindingException();
        if (expressionBindingException != null) {
            renderer.setBorder(BorderFactory.createLineBorder(Color.red));
            renderer.setToolTipText(expressionBindingException.getMessage());
        } else {
            renderer.setBorder(BorderFactory.createEmptyBorder());
            renderer.setToolTipText(null);
        }
        if (tableModel instanceof VCellSortTableModel) {
            List<Issue> issueList = ((VCellSortTableModel<?>) tableModel).getIssues(row, column, Issue.SEVERITY_ERROR);
            if (issueList.size() > 0) {
                renderer.setToolTipText(Issue.getHtmlIssueMessage(issueList));
                if (column == 0) {
                    renderer.setBorder(new MatteBorder(1, 1, 1, 0, Color.red));
                } else if (column == table.getColumnCount() - 1) {
                    renderer.setBorder(new MatteBorder(1, 0, 1, 1, Color.red));
                } else {
                    renderer.setBorder(new MatteBorder(1, 0, 1, 0, Color.red));
                }
            } else {
                renderer.setBorder(BORDER);
            }
        }
        return renderer;
    } catch (Exception e) {
        e.printStackTrace();
        templateJLabel.setText("ScopedExpressionTableCellRenderer Error - " + e.getMessage() + " " + value);
        return templateJLabel;
    }
}
Also used : ImageIcon(javax.swing.ImageIcon) Issue(org.vcell.util.Issue) MatteBorder(javax.swing.border.MatteBorder) ExpressionPrintFormatter(cbit.vcell.parser.ExpressionPrintFormatter) VCellSortTableModel(cbit.vcell.client.desktop.biomodel.VCellSortTableModel) ImageIcon(javax.swing.ImageIcon) SpeciesContextSpecParameter(cbit.vcell.mapping.SpeciesContextSpec.SpeciesContextSpecParameter) JLabel(javax.swing.JLabel) ExpressionBindingException(cbit.vcell.parser.ExpressionBindingException) ExpressionBindingException(cbit.vcell.parser.ExpressionBindingException) Dimension(java.awt.Dimension) ScopedExpression(cbit.gui.ScopedExpression) VCellSortTableModel(cbit.vcell.client.desktop.biomodel.VCellSortTableModel) TableModel(javax.swing.table.TableModel)

Example 12 with ExpressionBindingException

use of cbit.vcell.parser.ExpressionBindingException in project vcell by virtualcell.

the class GeometryContext method refreshStructureMappings.

/**
 * This method was created by a SmartGuide.
 * @throws ExpressionBindingException
 */
public void refreshStructureMappings() throws MappingException, PropertyVetoException {
    // 
    // step through all structure mappings
    // 
    StructureMapping[] newStructureMappings = (StructureMapping[]) fieldStructureMappings.clone();
    // fill in geometryClass for those MembraneMappings that were not mapped explicitly (and topology is available)
    for (int j = 0; j < newStructureMappings.length; j++) {
        StructureMapping structureMapping = newStructureMappings[j];
        if (structureMapping instanceof MembraneMapping && structureMapping.getGeometryClass() == null) {
            MembraneMapping membraneMapping = (MembraneMapping) structureMapping;
            Feature insideFeature = getModel().getStructureTopology().getInsideFeature(membraneMapping.getMembrane());
            Feature outsideFeature = getModel().getStructureTopology().getOutsideFeature(membraneMapping.getMembrane());
            if (insideFeature != null && outsideFeature != null) {
                FeatureMapping insideFeatureMapping = (FeatureMapping) getStructureMapping(insideFeature);
                FeatureMapping outsideFeatureMapping = (FeatureMapping) getStructureMapping(outsideFeature);
                if (insideFeatureMapping.getGeometryClass() == outsideFeatureMapping.getGeometryClass()) {
                    membraneMapping.setGeometryClass(insideFeatureMapping.getGeometryClass());
                } else if (insideFeatureMapping.getGeometryClass() instanceof SubVolume && outsideFeatureMapping.getGeometryClass() instanceof SubVolume) {
                    SubVolume insideSubVolume = (SubVolume) insideFeatureMapping.getGeometryClass();
                    SubVolume outsideSubVolume = (SubVolume) outsideFeatureMapping.getGeometryClass();
                    SurfaceClass surfaceClass = getGeometry().getGeometrySurfaceDescription().getSurfaceClass(insideSubVolume, outsideSubVolume);
                    if (surfaceClass != null) {
                        membraneMapping.setGeometryClass(surfaceClass);
                    }
                }
            }
        }
    }
    for (int j = 0; j < newStructureMappings.length; j++) {
        StructureMapping structureMapping = newStructureMappings[j];
        Structure mappedStructure = structureMapping.getStructure();
        // SubVolume mappedSubvolume = structureMapping.getSubVolume();
        Structure newStructure = null;
        GeometryClass newGeometryClass = null;
        boolean structureFound = false;
        boolean geometryClassFound = false;
        // 
        // match up with structures defined within model
        // 
        Structure[] modelStructures = getModel().getStructures();
        for (int i = 0; i < modelStructures.length; i++) {
            Structure modelStructure = modelStructures[i];
            if (modelStructure.compareEqual(mappedStructure)) {
                structureFound = true;
                newStructure = modelStructure;
                break;
            }
        }
        // 
        // match up with geometryClasses defined within geometry
        // 
        GeometryClass[] geometryClasses = getGeometry().getGeometryClasses();
        for (int i = 0; i < geometryClasses.length; i++) {
            if (geometryClasses[i].compareEqual(structureMapping.getGeometryClass())) {
                geometryClassFound = true;
                newGeometryClass = geometryClasses[i];
                break;
            }
        }
        // 
        if (!(structureFound && geometryClassFound)) {
            newStructureMappings = (StructureMapping[]) BeanUtils.removeElement(newStructureMappings, structureMapping);
            j--;
        // //
        // // delete accompanied membrane mapping if exists
        // //
        // for (int i = 0; i < newStructureMappings.length; i++){
        // if (newStructureMappings[i] instanceof MembraneMapping){
        // MembraneMapping membraneMapping = (MembraneMapping)newStructureMappings[i];
        // if (membraneMapping.getMembrane()==null ||
        // membraneMapping.getMembrane().getInsideFeature() == structureMapping.getStructure() ||
        // membraneMapping.getMembrane().getOutsideFeature() == structureMapping.getStructure()){
        // newStructureMappings = (StructureMapping[])BeanUtils.removeElement(newStructureMappings,membraneMapping);
        // break;
        // }
        // }
        // }
        } else {
            // update references to Structure and SubVolume to correspond to those of Model and Geometry
            structureMapping.setGeometryClass(newGeometryClass);
        }
        if (structureFound) {
            structureMapping.setStructure(newStructure);
        }
    }
    // 
    // add default mappings for any new structures
    // 
    Structure[] structures = getModel().getStructures();
    for (int i = 0; i < structures.length; i++) {
        Structure structure = structures[i];
        StructureMapping sm = null;
        for (int j = 0; j < newStructureMappings.length; j++) {
            if (newStructureMappings[j].getStructure().compareEqual(structure)) {
                sm = newStructureMappings[j];
            }
        }
        if (sm == null) {
            if (structure instanceof Feature) {
                FeatureMapping fm = new FeatureMapping((Feature) structure, fieldSimulationContext, getModel().getUnitSystem());
                fm.setSimulationContext(this.fieldSimulationContext);
                newStructureMappings = (StructureMapping[]) BeanUtils.addElement(newStructureMappings, fm);
                if (getGeometry().getDimension() == 0) {
                    fm.setGeometryClass((CompartmentSubVolume) getGeometry().getGeometrySpec().getSubVolumes()[0]);
                }
            } else if (structure instanceof Membrane) {
                MembraneMapping mm = new MembraneMapping((Membrane) structure, fieldSimulationContext, getModel().getUnitSystem());
                mm.setSimulationContext(fieldSimulationContext);
                newStructureMappings = (StructureMapping[]) BeanUtils.addElement(newStructureMappings, mm);
                if (getGeometry().getDimension() == 0) {
                    mm.setGeometryClass((CompartmentSubVolume) getGeometry().getGeometrySpec().getSubVolumes()[0]);
                }
            } else {
                throw new MappingException("unsupported Structure Mapping for structure " + structure.getClass().toString());
            }
        }
    }
    if (newStructureMappings != fieldStructureMappings) {
        try {
            setStructureMappings(newStructureMappings);
        } catch (Exception e) {
            e.printStackTrace(System.out);
            throw new MappingException(e.getMessage());
        }
    }
    fixMembraneMappings();
}
Also used : GeometryClass(cbit.vcell.geometry.GeometryClass) SurfaceClass(cbit.vcell.geometry.SurfaceClass) Feature(cbit.vcell.model.Feature) PropertyVetoException(java.beans.PropertyVetoException) ExpressionException(cbit.vcell.parser.ExpressionException) ExpressionBindingException(cbit.vcell.parser.ExpressionBindingException) CompartmentSubVolume(cbit.vcell.geometry.CompartmentSubVolume) SubVolume(cbit.vcell.geometry.SubVolume) CompartmentSubVolume(cbit.vcell.geometry.CompartmentSubVolume) Membrane(cbit.vcell.model.Membrane) Structure(cbit.vcell.model.Structure)

Example 13 with ExpressionBindingException

use of cbit.vcell.parser.ExpressionBindingException in project vcell by virtualcell.

the class NetworkTransformer method transform.

private void transform(SimulationContext simContext, SimulationContext transformedSimulationContext, ArrayList<ModelEntityMapping> entityMappings, MathMappingCallback mathMappingCallback, NetworkGenerationRequirements networkGenerationRequirements) {
    String msg = "Generating network: flattening...";
    mathMappingCallback.setMessage(msg);
    TaskCallbackMessage tcm = new TaskCallbackMessage(TaskCallbackStatus.Clean, "");
    simContext.appendToConsole(tcm);
    tcm = new TaskCallbackMessage(TaskCallbackStatus.TaskStart, msg);
    simContext.appendToConsole(tcm);
    long startTime = System.currentTimeMillis();
    System.out.println("Convert to bngl, execute BNG, retrieve the results.");
    try {
        BNGOutputSpec outputSpec = generateNetwork(simContext, mathMappingCallback, networkGenerationRequirements);
        if (mathMappingCallback.isInterrupted()) {
            msg = "Canceled by user.";
            tcm = new TaskCallbackMessage(TaskCallbackStatus.Error, msg);
            simContext.appendToConsole(tcm);
            throw new UserCancelException(msg);
        }
        long endTime = System.currentTimeMillis();
        long elapsedTime = endTime - startTime;
        System.out.println("     " + elapsedTime + " milliseconds");
        Model model = transformedSimulationContext.getModel();
        ReactionContext reactionContext = transformedSimulationContext.getReactionContext();
        // ---- Parameters -----------------------------------------------------------------------------------------------
        startTime = System.currentTimeMillis();
        for (int i = 0; i < outputSpec.getBNGParams().length; i++) {
            BNGParameter p = outputSpec.getBNGParams()[i];
            // System.out.println(i+1 + ":\t\t"+ p.toString());
            if (model.getRbmModelContainer().getParameter(p.getName()) != null) {
                // if it's already there we don't try to add it again; this should be true for all of them!
                continue;
            }
            String s = p.getName();
            FakeSeedSpeciesInitialConditionsParameter fakeICParam = FakeSeedSpeciesInitialConditionsParameter.fromString(s);
            if (speciesEquivalenceMap.containsKey(fakeICParam)) {
                // we get rid of the fake parameters we use as keys
                continue;
            }
            FakeReactionRuleRateParameter fakeKineticParam = FakeReactionRuleRateParameter.fromString(s);
            if (fakeKineticParam != null) {
                System.out.println("found fakeKineticParam " + fakeKineticParam.fakeParameterName);
                // we get rid of the fake parameters we use as keys
                continue;
            }
            throw new RuntimeException("unexpected parameter " + p.getName() + " in internal BNG processing");
        // Expression exp = new Expression(p.getValue());
        // exp.bindExpression(model.getRbmModelContainer().getSymbolTable());
        // model.getRbmModelContainer().addParameter(p.getName(), exp, model.getUnitSystem().getInstance_TBD());
        }
        endTime = System.currentTimeMillis();
        elapsedTime = endTime - startTime;
        msg = "Adding " + outputSpec.getBNGParams().length + " parameters to model, " + elapsedTime + " ms";
        System.out.println(msg);
        // ---- Species ------------------------------------------------------------------------------------------------------------
        mathMappingCallback.setMessage("generating network: adding species...");
        mathMappingCallback.setProgressFraction(progressFractionQuota / 4.0f);
        startTime = System.currentTimeMillis();
        System.out.println("\nSpecies :");
        // the reactions will need this map to recover the names of species knowing only the networkFileIndex
        HashMap<Integer, String> speciesMap = new HashMap<Integer, String>();
        LinkedHashMap<String, Species> sMap = new LinkedHashMap<String, Species>();
        LinkedHashMap<String, SpeciesContext> scMap = new LinkedHashMap<String, SpeciesContext>();
        LinkedHashMap<String, BNGSpecies> crossMap = new LinkedHashMap<String, BNGSpecies>();
        List<SpeciesContext> noMapForThese = new ArrayList<SpeciesContext>();
        // final int decimalTickCount = Math.max(outputSpec.getBNGSpecies().length/10, 1);
        for (int i = 0; i < outputSpec.getBNGSpecies().length; i++) {
            BNGSpecies s = outputSpec.getBNGSpecies()[i];
            // System.out.println(i+1 + ":\t\t"+ s.toString());
            String key = s.getConcentration().infix();
            FakeSeedSpeciesInitialConditionsParameter fakeParam = FakeSeedSpeciesInitialConditionsParameter.fromString(key);
            if (fakeParam != null) {
                Pair<SpeciesContext, Expression> value = speciesEquivalenceMap.get(fakeParam);
                // the species context of the original model
                SpeciesContext originalsc = value.one;
                Expression initial = value.two;
                // replace the fake initial condition with the real one
                s.setConcentration(initial);
                // we'll have to find the species context from the cloned model which correspond to the original species
                SpeciesContext sc = model.getSpeciesContext(originalsc.getName());
                // System.out.println(sc.getName() + ", " + sc.getSpecies().getCommonName() + "   ...is one of the original seed species.");
                // existing name
                speciesMap.put(s.getNetworkFileIndex(), sc.getName());
                sMap.put(sc.getName(), sc.getSpecies());
                scMap.put(sc.getName(), sc);
                crossMap.put(sc.getName(), s);
                noMapForThese.add(sc);
                continue;
            }
            // all these species are new!
            // generate unique name for the species
            int count = 0;
            String speciesName = null;
            String nameRoot = "s";
            String speciesPatternNameString = s.extractName();
            while (true) {
                speciesName = nameRoot + count;
                if (Model.isNameUnused(speciesName, model) && !sMap.containsKey(speciesName) && !scMap.containsKey(speciesName)) {
                    break;
                }
                count++;
            }
            // newly created name
            speciesMap.put(s.getNetworkFileIndex(), speciesName);
            SpeciesContext speciesContext;
            if (s.hasCompartment()) {
                String speciesPatternCompartmentString = s.extractCompartment();
                speciesContext = new SpeciesContext(new Species(speciesName, s.getName()), model.getStructure(speciesPatternCompartmentString), null);
            } else {
                speciesContext = new SpeciesContext(new Species(speciesName, s.getName()), model.getStructure(0), null);
            }
            speciesContext.setName(speciesName);
            try {
                if (speciesPatternNameString != null) {
                    SpeciesPattern sp = RbmUtils.parseSpeciesPattern(speciesPatternNameString, model);
                    speciesContext.setSpeciesPattern(sp);
                }
            } catch (ParseException e) {
                e.printStackTrace();
                throw new RuntimeException("Bad format for species pattern string: " + e.getMessage());
            }
            // speciesContext.setSpeciesPatternString(speciesPatternString);
            // model.addSpecies(speciesContext.getSpecies());
            // model.addSpeciesContext(speciesContext);
            sMap.put(speciesName, speciesContext.getSpecies());
            scMap.put(speciesName, speciesContext);
            crossMap.put(speciesName, s);
            // }
            if (mathMappingCallback.isInterrupted()) {
                msg = "Canceled by user.";
                tcm = new TaskCallbackMessage(TaskCallbackStatus.Error, msg);
                simContext.appendToConsole(tcm);
                throw new UserCancelException(msg);
            }
        // if(i%50 == 0) {
        // System.out.println(i+"");
        // }
        // if(i%decimalTickCount == 0) {
        // int multiplier = i/decimalTickCount;
        // float progress = progressFractionQuota/4.0f + progressFractionQuotaSpecies*multiplier;
        // mathMappingCallback.setProgressFraction(progress);
        // }
        }
        for (SpeciesContext sc1 : model.getSpeciesContexts()) {
            boolean found = false;
            for (Map.Entry<String, SpeciesContext> entry : scMap.entrySet()) {
                SpeciesContext sc2 = entry.getValue();
                if (sc1.getName().equals(sc2.getName())) {
                    found = true;
                    // System.out.println("found species context " + sc1.getName() + " of species " + sc1.getSpecies().getCommonName() + " // " + sc2.getSpecies().getCommonName());
                    break;
                }
            }
            if (found == false) {
                // we add to the map the species context and the species which exist in the model but which are not in the map yet
                // the only ones in this situation should be plain species which were not given to bngl for flattening (they are flat already)
                // System.out.println("species context " + sc1.getName() + " not found in the map. Adding it.");
                scMap.put(sc1.getName(), sc1);
                sMap.put(sc1.getName(), sc1.getSpecies());
                noMapForThese.add(sc1);
            }
        }
        for (Species s1 : model.getSpecies()) {
            boolean found = false;
            for (Map.Entry<String, Species> entry : sMap.entrySet()) {
                Species s2 = entry.getValue();
                if (s1.getCommonName().equals(s2.getCommonName())) {
                    found = true;
                    // System.out.println("found species " + s1.getCommonName());
                    break;
                }
            }
            if (found == false) {
                System.err.println("species " + s1.getCommonName() + " not found in the map!");
            }
        }
        SpeciesContext[] sca = new SpeciesContext[scMap.size()];
        scMap.values().toArray(sca);
        Species[] sa = new HashSet<Species>(sMap.values()).toArray(new Species[0]);
        model.setSpecies(sa);
        model.setSpeciesContexts(sca);
        boolean isSpatial = transformedSimulationContext.getGeometry().getDimension() > 0;
        for (SpeciesContext sc : sca) {
            if (noMapForThese.contains(sc)) {
                continue;
            }
            SpeciesContextSpec scs = reactionContext.getSpeciesContextSpec(sc);
            Parameter param = scs.getParameter(SpeciesContextSpec.ROLE_InitialConcentration);
            BNGSpecies s = crossMap.get(sc.getName());
            param.setExpression(s.getConcentration());
            SpeciesContext origSpeciesContext = simContext.getModel().getSpeciesContext(s.getName());
            if (origSpeciesContext != null) {
                ModelEntityMapping em = new ModelEntityMapping(origSpeciesContext, sc);
                entityMappings.add(em);
            } else {
                ModelEntityMapping em = new ModelEntityMapping(new GeneratedSpeciesSymbolTableEntry(sc), sc);
                if (isSpatial) {
                    scs.initializeForSpatial();
                }
                entityMappings.add(em);
            }
        }
        // for(SpeciesContext sc : sca) {		// clean all the species patterns from the flattened species, we have no sp now
        // sc.setSpeciesPattern(null);
        // }
        endTime = System.currentTimeMillis();
        elapsedTime = endTime - startTime;
        msg = "Adding " + outputSpec.getBNGSpecies().length + " species to model, " + elapsedTime + " ms";
        System.out.println(msg);
        // ---- Reactions -----------------------------------------------------------------------------------------------------
        mathMappingCallback.setMessage("generating network: adding reactions...");
        mathMappingCallback.setProgressFraction(progressFractionQuota / 4.0f * 3.0f);
        startTime = System.currentTimeMillis();
        System.out.println("\nReactions :");
        Map<String, HashSet<String>> ruleKeyMap = new HashMap<String, HashSet<String>>();
        Map<String, BNGReaction> directBNGReactionsMap = new HashMap<String, BNGReaction>();
        Map<String, BNGReaction> reverseBNGReactionsMap = new HashMap<String, BNGReaction>();
        for (int i = 0; i < outputSpec.getBNGReactions().length; i++) {
            BNGReaction r = outputSpec.getBNGReactions()[i];
            if (!r.isRuleReversed()) {
                // direct
                directBNGReactionsMap.put(r.getKey(), r);
            } else {
                reverseBNGReactionsMap.put(r.getKey(), r);
            }
            // 
            // for each rule name, store set of keySets (number of unique keysets are number of generated reactions from this ruleName).
            // 
            HashSet<String> keySet = ruleKeyMap.get(r.getRuleName());
            if (keySet == null) {
                keySet = new HashSet<String>();
                ruleKeyMap.put(r.getRuleName(), keySet);
            }
            keySet.add(r.getKey());
        }
        Map<String, ReactionStep> reactionStepMap = new HashMap<String, ReactionStep>();
        for (int i = 0; i < outputSpec.getBNGReactions().length; i++) {
            BNGReaction bngReaction = outputSpec.getBNGReactions()[i];
            // System.out.println(i+1 + ":\t\t"+ r.writeReaction());
            String baseName = bngReaction.getRuleName();
            String reactionName = null;
            HashSet<String> keySetsForThisRule = ruleKeyMap.get(bngReaction.getRuleName());
            if (keySetsForThisRule.size() == 1 && model.getReactionStep(bngReaction.getRuleName()) == null && !reactionStepMap.containsKey(bngReaction.getRuleName())) {
                // we can reuse the reaction rule labels
                reactionName = bngReaction.getRuleName();
            } else {
                reactionName = bngReaction.getRuleName() + "_0";
                while (true) {
                    if (model.getReactionStep(reactionName) == null && !reactionStepMap.containsKey(reactionName)) {
                        // we can reuse the reaction rule labels
                        break;
                    }
                    reactionName = TokenMangler.getNextEnumeratedToken(reactionName);
                }
            }
            // 
            if (directBNGReactionsMap.containsValue(bngReaction)) {
                BNGReaction forwardBNGReaction = bngReaction;
                BNGReaction reverseBNGReaction = reverseBNGReactionsMap.get(bngReaction.getKey());
                String name = forwardBNGReaction.getRuleName();
                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));
                }
                ReactionRule rr = model.getRbmModelContainer().getReactionRule(name);
                Structure structure = rr.getStructure();
                boolean bReversible = reverseBNGReaction != null;
                SimpleReaction sr = new SimpleReaction(model, structure, reactionName, bReversible);
                for (int j = 0; j < forwardBNGReaction.getReactants().length; j++) {
                    BNGSpecies s = forwardBNGReaction.getReactants()[j];
                    String scName = speciesMap.get(s.getNetworkFileIndex());
                    SpeciesContext sc = model.getSpeciesContext(scName);
                    Reactant reactant = sr.getReactant(scName);
                    if (reactant == null) {
                        int stoichiometry = 1;
                        sr.addReactant(sc, stoichiometry);
                    } else {
                        int stoichiometry = reactant.getStoichiometry();
                        stoichiometry += 1;
                        reactant.setStoichiometry(stoichiometry);
                    }
                }
                for (int j = 0; j < forwardBNGReaction.getProducts().length; j++) {
                    BNGSpecies s = forwardBNGReaction.getProducts()[j];
                    String scName = speciesMap.get(s.getNetworkFileIndex());
                    SpeciesContext sc = model.getSpeciesContext(scName);
                    Product product = sr.getProduct(scName);
                    if (product == null) {
                        int stoichiometry = 1;
                        sr.addProduct(sc, stoichiometry);
                    } else {
                        int stoichiometry = product.getStoichiometry();
                        stoichiometry += 1;
                        product.setStoichiometry(stoichiometry);
                    }
                }
                MassActionKinetics targetKinetics = new MassActionKinetics(sr);
                sr.setKinetics(targetKinetics);
                KineticsParameter kforward = targetKinetics.getForwardRateParameter();
                KineticsParameter kreverse = targetKinetics.getReverseRateParameter();
                String kforwardNewName = rr.getKineticLaw().getLocalParameter(RbmKineticLawParameterType.MassActionForwardRate).getName();
                if (!kforward.getName().equals(kforwardNewName)) {
                    targetKinetics.renameParameter(kforward.getName(), kforwardNewName);
                    kforward = targetKinetics.getForwardRateParameter();
                }
                final String kreverseNewName = rr.getKineticLaw().getLocalParameter(RbmKineticLawParameterType.MassActionReverseRate).getName();
                if (!kreverse.getName().equals(kreverseNewName)) {
                    targetKinetics.renameParameter(kreverse.getName(), kreverseNewName);
                    kreverse = targetKinetics.getReverseRateParameter();
                }
                applyKineticsExpressions(forwardBNGReaction, kforward, targetKinetics);
                if (reverseBNGReaction != null) {
                    applyKineticsExpressions(reverseBNGReaction, kreverse, targetKinetics);
                }
                // String fieldParameterName = kforward.getName();
                // fieldParameterName += "_" + r.getRuleName();
                // kforward.setName(fieldParameterName);
                reactionStepMap.put(reactionName, sr);
            } else if (reverseBNGReactionsMap.containsValue(bngReaction) && !directBNGReactionsMap.containsKey(bngReaction.getKey())) {
                // reverse only (must be irreversible)
                BNGReaction reverseBNGReaction = reverseBNGReactionsMap.get(bngReaction.getKey());
                ReactionRule rr = model.getRbmModelContainer().getReactionRule(reverseBNGReaction.extractRuleName());
                Structure structure = rr.getStructure();
                boolean bReversible = false;
                SimpleReaction sr = new SimpleReaction(model, structure, reactionName, bReversible);
                for (int j = 0; j < reverseBNGReaction.getReactants().length; j++) {
                    BNGSpecies s = reverseBNGReaction.getReactants()[j];
                    String scName = speciesMap.get(s.getNetworkFileIndex());
                    SpeciesContext sc = model.getSpeciesContext(scName);
                    Reactant reactant = sr.getReactant(scName);
                    if (reactant == null) {
                        int stoichiometry = 1;
                        sr.addReactant(sc, stoichiometry);
                    } else {
                        int stoichiometry = reactant.getStoichiometry();
                        stoichiometry += 1;
                        reactant.setStoichiometry(stoichiometry);
                    }
                }
                for (int j = 0; j < reverseBNGReaction.getProducts().length; j++) {
                    BNGSpecies s = reverseBNGReaction.getProducts()[j];
                    String scName = speciesMap.get(s.getNetworkFileIndex());
                    SpeciesContext sc = model.getSpeciesContext(scName);
                    Product product = sr.getProduct(scName);
                    if (product == null) {
                        int stoichiometry = 1;
                        sr.addProduct(sc, stoichiometry);
                    } else {
                        int stoichiometry = product.getStoichiometry();
                        stoichiometry += 1;
                        product.setStoichiometry(stoichiometry);
                    }
                }
                MassActionKinetics k = new MassActionKinetics(sr);
                sr.setKinetics(k);
                KineticsParameter kforward = k.getForwardRateParameter();
                KineticsParameter kreverse = k.getReverseRateParameter();
                String kforwardNewName = rr.getKineticLaw().getLocalParameter(RbmKineticLawParameterType.MassActionForwardRate).getName();
                if (!kforward.getName().equals(kforwardNewName)) {
                    k.renameParameter(kforward.getName(), kforwardNewName);
                    kforward = k.getForwardRateParameter();
                }
                final String kreverseNewName = rr.getKineticLaw().getLocalParameter(RbmKineticLawParameterType.MassActionReverseRate).getName();
                if (!kreverse.getName().equals(kreverseNewName)) {
                    k.renameParameter(kreverse.getName(), kreverseNewName);
                    kreverse = k.getReverseRateParameter();
                }
                applyKineticsExpressions(reverseBNGReaction, kforward, k);
                // String fieldParameterName = kforward.getName();
                // fieldParameterName += "_" + r.getRuleName();
                // kforward.setName(fieldParameterName);
                reactionStepMap.put(reactionName, sr);
            }
        }
        for (ReactionStep rs : model.getReactionSteps()) {
            reactionStepMap.put(rs.getName(), rs);
        }
        ReactionStep[] reactionSteps = new ReactionStep[reactionStepMap.size()];
        reactionStepMap.values().toArray(reactionSteps);
        model.setReactionSteps(reactionSteps);
        if (mathMappingCallback.isInterrupted()) {
            msg = "Canceled by user.";
            tcm = new TaskCallbackMessage(TaskCallbackStatus.Error, msg);
            simContext.appendToConsole(tcm);
            throw new UserCancelException(msg);
        }
        endTime = System.currentTimeMillis();
        elapsedTime = endTime - startTime;
        msg = "Adding " + outputSpec.getBNGReactions().length + " reactions to model, " + elapsedTime + " ms";
        System.out.println(msg);
        // clean all the reaction rules
        model.getRbmModelContainer().getReactionRuleList().clear();
        // ---- Observables -------------------------------------------------------------------------------------------------
        mathMappingCallback.setMessage("generating network: adding observables...");
        mathMappingCallback.setProgressFraction(progressFractionQuota / 8.0f * 7.0f);
        startTime = System.currentTimeMillis();
        System.out.println("\nObservables :");
        RbmModelContainer rbmmc = model.getRbmModelContainer();
        for (int i = 0; i < outputSpec.getObservableGroups().length; i++) {
            ObservableGroup o = outputSpec.getObservableGroups()[i];
            if (rbmmc.getParameter(o.getObservableGroupName()) != null) {
                System.out.println("   ...already exists.");
                // if it's already there we don't try to add it again; this should be true for all of them!
                continue;
            }
            ArrayList<Expression> terms = new ArrayList<Expression>();
            for (int j = 0; j < o.getListofSpecies().length; j++) {
                Expression term = Expression.mult(new Expression(o.getSpeciesMultiplicity()[j]), new Expression(speciesMap.get(o.getListofSpecies()[j].getNetworkFileIndex())));
                terms.add(term);
            }
            Expression exp = Expression.add(terms.toArray(new Expression[terms.size()])).flatten();
            exp.bindExpression(rbmmc.getSymbolTable());
            RbmObservable originalObservable = rbmmc.getObservable(o.getObservableGroupName());
            VCUnitDefinition observableUnitDefinition = originalObservable.getUnitDefinition();
            rbmmc.removeObservable(originalObservable);
            Parameter newParameter = rbmmc.addParameter(o.getObservableGroupName(), exp, observableUnitDefinition);
            RbmObservable origObservable = simContext.getModel().getRbmModelContainer().getObservable(o.getObservableGroupName());
            ModelEntityMapping em = new ModelEntityMapping(origObservable, newParameter);
            entityMappings.add(em);
        }
        if (mathMappingCallback.isInterrupted()) {
            msg = "Canceled by user.";
            tcm = new TaskCallbackMessage(TaskCallbackStatus.Error, msg);
            simContext.appendToConsole(tcm);
            throw new UserCancelException(msg);
        }
        endTime = System.currentTimeMillis();
        elapsedTime = endTime - startTime;
        msg = "Adding " + outputSpec.getObservableGroups().length + " observables to model, " + elapsedTime + " ms";
        System.out.println(msg);
    } catch (PropertyVetoException ex) {
        ex.printStackTrace(System.out);
        throw new RuntimeException(ex.getMessage());
    } catch (ExpressionBindingException ex) {
        ex.printStackTrace(System.out);
        throw new RuntimeException(ex.getMessage());
    } catch (ModelException ex) {
        ex.printStackTrace(System.out);
        throw new RuntimeException(ex.getMessage());
    } catch (ExpressionException ex) {
        ex.printStackTrace(System.out);
        throw new RuntimeException(ex.getMessage());
    } catch (ClassNotFoundException ex) {
        throw new RuntimeException(ex.getMessage());
    } catch (IOException ex) {
        throw new RuntimeException(ex.getMessage());
    }
    System.out.println("Done transforming");
    msg = "Generating math...";
    System.out.println(msg);
    mathMappingCallback.setMessage(msg);
    mathMappingCallback.setProgressFraction(progressFractionQuota);
}
Also used : HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) UserCancelException(org.vcell.util.UserCancelException) ArrayList(java.util.ArrayList) Product(cbit.vcell.model.Product) SpeciesContext(cbit.vcell.model.SpeciesContext) FakeSeedSpeciesInitialConditionsParameter(org.vcell.model.rbm.FakeSeedSpeciesInitialConditionsParameter) Reactant(cbit.vcell.model.Reactant) BNGOutputSpec(cbit.vcell.bionetgen.BNGOutputSpec) ExpressionException(cbit.vcell.parser.ExpressionException) LinkedHashMap(java.util.LinkedHashMap) FakeReactionRuleRateParameter(org.vcell.model.rbm.FakeReactionRuleRateParameter) KineticsParameter(cbit.vcell.model.Kinetics.KineticsParameter) RbmModelContainer(cbit.vcell.model.Model.RbmModelContainer) Species(cbit.vcell.model.Species) BNGSpecies(cbit.vcell.bionetgen.BNGSpecies) HashSet(java.util.HashSet) BNGParameter(cbit.vcell.bionetgen.BNGParameter) ModelException(cbit.vcell.model.ModelException) ObservableGroup(cbit.vcell.bionetgen.ObservableGroup) RbmObservable(cbit.vcell.model.RbmObservable) PropertyVetoException(java.beans.PropertyVetoException) BNGReaction(cbit.vcell.bionetgen.BNGReaction) VCUnitDefinition(cbit.vcell.units.VCUnitDefinition) ReactionStep(cbit.vcell.model.ReactionStep) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) SpeciesPattern(org.vcell.model.rbm.SpeciesPattern) Structure(cbit.vcell.model.Structure) SimpleReaction(cbit.vcell.model.SimpleReaction) ReactionRule(cbit.vcell.model.ReactionRule) IOException(java.io.IOException) ExpressionBindingException(cbit.vcell.parser.ExpressionBindingException) Expression(cbit.vcell.parser.Expression) Model(cbit.vcell.model.Model) FakeSeedSpeciesInitialConditionsParameter(org.vcell.model.rbm.FakeSeedSpeciesInitialConditionsParameter) Parameter(cbit.vcell.model.Parameter) KineticsParameter(cbit.vcell.model.Kinetics.KineticsParameter) LocalParameter(cbit.vcell.mapping.ParameterContext.LocalParameter) BNGParameter(cbit.vcell.bionetgen.BNGParameter) FakeReactionRuleRateParameter(org.vcell.model.rbm.FakeReactionRuleRateParameter) MassActionKinetics(cbit.vcell.model.MassActionKinetics) ParseException(org.vcell.model.bngl.ParseException) BNGSpecies(cbit.vcell.bionetgen.BNGSpecies)

Example 14 with ExpressionBindingException

use of cbit.vcell.parser.ExpressionBindingException in project vcell by virtualcell.

the class ODESimData method readIn.

/**
 * JMW : This really should be synchronized...
 */
public void readIn(DataInputStream input) throws IOException {
    formatID = input.readUTF();
    if (formatID.equals(SIMPLE_ODE_DATA_FORMAT_ID)) {
        this.mathName = input.readUTF();
        // read data from old format file
        double saveInterval = input.readDouble();
        int savedNumber = input.readInt();
        int variableNumber = input.readInt();
        String[] variableNames = new String[variableNumber];
        double[][] dataValues = new double[savedNumber][variableNumber];
        for (int i = 0; i < variableNumber; i++) {
            int flag = input.readInt();
            variableNames[i] = input.readUTF();
            for (int j = 0; j < savedNumber; j++) {
                dataValues[j][i] = input.readDouble();
            }
        }
        // now put data in new data structure
        int rowCount = savedNumber;
        int columnCount = variableNumber + 1;
        addDataColumn(new ODESolverResultSetColumnDescription("t", "t"));
        for (int c = 1; c < columnCount; c++) {
            addDataColumn(new ODESolverResultSetColumnDescription(variableNames[c - 1], variableNames[c - 1]));
        }
        double[] values = new double[columnCount];
        for (int c = 0; c < columnCount; c++) values[c] = 0.0;
        for (int r = 0; r < rowCount; r++) {
            values[0] = r * saveInterval / 1000.0;
            addRow(values);
        }
        for (int c = 1; c < columnCount; c++) {
            for (int r = 0; r < rowCount; r++) {
                setValue(r, c, dataValues[r][c - 1]);
            }
        }
    } else if (formatID.equals(GENERIC_ODE_DATA_FORMAT_ID)) {
        this.mathName = input.readUTF();
        int rowCount = input.readInt();
        int columnCount = input.readInt();
        for (int c = 0; c < columnCount; c++) {
            String columnName = input.readUTF();
            String columnDisplayName = input.readUTF();
            addDataColumn(new ODESolverResultSetColumnDescription(columnName, columnDisplayName));
        }
        double[] values = new double[columnCount];
        for (int r = 0; r < rowCount; r++) {
            for (int c = 0; c < columnCount; c++) {
                values[c] = input.readDouble();
            }
            addRow(values);
        }
    } else if (formatID.equals(COMPACT_ODE_DATA_FORMAT_ID)) {
        this.mathName = input.readUTF();
        int rowCount = input.readInt();
        int columnCount = input.readInt();
        for (int c = 0; c < columnCount; c++) {
            String columnName = input.readUTF();
            String columnDisplayName = input.readUTF();
            String columnParameterName = input.readUTF();
            if (columnParameterName.equals("null")) {
                columnParameterName = null;
            }
            addDataColumn(new ODESolverResultSetColumnDescription(columnName, columnParameterName, columnDisplayName));
        }
        double[] values = new double[columnCount];
        for (int r = 0; r < rowCount; r++) {
            for (int c = 0; c < columnCount; c++) {
                values[c] = input.readDouble();
            }
            addRow(values);
        }
        try {
            int functionCount = input.readInt();
            for (int c = 0; c < functionCount; c++) {
                String columnName = input.readUTF();
                String columnDisplayName = input.readUTF();
                String columnParameterName = input.readUTF();
                if (columnParameterName.equals("null")) {
                    columnParameterName = null;
                }
                String expressionString = input.readUTF();
                try {
                    Expression expression = new Expression(expressionString);
                    addFunctionColumn(new FunctionColumnDescription(expression, columnName, columnParameterName, columnDisplayName, false));
                } catch (ExpressionBindingException e) {
                    e.printStackTrace(System.out);
                    System.out.println("ODESimData.readIn(): unable to bind expression '" + expressionString + "'");
                } catch (ExpressionException e) {
                    e.printStackTrace(System.out);
                    System.out.println("ODESimData.readIn(): unable to parse expression '" + expressionString + "'");
                }
            }
        } catch (EOFException e) {
        }
    } else {
        throw new IOException("DataInputStream is wrong format '" + formatID + "'");
    }
}
Also used : IOException(java.io.IOException) ExpressionBindingException(cbit.vcell.parser.ExpressionBindingException) ExpressionException(cbit.vcell.parser.ExpressionException) Expression(cbit.vcell.parser.Expression) EOFException(java.io.EOFException) ODESolverResultSetColumnDescription(cbit.vcell.math.ODESolverResultSetColumnDescription) FunctionColumnDescription(cbit.vcell.math.FunctionColumnDescription)

Example 15 with ExpressionBindingException

use of cbit.vcell.parser.ExpressionBindingException in project vcell by virtualcell.

the class MergedData method getFunctions.

/**
 * Insert the method's description here.
 * Creation date: (10/11/00 5:16:06 PM)
 * @return cbit.vcell.math.Function
 * @param name java.lang.String
 */
public AnnotatedFunction[] getFunctions(OutputContext outputContext) {
    try {
        getFunctionDataIdentifiers(outputContext);
    } catch (Exception ex) {
        ex.printStackTrace(System.out);
    }
    ArrayList<AnnotatedFunction> functionsArr = new ArrayList<>();
    // Get the functions in annotatedFunctionsList
    for (int i = 0; i < annotatedFunctionList.size(); i++) {
        // AnnotatedFunction annotatedFunc = (AnnotatedFunction)annotatedFunctionList.elementAt(i);
        // functions[i] = new Function(annotatedFunc.getName(), annotatedFunc.getExpression());
        functionsArr.add((AnnotatedFunction) annotatedFunctionList.elementAt(i));
    }
    for (int i = 0; i < datasetsIDList.length; i++) {
        VCDataIdentifier vcdid = datasetsIDList[i];
        try {
            AnnotatedFunction[] myFuncs = getDatasetControllerImpl().getFunctions(outputContext, vcdid);
            for (int j = 0; j < myFuncs.length; j++) {
                AnnotatedFunction myfunc = new AnnotatedFunction(dataSetPrefix[i] + "." + myFuncs[j].getName(), myFuncs[j].getExpression(), myFuncs[j].getDomain(), myFuncs[j].getErrorString(), myFuncs[j].getFunctionType(), myFuncs[j].getFunctionCatogery());
                functionsArr.add(myfunc);
            }
        } catch (ExpressionBindingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (DataAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    return functionsArr.toArray(new AnnotatedFunction[0]);
}
Also used : ArrayList(java.util.ArrayList) ExpressionBindingException(cbit.vcell.parser.ExpressionBindingException) VCDataIdentifier(org.vcell.util.document.VCDataIdentifier) XmlParseException(cbit.vcell.xml.XmlParseException) IOException(java.io.IOException) DataAccessException(org.vcell.util.DataAccessException) ExpressionException(cbit.vcell.parser.ExpressionException) ExpressionBindingException(cbit.vcell.parser.ExpressionBindingException) FileNotFoundException(java.io.FileNotFoundException) MathException(cbit.vcell.math.MathException) DataAccessException(org.vcell.util.DataAccessException) AnnotatedFunction(cbit.vcell.solver.AnnotatedFunction)

Aggregations

ExpressionBindingException (cbit.vcell.parser.ExpressionBindingException)37 Expression (cbit.vcell.parser.Expression)26 ExpressionException (cbit.vcell.parser.ExpressionException)16 PropertyVetoException (java.beans.PropertyVetoException)15 Vector (java.util.Vector)8 MathException (cbit.vcell.math.MathException)7 SymbolTableEntry (cbit.vcell.parser.SymbolTableEntry)7 VCUnitDefinition (cbit.vcell.units.VCUnitDefinition)7 ArrayList (java.util.ArrayList)7 VCUnitException (cbit.vcell.units.VCUnitException)6 LocalParameter (cbit.vcell.mapping.ParameterContext.LocalParameter)5 ModelParameter (cbit.vcell.model.Model.ModelParameter)5 SpeciesContext (cbit.vcell.model.SpeciesContext)5 Issue (org.vcell.util.Issue)5 ModelException (cbit.vcell.model.ModelException)4 ModelUnitSystem (cbit.vcell.model.ModelUnitSystem)4 Structure (cbit.vcell.model.Structure)4 Element (org.jdom.Element)4 ScopedExpression (cbit.gui.ScopedExpression)3 SubVolume (cbit.vcell.geometry.SubVolume)3