Search in sources :

Example 1 with CommentStringTokenizer

use of org.vcell.util.CommentStringTokenizer in project vcell by virtualcell.

the class BioCartoonTool method pasteReactionSteps0.

/**
 * pasteReactionSteps0 : does the actual pasting. First called with a cloned model, to track issues. If user still wants to proceed, the paste
 * is performed on the original model.
 *
 * Insert the method's description here.
 * Creation date: (5/10/2003 3:55:25 PM)
 * @param pasteToModel cbit.vcell.model.Model
 * @param pasteToStructure cbit.vcell.model.Structure
 * @param bNew boolean
 */
private static final PasteHelper pasteReactionSteps0(HashMap<String, HashMap<ReactionParticipant, Structure>> rxPartMapStructure, Component parent, IssueContext issueContext, ReactionStep[] copyFromRxSteps, Model pasteToModel, Structure pasteToStructure, boolean bNew, /*boolean bUseDBSpecies,*/
UserResolvedRxElements userResolvedRxElements) throws Exception {
    HashMap<BioModelEntityObject, BioModelEntityObject> reactionsAndSpeciesContexts = new HashMap<>();
    if (copyFromRxSteps == null || copyFromRxSteps.length == 0 || pasteToModel == null || pasteToStructure == null) {
        throw new IllegalArgumentException("CartoonTool.pasteReactionSteps Error " + (copyFromRxSteps == null || copyFromRxSteps.length == 0 ? "reactionStepsArr empty " : "") + (pasteToModel == null ? "model is null " : "") + (pasteToStructure == null ? "struct is null " : ""));
    }
    if (!pasteToModel.contains(pasteToStructure)) {
        throw new IllegalArgumentException("CartoonTool.pasteReactionSteps model " + pasteToModel.getName() + " does not contain structure " + pasteToStructure.getName());
    }
    // Check PasteToModel has preferred targets if set
    if (userResolvedRxElements != null) {
        for (int i = 0; i < userResolvedRxElements.toSpeciesArr.length; i++) {
            if (userResolvedRxElements.toSpeciesArr[i] != null) {
            // Structure toNewStruct = userResolvedRxElements.toStructureArr[i];
            // SpeciesContext[] toNewSC = pasteToModel.getSpeciesContexts(toNewStruct);
            // SpeciesContext[] usersSC = userResolvedRxElements.fromSpeciesContextArr;
            // boolean bFound = false;
            // for (int j = 0; j < toNewSC.length; j++) {
            // boolean structeql = toNewSC[j].getStructure().getName().equals(usersSC[i].getStructure().getName());
            // boolean specieseql = toNewSC[j].getSpecies().getCommonName().equals(usersSC[i].getSpecies().getCommonName());
            // System.out.println(toNewSC[j]+" "+structeql+" "+usersSC[i]+" "+specieseql);
            // if(structeql &&  specieseql) {
            // bFound = true;
            // break;
            // }
            // }
            // if(!bFound) {
            // throw new Exception("Expecting speciesContext '"+usersSC[i].getSpecies().getCommonName()+"' to exist already in structure "+toNewStruct.getName());
            // }
            // 
            // //					if(!pasteToModel.contains(userResolvedRxElements.toSpeciesArr[i])){
            // //						throw new RuntimeException("PasteToModel does not contain preferred Species "+userResolvedRxElements.toSpeciesArr[i]);
            // //					}
            }
            // }
            if (userResolvedRxElements.toStructureArr[i] != null) {
                if (!pasteToModel.contains(userResolvedRxElements.toStructureArr[i])) {
                    throw new RuntimeException("PasteToModel does not contain preferred Structure " + userResolvedRxElements.toStructureArr[i]);
                }
            }
        }
    }
    int counter = 0;
    Structure currentStruct = pasteToStructure;
    String copiedStructName = copyFromRxSteps[counter].getStructure().getName();
    StructureTopology structTopology = (copyFromRxSteps[counter].getModel() == null ? pasteToModel.getStructureTopology() : copyFromRxSteps[counter].getModel().getStructureTopology());
    IdentityHashMap<Species, Species> speciesHash = new IdentityHashMap<Species, Species>();
    IdentityHashMap<SpeciesContext, SpeciesContext> speciesContextHash = new IdentityHashMap<SpeciesContext, SpeciesContext>();
    Vector<Issue> issueVector = new Vector<Issue>();
    do {
        // create a new reaction, instead of cloning the old one; set struc
        ReactionStep copyFromReactionStep = copyFromRxSteps[counter];
        String newName = copyFromReactionStep.getName();
        while (pasteToModel.getReactionStep(newName) != null) {
            newName = org.vcell.util.TokenMangler.getNextEnumeratedToken(newName);
        }
        ReactionStep newReactionStep = null;
        if (copyFromReactionStep instanceof SimpleReaction) {
            newReactionStep = new SimpleReaction(pasteToModel, currentStruct, newName, copyFromReactionStep.isReversible());
        } else if (copyFromReactionStep instanceof FluxReaction && currentStruct instanceof Membrane) {
            newReactionStep = new FluxReaction(pasteToModel, (Membrane) currentStruct, null, newName, copyFromReactionStep.isReversible());
        }
        pasteToModel.addReactionStep(newReactionStep);
        reactionsAndSpeciesContexts.put(newReactionStep, copyFromReactionStep);
        Structure toRxnStruct = newReactionStep.getStructure();
        Structure fromRxnStruct = copyFromReactionStep.getStructure();
        if (!fromRxnStruct.getClass().equals(pasteToStructure.getClass())) {
            throw new Exception("Cannot copy reaction from " + fromRxnStruct.getTypeName() + " to " + pasteToStructure.getTypeName() + ".");
        }
        // add appropriate reactionParticipants to newReactionStep.
        StructureTopology toStructureTopology = pasteToModel.getStructureTopology();
        ReactionParticipant[] copyFromRxParticipantArr = copyFromReactionStep.getReactionParticipants();
        if (rxPartMapStructure == null) {
            // null during 'issues' trial
            rxPartMapStructure = new HashMap<String, HashMap<ReactionParticipant, Structure>>();
        }
        // }
        for (int i = 0; i < copyFromRxParticipantArr.length; i += 1) {
            Structure pasteToStruct = currentStruct;
            // if(toRxnStruct instanceof Membrane){
            pasteToStruct = rxPartMapStructure.get(copyFromReactionStep.getName()).get(copyFromRxParticipantArr[i]);
            // if(pasteToStruct == null){
            // for(ReactionParticipant myRXPart:rxPartMapStructure.get(copyFromReactionStep.getName()).keySet()){
            // if(myRXPart.getSpeciesContext().getName().equals(copyFromRxParticipantArr[i].getSpeciesContext().getName())){
            // pasteToStruct = rxPartMapStructure.get(copyFromReactionStep.getName()).get(myRXPart);
            // break;
            // }
            // }
            // }
            // }
            // this adds the speciesContexts and species (if any) to the model)
            SpeciesContext newSc = null;
            for (int j = 0; j < userResolvedRxElements.fromSpeciesContextArr.length; j++) {
                String forceName = userResolvedRxElements.finalNames.get(j).getText();
                if (userResolvedRxElements.fromSpeciesContextArr[j] == copyFromRxParticipantArr[i].getSpeciesContext()) {
                    if (userResolvedRxElements.toSpeciesArr[j] == null) {
                        newSc = pasteSpecies(parent, copyFromRxParticipantArr[i].getSpecies(), null, pasteToModel, pasteToStruct, bNew, /*bUseDBSpecies,*/
                        speciesHash, UserResolvedRxElements.getPreferredReactionElement(userResolvedRxElements, copyFromRxParticipantArr[i]));
                        changeName(userResolvedRxElements, newSc, j, pasteToModel, forceName);
                        reactionsAndSpeciesContexts.put(newSc, copyFromRxParticipantArr[i].getSpeciesContext());
                    } else {
                        if (forceName != null && forceName.length() > 0 && pasteToModel.getSpeciesContext(forceName) != null) {
                            if (pasteToModel.getSpeciesContext(forceName).getStructure().getName() == userResolvedRxElements.toStructureArr[j].getName()) {
                                throw new Exception("Paste custom name error:\nSpeciesContext name '" + forceName + "' in structure '" + userResolvedRxElements.toStructureArr[j].getName() + "' already used");
                            }
                        }
                        newSc = pasteToModel.getSpeciesContext(userResolvedRxElements.toSpeciesArr[j], userResolvedRxElements.toStructureArr[j]);
                        if (newSc == null) {
                            newSc = pasteSpecies(parent, copyFromRxParticipantArr[i].getSpecies(), null, pasteToModel, pasteToStruct, bNew, /*bUseDBSpecies,*/
                            speciesHash, UserResolvedRxElements.getPreferredReactionElement(userResolvedRxElements, copyFromRxParticipantArr[i]));
                            changeName(userResolvedRxElements, newSc, j, pasteToModel, forceName);
                        } else if (forceName != null && forceName.length() > 0) {
                            throw new Exception("Paste custom name error:\nCan't rename existing speciesContext '" + newSc.getName() + "' in structure '" + newSc.getStructure().getName() + "' to '" + forceName + "'");
                        }
                        reactionsAndSpeciesContexts.put(newSc, copyFromRxParticipantArr[i].getSpeciesContext());
                    // String rootSC = ReactionCartoonTool.speciesContextRootFinder(copyFromRxParticipantArr[i].getSpeciesContext());
                    // SpeciesContext[] matchSC = pasteToModel.getSpeciesContexts();
                    // for(int k=0;matchSC != null && k<matchSC.length;k++){
                    // String matchRoot = ReactionCartoonTool.speciesContextRootFinder(matchSC[k]);
                    // if(matchRoot != null && matchRoot.equals(rootSC) && matchSC[k].getStructure().getName().equals(pasteToStruct.getName())){
                    // newSc = matchSC[k];
                    // reactionsAndSpeciesContexts.put(newSc, matchSC[k]);
                    // break;
                    // }
                    // }
                    }
                    if (newSc == null) {
                        throw new Exception("Couldn't assign speciesContext='" + copyFromRxParticipantArr[i].getSpeciesContext().getName() + "' to species='" + userResolvedRxElements.toSpeciesArr[j].getCommonName() + "' in structure='" + userResolvedRxElements.toStructureArr[j].getName() + "', species/structure not exist");
                    }
                }
            }
            // String rootSC = ReactionCartoonTool.speciesContextRootFinder(copyFromRxParticipantArr[i].getSpeciesContext());
            // SpeciesContext newSc = null;
            // //				if(!bNew) {
            // SpeciesContext[] matchSC = pasteToModel.getSpeciesContexts();
            // for(int j=0;matchSC != null && j<matchSC.length;j++){
            // String matchRoot = ReactionCartoonTool.speciesContextRootFinder(matchSC[j]);
            // if(matchRoot != null && matchRoot.equals(rootSC) && matchSC[j].getStructure().getName().equals(pasteToStruct.getName())){
            // newSc = matchSC[j];
            // reactionsAndSpeciesContexts.put(newSc, matchSC[j]);
            // break;
            // }
            // }
            // //				}
            // 
            // if(newSc == null){
            // newSc = pasteSpecies(parent, copyFromRxParticipantArr[i].getSpecies(),rootSC,pasteToModel,pasteToStruct,bNew, /*bUseDBSpecies,*/speciesHash,
            // UserResolvedRxElements.getPreferredReactionElement(userResolvedRxElements,copyFromRxParticipantArr[i]));
            // reactionsAndSpeciesContexts.put(newSc,copyFromRxParticipantArr[i].getSpeciesContext());
            // }
            // record the old-new speciesContexts (reactionparticipants) in the IdHashMap, this is useful, esp for 'Paste new', while replacing proxyparams.
            SpeciesContext oldSc = copyFromRxParticipantArr[i].getSpeciesContext();
            if (speciesContextHash.get(oldSc) == null) {
                speciesContextHash.put(oldSc, newSc);
            }
            if (copyFromRxParticipantArr[i] instanceof Reactant) {
                newReactionStep.addReactionParticipant(new Reactant(null, newReactionStep, newSc, copyFromRxParticipantArr[i].getStoichiometry()));
            } else if (copyFromRxParticipantArr[i] instanceof Product) {
                newReactionStep.addReactionParticipant(new Product(null, newReactionStep, newSc, copyFromRxParticipantArr[i].getStoichiometry()));
            } else if (copyFromRxParticipantArr[i] instanceof Catalyst) {
                newReactionStep.addCatalyst(newSc);
            }
        }
        // // If 'newReactionStep' is a fluxRxn, set its fluxCarrier
        // if (newReactionStep instanceof FluxReaction) {
        // if (fluxCarrierSp != null) {
        // ((FluxReaction)newReactionStep).setFluxCarrier(fluxCarrierSp, pasteToModel);
        // } else {
        // throw new RuntimeException("Could not set FluxCarrier species for the flux reaction to be pasted");
        // }
        // }
        // For each kinetic parameter expression for new kinetics, replace the proxyParams from old kinetics with proxyParams in new kinetics
        // i.e., if the proxyParams are speciesContexts, replace with corresponding speciesContext in newReactionStep;
        // if the proxyParams are structureSizes or MembraneVoltages, replace with corresponding structure quantity in newReactionStep
        Kinetics oldKinetics = copyFromReactionStep.getKinetics();
        KineticsParameter[] oldKps = oldKinetics.getKineticsParameters();
        KineticsProxyParameter[] oldKprps = oldKinetics.getProxyParameters();
        Hashtable<String, Expression> paramExprHash = new Hashtable<String, Expression>();
        for (int i = 0; oldKps != null && i < oldKps.length; i++) {
            Expression newExpression = new Expression(oldKps[i].getExpression());
            for (int j = 0; oldKprps != null && j < oldKprps.length; j++) {
                // check if kinetic proxy parameter is in kinetic parameter expression
                if (newExpression.hasSymbol(oldKprps[j].getName())) {
                    SymbolTableEntry ste = oldKprps[j].getTarget();
                    Model pasteFromModel = copyFromReactionStep.getModel();
                    if (ste instanceof SpeciesContext) {
                        // if newRxnStruct is a feature/membrane, get matching spContexts from old reaction and replace them in new rate expr.
                        SpeciesContext oldSC = (SpeciesContext) ste;
                        SpeciesContext newSC = speciesContextHash.get(oldSC);
                        if (newSC == null) {
                            // check if oldSc is present in paste-model; if not, add it.
                            if (!pasteToModel.equals(pasteFromModel)) {
                                if (pasteToModel.getSpeciesContext(oldSC.getName()) == null) {
                                    // if paste-model has oldSc struct, paste it there,
                                    Structure newSCStruct = pasteToModel.getStructure(oldSC.getStructure().getName());
                                    if (newSCStruct != null) {
                                        newSC = pasteSpecies(parent, oldSC.getSpecies(), null, pasteToModel, newSCStruct, bNew, /*bUseDBSpecies,*/
                                        speciesHash, UserResolvedRxElements.getPreferredReactionElement(userResolvedRxElements, oldSC));
                                        speciesContextHash.put(oldSC, newSC);
                                    } else {
                                        // oldStruct wasn't found in paste-model, paste it in newRxnStruct and add warning to issues list
                                        newSC = pasteSpecies(parent, oldSC.getSpecies(), null, pasteToModel, toRxnStruct, bNew, /*bUseDBSpecies,*/
                                        speciesHash, UserResolvedRxElements.getPreferredReactionElement(userResolvedRxElements, oldSC));
                                        speciesContextHash.put(oldSC, newSC);
                                        Issue issue = new Issue(oldSC, issueContext, IssueCategory.CopyPaste, "SpeciesContext '" + oldSC.getSpecies().getCommonName() + "' was not found in compartment '" + oldSC.getStructure().getName() + "' in the model; the species was added to the compartment '" + toRxnStruct.getName() + "' where the reaction was pasted.", Issue.SEVERITY_WARNING);
                                        issueVector.add(issue);
                                    }
                                }
                            }
                        // if models are the same and newSc is null, then oldSc is not a rxnParticipant. Leave it as is in the expr.
                        }
                        if (newSC != null) {
                            reactionsAndSpeciesContexts.put(newSC, oldSC);
                            newExpression.substituteInPlace(new Expression(ste.getName()), new Expression(newSC.getName()));
                        }
                    // SpeciesContext sc = null;
                    // Species newSp = model.getSpecies(oldSc.getSpecies().getCommonName());
                    // if  (oldSc.getStructure() == (oldRxnStruct)) {
                    // sc = model.getSpeciesContext(newSp, newRxnStruct);
                    // } else {
                    // if (newRxnStruct instanceof Membrane) {
                    // // for a membrane, we need to make sure that inside-outside spContexts used are appropriately replaced.
                    // if (oldSc.getStructure() == ((Membrane)oldRxnStruct).getOutsideFeature()) {
                    // // old speciesContext is outside (old) membrane, new spContext should be outside new membrane
                    // sc = model.getSpeciesContext(newSp, ((Membrane)newRxnStruct).getOutsideFeature());
                    // } else if (oldSc.getStructure() == ((Membrane)oldRxnStruct).getInsideFeature()) {
                    // // old speciesContext is inside (old) membrane, new spContext should be inside new membrane
                    // sc = model.getSpeciesContext(newSp, ((Membrane)newRxnStruct).getInsideFeature());
                    // }
                    // }
                    // }
                    // if (sc != null) {
                    // newExpression.substituteInPlace(new Expression(ste.getName()), new Expression(sc.getName()));
                    // }
                    } else if (ste instanceof StructureSize) {
                        Structure str = ((StructureSize) ste).getStructure();
                        // if the structure size used is same as the structure in which the reaction is present, change the structSize to appropriate new struct
                        if (str.compareEqual(fromRxnStruct)) {
                            newExpression.substituteInPlace(new Expression(ste.getName()), new Expression(toRxnStruct.getStructureSize().getName()));
                        } else {
                            if (fromRxnStruct instanceof Membrane) {
                                if (str.equals(structTopology.getOutsideFeature((Membrane) fromRxnStruct))) {
                                    newExpression.substituteInPlace(new Expression(ste.getName()), new Expression(structTopology.getOutsideFeature((Membrane) toRxnStruct).getStructureSize().getName()));
                                } else if (str.equals(structTopology.getInsideFeature((Membrane) fromRxnStruct))) {
                                    newExpression.substituteInPlace(new Expression(ste.getName()), new Expression(structTopology.getInsideFeature((Membrane) toRxnStruct).getStructureSize().getName()));
                                }
                            }
                        }
                    } else if (ste instanceof MembraneVoltage) {
                        Membrane membr = ((MembraneVoltage) ste).getMembrane();
                        // if the MembraneVoltage used is same as that of the membrane in which the reaction is present, change the MemVoltage
                        if ((fromRxnStruct instanceof Membrane) && (membr.compareEqual(fromRxnStruct))) {
                            newExpression.substituteInPlace(new Expression(ste.getName()), new Expression(((Membrane) toRxnStruct).getMembraneVoltage().getName()));
                        }
                    } else if (ste instanceof ModelParameter) {
                        // see if model has this global parameter (if rxn is being pasted into another model, it won't)
                        if (!pasteToModel.equals(pasteFromModel)) {
                            ModelParameter oldMp = (ModelParameter) ste;
                            ModelParameter mp = pasteToModel.getModelParameter(oldMp.getName());
                            boolean bNonNumeric = false;
                            String newMpName = oldMp.getName();
                            if (mp != null) {
                                // new model has a model parameter with same name - are they the same param?
                                if (!mp.getExpression().equals(oldMp.getExpression())) {
                                    // no, they are not the same param, so mangle the 'ste' name and add as global in the other model
                                    while (pasteToModel.getModelParameter(newMpName) != null) {
                                        newMpName = TokenMangler.getNextEnumeratedToken(newMpName);
                                    }
                                    // if expression if numeric, add it as such. If not, set it to 0.0 and add it as global
                                    Expression exp = oldMp.getExpression();
                                    if (!exp.flatten().isNumeric()) {
                                        exp = new Expression(0.0);
                                        bNonNumeric = true;
                                    }
                                    ModelParameter newMp = pasteToModel.new ModelParameter(newMpName, exp, Model.ROLE_UserDefined, oldMp.getUnitDefinition());
                                    String annotation = "Copied from model : " + pasteFromModel.getNameScope();
                                    newMp.setModelParameterAnnotation(annotation);
                                    pasteToModel.addModelParameter(newMp);
                                    // if global param name had to be changed, make sure newExpr is updated as well.
                                    if (!newMpName.equals(oldMp.getName())) {
                                        newExpression.substituteInPlace(new Expression(oldMp.getName()), new Expression(newMpName));
                                    }
                                }
                            } else {
                                // no global param with same name was found in other model, so add it to other model.
                                // if expression if numeric, add it as such. If not, set it to 0.0 and add it as global
                                Expression exp = oldMp.getExpression();
                                if (!exp.flatten().isNumeric()) {
                                    exp = new Expression(0.0);
                                    bNonNumeric = true;
                                }
                                ModelParameter newMp = pasteToModel.new ModelParameter(newMpName, exp, Model.ROLE_UserDefined, oldMp.getUnitDefinition());
                                String annotation = "Copied from model : " + pasteFromModel.getNameScope();
                                newMp.setModelParameterAnnotation(annotation);
                                pasteToModel.addModelParameter(newMp);
                            }
                            // if a non-numeric parameter was encountered in the old model, it was added as a numeric (0.0), warn user of change.
                            if (bNonNumeric) {
                                Issue issue = new Issue(oldMp, issueContext, IssueCategory.CopyPaste, "Global parameter '" + oldMp.getName() + "' was non-numeric; it has been added " + "as global parameter '" + newMpName + "' in the new model with value = 0.0. " + "Please update its value, if required, before using it.", Issue.SEVERITY_WARNING);
                                issueVector.add(issue);
                            }
                        }
                    }
                }
            // end - if newExpr.hasSymbol(ProxyParam)
            }
            // now if store <param names, new expression> in hashTable
            if (paramExprHash.get(oldKps[i].getName()) == null) {
                paramExprHash.put(oldKps[i].getName(), newExpression);
            }
        }
        // end for - oldKps (old kinetic parameters)
        // use this new expression to generate 'vcml' for the (new) kinetics (easier way to transfer all kinetic parameters)
        String newKineticsStr = oldKinetics.writeTokensWithReplacingProxyParams(paramExprHash);
        // convert the kinetics 'vcml' to tokens.
        CommentStringTokenizer kineticsTokens = new CommentStringTokenizer(newKineticsStr);
        // skip the first token;
        kineticsTokens.nextToken();
        // second token is the kinetic type; use this to create a dummy kinetics
        String kineticType = kineticsTokens.nextToken();
        Kinetics newkinetics = KineticsDescription.fromVCMLKineticsName(kineticType).createKinetics(newReactionStep);
        // use the remaining tokens to construct the new kinetics
        newkinetics.fromTokens(newKineticsStr);
        // bind newkinetics to newReactionStep and add it to newReactionStep
        newkinetics.bind(newReactionStep);
        newReactionStep.setKinetics(newkinetics);
        counter += 1;
        if (counter == copyFromRxSteps.length) {
            break;
        }
        if (!copiedStructName.equals(fromRxnStruct.getName())) {
            if (currentStruct instanceof Feature) {
                currentStruct = structTopology.getMembrane((Feature) currentStruct);
            } else if (currentStruct instanceof Membrane) {
                currentStruct = structTopology.getInsideFeature((Membrane) currentStruct);
            }
        }
        copiedStructName = fromRxnStruct.getName();
    } while (true);
    return new PasteHelper(issueVector, rxPartMapStructure, reactionsAndSpeciesContexts);
}
Also used : Issue(org.vcell.util.Issue) IdentityHashMap(java.util.IdentityHashMap) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) IdentityHashMap(java.util.IdentityHashMap) Product(cbit.vcell.model.Product) FluxReaction(cbit.vcell.model.FluxReaction) SpeciesContext(cbit.vcell.model.SpeciesContext) Reactant(cbit.vcell.model.Reactant) Feature(cbit.vcell.model.Feature) SymbolTableEntry(cbit.vcell.parser.SymbolTableEntry) KineticsParameter(cbit.vcell.model.Kinetics.KineticsParameter) Membrane(cbit.vcell.model.Membrane) Structure(cbit.vcell.model.Structure) Species(cbit.vcell.model.Species) Vector(java.util.Vector) SimpleReaction(cbit.vcell.model.SimpleReaction) KineticsProxyParameter(cbit.vcell.model.Kinetics.KineticsProxyParameter) StructureTopology(cbit.vcell.model.Model.StructureTopology) Hashtable(java.util.Hashtable) BioModelEntityObject(cbit.vcell.model.BioModelEntityObject) StructureSize(cbit.vcell.model.Structure.StructureSize) PropertyVetoException(java.beans.PropertyVetoException) ExpressionBindingException(cbit.vcell.parser.ExpressionBindingException) ModelException(cbit.vcell.model.ModelException) UserCancelException(org.vcell.util.UserCancelException) ModelParameter(cbit.vcell.model.Model.ModelParameter) Expression(cbit.vcell.parser.Expression) MembraneVoltage(cbit.vcell.model.Membrane.MembraneVoltage) ReactionStep(cbit.vcell.model.ReactionStep) Model(cbit.vcell.model.Model) CommentStringTokenizer(org.vcell.util.CommentStringTokenizer) Kinetics(cbit.vcell.model.Kinetics) ReactionParticipant(cbit.vcell.model.ReactionParticipant) Catalyst(cbit.vcell.model.Catalyst)

Example 2 with CommentStringTokenizer

use of org.vcell.util.CommentStringTokenizer in project vcell by virtualcell.

the class DbDriver method getVCInfoContainer.

/**
 * Insert the method's description here.
 * Creation date: (9/24/2003 12:54:32 PM)
 * @return cbit.vcell.modeldb.VCInfoContainer
 */
public static VCInfoContainer getVCInfoContainer(User user, Connection con, DatabaseSyntax dbSyntax, int whichExtraInfo) throws SQLException, DataAccessException {
    VCInfoContainer results = null;
    // 
    VCImageInfo[] vcImageInfos = null;
    GeometryInfo[] geometryInfos = null;
    MathModelInfo[] mathModelInfos = null;
    BioModelInfo[] bioModelInfos = null;
    PublicationInfo[] publicationInfos = null;
    // 
    StringBuffer sql = null;
    String special = null;
    ResultSet rset = null;
    boolean enableSpecial = true;
    boolean enableDistinct = true;
    Statement stmt = con.createStatement();
    stmt.setFetchSize(500);
    try {
        String aliasSimName = "aliasSimName";
        String aliasSimID = "aliasSimID";
        String aliasSCName = "aliasSCName";
        String aliasSVName = "aliasSVName";
        // 
        // BioModelInfos
        // 
        {
            double beginTime = System.currentTimeMillis();
            special = " ORDER BY " + BioModelTable.table.name.getQualifiedColName() + "," + BioModelTable.table.versionBranchID.getQualifiedColName() + "," + BioModelTable.table.versionDate.getQualifiedColName();
            sql = new StringBuffer(BioModelTable.table.getInfoSQL(user, null, (enableSpecial ? special : null), dbSyntax));
            sql.insert(7, Table.SQL_GLOBAL_HINT);
            rset = stmt.executeQuery(sql.toString());
            TreeMap<BigDecimal, BioModelInfo> mapBmToBioModelInfo = new TreeMap<BigDecimal, BioModelInfo>();
            while (rset.next()) {
                BigDecimal bmID = rset.getBigDecimal(VersionTable.id_ColumnName);
                if (!mapBmToBioModelInfo.containsKey(bmID)) {
                    BioModelInfo versionInfo = (BioModelInfo) BioModelTable.table.getInfo(rset, con, dbSyntax);
                    mapBmToBioModelInfo.put(bmID, versionInfo);
                }
            }
            rset.close();
            if (whichExtraInfo != 0) {
                // Add mapping simName->SimID
                try {
                    // String aliasUserKey = "aliasUserKey";
                    sql = new StringBuffer("SELECT " + SimContextTable.table.id.getQualifiedColName() + "," + SimContextTable.table.name.getQualifiedColName() + " " + aliasSCName + "," + BioModelSimContextLinkTable.table.bioModelRef.getQualifiedColName() + "," + SimulationTable.table.name.getQualifiedColName() + " " + aliasSimName + "," + SimulationTable.table.id.getQualifiedColName() + " " + aliasSimID + (whichExtraInfo == 0xFF ? "," + ApplicationMathTable.table.outputFuncLarge.getQualifiedColName() + "," + ApplicationMathTable.table.outputFuncSmall.getQualifiedColName() + "," + SimulationTable.table.mathOverridesSmall + "," + SimulationTable.table.mathOverridesLarge + "," + SubVolumeTable.table.handle.getQualifiedColName() + "," + SubVolumeTable.table.name.getQualifiedColName() + " " + aliasSVName : // SubVolumeTable.table.ordinal.getQualifiedColName()+
                    "") + " FROM " + SimContextTable.table.getTableName() + "," + BioModelSimContextLinkTable.table.getTableName() + "," + BioModelSimulationLinkTable.table.getTableName() + "," + SimulationTable.table.getTableName() + (whichExtraInfo == 0xFF ? "," + ApplicationMathTable.table.getTableName() + "," + // GeometricRegionTable.table.getTableName()+","+
                    SubVolumeTable.table.getTableName() : "") + " WHERE " + BioModelSimContextLinkTable.table.simContextRef.getQualifiedColName() + " = " + SimContextTable.table.id.getQualifiedColName() + " AND " + SimulationTable.table.id.getQualifiedColName() + " = " + BioModelSimulationLinkTable.table.simRef.getQualifiedColName() + " AND " + BioModelSimulationLinkTable.table.bioModelRef.getQualifiedColName() + " = " + BioModelSimContextLinkTable.table.bioModelRef.getQualifiedColName() + " AND " + SimContextTable.table.mathRef.getQualifiedColName() + " = " + SimulationTable.table.mathRef.getQualifiedColName() + (whichExtraInfo == 0xFF ? " AND " + SimContextTable.table.id.getQualifiedColName() + " = " + ApplicationMathTable.table.simContextRef.getQualifiedColName() + " (+)" + // " AND "+SubVolumeTable.table.geometryRef.getQualifiedColName()+" = "+GeometricRegionTable.table.geometryRef.getQualifiedColName()
                    " AND " + SimContextTable.table.geometryRef.getQualifiedColName() + " = " + SubVolumeTable.table.geometryRef.getQualifiedColName() + " (+)" : ""));
                    final BigDecimal[] array = mapBmToBioModelInfo.keySet().toArray(new BigDecimal[0]);
                    final int MAX_LIST = 500;
                    for (int i = 0; i < array.length; i += MAX_LIST) {
                        StringBuffer bmListStr = new StringBuffer();
                        for (int j = 0; (i + j) < array.length && j < MAX_LIST; j++) {
                            bmListStr.append((j != 0 ? "," : "") + array[i + j].toString());
                        }
                        final String sql2 = sql.toString() + " AND " + BioModelSimulationLinkTable.table.bioModelRef.getQualifiedColName() + " IN (" + bmListStr.toString() + ")" + " ORDER BY " + BioModelSimulationLinkTable.table.bioModelRef.getQualifiedColName() + "," + SimContextTable.table.id.getQualifiedColName() + "," + SimulationTable.table.id.getQualifiedColName();
                        rset = stmt.executeQuery(sql2);
                        BioModelInfo bmInfo = null;
                        while (rset.next()) {
                            final BigDecimal bmID = rset.getBigDecimal(BioModelSimContextLinkTable.table.bioModelRef.toString());
                            bmInfo = mapBmToBioModelInfo.get(bmID);
                            if (bmInfo != null) {
                                final BigDecimal scID = rset.getBigDecimal(SimContextTable.table.id.toString());
                                final String scName = rset.getString(aliasSCName);
                                bmInfo.addSCID(scName, scID);
                                if ((whichExtraInfo & EXTRAINFO_ANNOTFUNC) != 0) {
                                    if (!bmInfo.hasSCIDForAnnotFunc(scID)) {
                                        String outputFunctionsXML = DbDriver.varchar2_CLOB_get(rset, ApplicationMathTable.table.outputFuncSmall, ApplicationMathTable.table.outputFuncLarge, dbSyntax);
                                        if (outputFunctionsXML != null) {
                                            bmInfo.addAnnotatedFunctionsStr(scName, scID, outputFunctionsXML);
                                        }
                                    }
                                }
                                final String simName = rset.getString(aliasSimName);
                                if (bmInfo.getSimID(simName) == null) {
                                    final BigDecimal simID = rset.getBigDecimal(aliasSimID);
                                    bmInfo.addSimID(simName, simID);
                                    if ((whichExtraInfo & EXTRAINFO_MATHOVERRIDES) != 0) {
                                        CommentStringTokenizer mathOverridesTokenizer = SimulationTable.getMathOverridesTokenizer(rset, dbSyntax);
                                        List<Element> mathOverrideElements = MathOverrides.parseOverrideElementsFromVCML(mathOverridesTokenizer);
                                        // int scanCount=1;
                                        // for(Element ele:mathOverrideElements) {
                                        // if(ele.getSpec() != null) {
                                        // scanCount*=ele.getSpec().getNumValues();
                                        // //										if(scanCount==0) {
                                        // //											scanCount=ele.getSpec().getNumValues();
                                        // //										}else {
                                        // //											scanCount*=ele.getSpec().getNumValues();
                                        // //										}
                                        // }
                                        // }
                                        // //							if(scanCount > 1) {
                                        // //								System.out.println("bmid="+bmID+" simid="+simID+" scans="+scanCount+" "+simName);
                                        // //							}
                                        bmInfo.addMathOverrides(simName, mathOverrideElements);
                                    }
                                }
                                if ((whichExtraInfo & EXTRAINFO_SUBVOLUMES) != 0) {
                                    final int subVolumeID = rset.getInt(SubVolumeTable.table.handle.toString());
                                    if (bmInfo.getSubVolumeName(subVolumeID) == null) {
                                        bmInfo.addSubVolume(subVolumeID, rset.getString(aliasSVName));
                                    }
                                }
                            }
                        }
                        rset.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                // ignore
                }
            }
            if (mapBmToBioModelInfo.size() > 0) {
                bioModelInfos = new BioModelInfo[mapBmToBioModelInfo.size()];
                mapBmToBioModelInfo.values().toArray(bioModelInfos);
            }
            // }
            if (lg.isInfoEnabled()) {
                lg.info("BioModelInfo Time=" + (((double) System.currentTimeMillis() - beginTime) / (double) 1000));
            }
        }
        // 
        // MathModelInfos
        // 
        {
            double beginTime = System.currentTimeMillis();
            special = " ORDER BY " + MathModelTable.table.name.getQualifiedColName() + "," + MathModelTable.table.versionBranchID.getQualifiedColName() + "," + MathModelTable.table.versionDate.getQualifiedColName();
            sql = new StringBuffer(MathModelTable.table.getInfoSQL(user, null, (enableSpecial ? special : null), dbSyntax));
            sql.insert(7, Table.SQL_GLOBAL_HINT);
            TreeMap<BigDecimal, MathModelInfo> mapMmToMathModelInfo = new TreeMap<BigDecimal, MathModelInfo>();
            rset = stmt.executeQuery(sql.toString());
            ArrayList<MathModelInfo> tempInfos = new ArrayList<MathModelInfo>();
            Set<String> distinctV = new HashSet<String>();
            while (rset.next()) {
                MathModelInfo versionInfo = (MathModelInfo) MathModelTable.table.getInfo(rset, con, dbSyntax);
                if (!distinctV.contains(versionInfo.getVersion().getVersionKey().toString())) {
                    tempInfos.add(versionInfo);
                    distinctV.add(versionInfo.getVersion().getVersionKey().toString());
                    mapMmToMathModelInfo.put(BigDecimal.valueOf(Long.parseLong(versionInfo.getVersion().getVersionKey().toString())), versionInfo);
                }
            }
            rset.close();
            if (whichExtraInfo != 0) {
                // Add mapping simName->SimID
                try {
                    // String aliasUserKey = "aliasUserKey";
                    sql = new StringBuffer("SELECT " + MathModelSimulationLinkTable.table.mathModelRef.getQualifiedColName() + "," + ApplicationMathTable.table.outputFuncLarge.getQualifiedColName() + "," + ApplicationMathTable.table.outputFuncSmall.getQualifiedColName() + "," + SimulationTable.table.name.getQualifiedColName() + " " + aliasSimName + "," + SimulationTable.table.id.getQualifiedColName() + " " + aliasSimID + "," + SimulationTable.table.mathOverridesSmall + "," + SimulationTable.table.mathOverridesLarge + "," + SubVolumeTable.table.handle.getQualifiedColName() + "," + SubVolumeTable.table.name.getQualifiedColName() + " " + aliasSVName + " FROM " + MathModelTable.table.getTableName() + "," + MathDescTable.table.getTableName() + "," + MathModelSimulationLinkTable.table.getTableName() + "," + ApplicationMathTable.table.getTableName() + "," + SimulationTable.table.getTableName() + "," + SubVolumeTable.table.getTableName() + " WHERE " + MathModelSimulationLinkTable.table.mathModelRef.getQualifiedColName() + " = " + ApplicationMathTable.table.mathModelRef.getQualifiedColName() + " (+)" + " AND " + MathModelTable.table.id.getQualifiedColName() + " = " + MathModelSimulationLinkTable.table.mathModelRef.getQualifiedColName() + " AND " + SimulationTable.table.id.getQualifiedColName() + " = " + MathModelSimulationLinkTable.table.simRef.getQualifiedColName() + " AND " + MathDescTable.table.id.getQualifiedColName() + " = " + MathModelTable.table.mathRef.getQualifiedColName() + " AND " + MathDescTable.table.geometryRef.getQualifiedColName() + " = " + SubVolumeTable.table.geometryRef.getQualifiedColName() + " (+)");
                    final BigDecimal[] array = mapMmToMathModelInfo.keySet().toArray(new BigDecimal[0]);
                    final int MAX_LIST = 500;
                    for (int i = 0; i < array.length; i += MAX_LIST) {
                        StringBuffer mmListStr = new StringBuffer();
                        for (int j = 0; (i + j) < array.length && j < MAX_LIST; j++) {
                            mmListStr.append((j != 0 ? "," : "") + array[i + j].toString());
                        }
                        final String sql2 = sql.toString() + " AND " + MathModelSimulationLinkTable.table.mathModelRef.getQualifiedColName() + " IN (" + mmListStr.toString() + ")" + " ORDER BY " + MathModelSimulationLinkTable.table.mathModelRef.getQualifiedColName() + "," + SimulationTable.table.id.getQualifiedColName();
                        rset = stmt.executeQuery(sql2);
                        MathModelInfo mmInfo = null;
                        while (rset.next()) {
                            final BigDecimal mmID = rset.getBigDecimal(MathModelSimulationLinkTable.table.mathModelRef.toString());
                            mmInfo = mapMmToMathModelInfo.get(mmID);
                            if (mmInfo != null) {
                                if (mmInfo.getAnnotatedFunctionsStr() == null) {
                                    String outputFunctionsXML = DbDriver.varchar2_CLOB_get(rset, ApplicationMathTable.table.outputFuncSmall, ApplicationMathTable.table.outputFuncLarge, dbSyntax);
                                    if (outputFunctionsXML != null) {
                                        mmInfo.setAnnotatedFunctionsStr(outputFunctionsXML);
                                    }
                                }
                                final String simName = rset.getString(aliasSimName);
                                if (mmInfo.getSimID(simName) == null) {
                                    final BigDecimal simID = rset.getBigDecimal(aliasSimID);
                                    CommentStringTokenizer mathOverridesTokenizer = SimulationTable.getMathOverridesTokenizer(rset, dbSyntax);
                                    List<Element> mathOverrideElements = MathOverrides.parseOverrideElementsFromVCML(mathOverridesTokenizer);
                                    // int scanCount=1;
                                    // for(Element ele:mathOverrideElements) {
                                    // if(ele.getSpec() != null) {
                                    // scanCount*=ele.getSpec().getNumValues();
                                    // }
                                    // }
                                    mmInfo.addSimID(simName, simID, mathOverrideElements);
                                }
                                final int subVolumeID = rset.getInt(SubVolumeTable.table.handle.toString());
                                if (mmInfo.getSubVolumeName(subVolumeID) == null) {
                                    mmInfo.addSubVolume(subVolumeID, rset.getString(aliasSVName));
                                }
                            }
                        }
                        rset.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                // ignore
                }
            }
            if (tempInfos.size() > 0) {
                mathModelInfos = new MathModelInfo[tempInfos.size()];
                tempInfos.toArray(mathModelInfos);
            }
            if (lg.isInfoEnabled()) {
                lg.info("MathModelInfo Time=" + (((double) System.currentTimeMillis() - beginTime) / (double) 1000));
            }
        }
        // 
        // VCImageInfos
        // 
        {
            double beginTime = System.currentTimeMillis();
            special = " ORDER BY " + ImageTable.table.name.getQualifiedColName() + "," + ImageTable.table.versionBranchID.getQualifiedColName() + "," + ImageTable.table.versionDate.getQualifiedColName();
            sql = new StringBuffer(ImageTable.table.getInfoSQL(user, null, (enableSpecial ? special : null), true, dbSyntax));
            sql.insert(7, Table.SQL_GLOBAL_HINT);
            rset = stmt.executeQuery(sql.toString());
            ArrayList<VCImageInfo> tempInfos = new ArrayList<VCImageInfo>();
            Set<String> distinctV = new HashSet<String>();
            while (rset.next()) {
                VCImageInfo versionInfo = (VCImageInfo) ImageTable.table.getInfo(rset, con, dbSyntax);
                if (!distinctV.contains(versionInfo.getVersion().getVersionKey().toString())) {
                    tempInfos.add(versionInfo);
                    distinctV.add(versionInfo.getVersion().getVersionKey().toString());
                }
            }
            rset.close();
            if (tempInfos.size() > 0) {
                vcImageInfos = new VCImageInfo[tempInfos.size()];
                tempInfos.toArray(vcImageInfos);
            }
            if (lg.isInfoEnabled()) {
                lg.info("ImageInfo Time=" + (((double) System.currentTimeMillis() - beginTime) / (double) 1000));
            }
        }
        // 
        // GeometeryInfos
        // 
        {
            double beginTime = System.currentTimeMillis();
            special = " ORDER BY " + GeometryTable.table.name.getQualifiedColName() + "," + GeometryTable.table.versionBranchID.getQualifiedColName() + "," + GeometryTable.table.versionDate.getQualifiedColName();
            sql = new StringBuffer(GeometryTable.table.getInfoSQL(user, null, (enableSpecial ? special : null), true, dbSyntax));
            sql.insert(7, Table.SQL_GLOBAL_HINT + (enableDistinct ? "DISTINCT " : ""));
            rset = stmt.executeQuery(sql.toString());
            ArrayList<GeometryInfo> tempInfos = new ArrayList<GeometryInfo>();
            Set<String> distinctV = new HashSet<String>();
            while (rset.next()) {
                GeometryInfo versionInfo = (GeometryInfo) GeometryTable.table.getInfo(rset, con);
                if (!distinctV.contains(versionInfo.getVersion().getVersionKey().toString())) {
                    tempInfos.add(versionInfo);
                    distinctV.add(versionInfo.getVersion().getVersionKey().toString());
                }
            }
            rset.close();
            if (tempInfos.size() > 0) {
                geometryInfos = new GeometryInfo[tempInfos.size()];
                tempInfos.toArray(geometryInfos);
            }
            if (lg.isInfoEnabled()) {
                lg.info("GeometryInfo Time=" + (((double) System.currentTimeMillis() - beginTime) / (double) 1000));
            }
        }
        try {
            Vector<VersionInfo> bm_mm_VCDocumentInfos = new Vector<>();
            bm_mm_VCDocumentInfos.addAll(Arrays.asList((bioModelInfos != null ? bioModelInfos : new BioModelInfo[0])));
            bm_mm_VCDocumentInfos.addAll(Arrays.asList((mathModelInfos != null ? mathModelInfos : new MathModelInfo[0])));
            DbDriver.addPublicationInfos(con, stmt, bm_mm_VCDocumentInfos);
        } catch (Exception e) {
            e.printStackTrace();
        // Don't fail if something goes wrong with setting publication info
        }
    } finally {
        if (stmt != null) {
            stmt.close();
        }
    }
    results = new VCInfoContainer(user, vcImageInfos, geometryInfos, mathModelInfos, bioModelInfos);
    return results;
}
Also used : ResultSet(java.sql.ResultSet) Set(java.util.Set) TreeSet(java.util.TreeSet) HashSet(java.util.HashSet) ArrayList(java.util.ArrayList) VCInfoContainer(org.vcell.util.document.VCInfoContainer) GeometryInfo(cbit.vcell.geometry.GeometryInfo) ResultSet(java.sql.ResultSet) ArrayList(java.util.ArrayList) List(java.util.List) Vector(java.util.Vector) VCImageInfo(cbit.image.VCImageInfo) PublicationInfo(org.vcell.util.document.PublicationInfo) PreparedStatement(java.sql.PreparedStatement) Statement(java.sql.Statement) BioModelInfo(org.vcell.util.document.BioModelInfo) MathModelInfo(org.vcell.util.document.MathModelInfo) TreeMap(java.util.TreeMap) BigDecimal(java.math.BigDecimal) DependencyException(org.vcell.util.DependencyException) RecordChangedException(cbit.sql.RecordChangedException) PermissionException(org.vcell.util.PermissionException) ObjectNotFoundException(org.vcell.util.ObjectNotFoundException) SQLException(java.sql.SQLException) DataAccessException(org.vcell.util.DataAccessException) VersionInfo(org.vcell.util.document.VersionInfo) CommentStringTokenizer(org.vcell.util.CommentStringTokenizer)

Example 3 with CommentStringTokenizer

use of org.vcell.util.CommentStringTokenizer in project vcell by virtualcell.

the class ParticleDataBlock method readParticleData.

private void readParticleData(List<String> lines) throws DataAccessException {
    String lastSpecies = null;
    List<Coordinate> working = null;
    for (String line : lines) {
        try {
            CommentStringTokenizer st = new CommentStringTokenizer(line);
            String sp = st.nextToken();
            if (!sp.equals(lastSpecies)) {
                lastSpecies = sp;
                working = fetch(sp);
            }
            double x = Double.parseDouble(st.nextToken());
            double y = Double.parseDouble(st.nextToken());
            double z = Double.parseDouble(st.nextToken());
            Coordinate c = new Coordinate(x, y, z);
            working.add(c);
        } catch (Exception exc) {
            throw new DataAccessException("Particle data file invalid. " + exc.getMessage());
        }
    }
}
Also used : Coordinate(org.vcell.util.Coordinate) CommentStringTokenizer(org.vcell.util.CommentStringTokenizer) IOException(java.io.IOException) DataAccessException(org.vcell.util.DataAccessException) DataAccessException(org.vcell.util.DataAccessException)

Example 4 with CommentStringTokenizer

use of org.vcell.util.CommentStringTokenizer in project vcell by virtualcell.

the class StlReader method readASCIIStl.

public static SurfaceCollection readASCIIStl(File file) throws IOException {
    String fileContents = XmlUtil.getXMLString(file.getAbsolutePath()).trim();
    // get rid of description text
    fileContents = fileContents.replaceFirst("^solid.*", "solid name");
    // get rid of description text
    fileContents = fileContents.replaceFirst("endsolid.*", "endsolid name");
    CommentStringTokenizer tokens = new CommentStringTokenizer(fileContents);
    String token = tokens.nextToken();
    if (!token.equalsIgnoreCase("solid")) {
        throw new RuntimeException("file not an ASCII STL file, didn't find 'solid'");
    }
    String name = tokens.nextToken();
    int inMask = 1;
    int outMask = 2;
    OrigSurface surface = new OrigSurface(inMask, outMask);
    surface.setExteriorMask(outMask);
    surface.setInteriorMask(inMask);
    SurfaceCollection surfaceCollection = new SurfaceCollection();
    surfaceCollection.addSurface(surface);
    HashMap<NodeKey, Node> nodeMap = new HashMap<NodeKey, Node>();
    while (tokens.hasMoreTokens()) {
        token = tokens.nextToken();
        if (token.equalsIgnoreCase("facet")) {
            token = tokens.nextToken();
            if (!token.equalsIgnoreCase("normal")) {
                throw new RuntimeException("unexpected token '" + token + "' while reading ASCII STL file at line " + tokens.lineIndex() + ", column " + tokens.columnIndex());
            }
            float nx = Float.parseFloat(tokens.nextToken());
            float ny = Float.parseFloat(tokens.nextToken());
            float nz = Float.parseFloat(tokens.nextToken());
            token = tokens.nextToken();
            if (!token.equalsIgnoreCase("outer")) {
                throw new RuntimeException("unexpected token '" + token + "' while reading ASCII STL file at line " + tokens.lineIndex() + ", column " + tokens.columnIndex());
            }
            token = tokens.nextToken();
            if (!token.equalsIgnoreCase("loop")) {
                throw new RuntimeException("unexpected token '" + token + "' while reading ASCII STL file at line " + tokens.lineIndex() + ", column " + tokens.columnIndex());
            }
            token = tokens.nextToken();
            if (!token.equalsIgnoreCase("vertex")) {
                throw new RuntimeException("unexpected token '" + token + "' while reading ASCII STL file at line " + tokens.lineIndex() + ", column " + tokens.columnIndex());
            }
            float v1x = Float.parseFloat(tokens.nextToken());
            float v1y = Float.parseFloat(tokens.nextToken());
            float v1z = Float.parseFloat(tokens.nextToken());
            token = tokens.nextToken();
            if (!token.equalsIgnoreCase("vertex")) {
                throw new RuntimeException("unexpected token '" + token + "' while reading ASCII STL file at line " + tokens.lineIndex() + ", column " + tokens.columnIndex());
            }
            float v2x = Float.parseFloat(tokens.nextToken());
            float v2y = Float.parseFloat(tokens.nextToken());
            float v2z = Float.parseFloat(tokens.nextToken());
            token = tokens.nextToken();
            if (!token.equalsIgnoreCase("vertex")) {
                throw new RuntimeException("unexpected token '" + token + "' while reading ASCII STL file at line " + tokens.lineIndex() + ", column " + tokens.columnIndex());
            }
            float v3x = Float.parseFloat(tokens.nextToken());
            float v3y = Float.parseFloat(tokens.nextToken());
            float v3z = Float.parseFloat(tokens.nextToken());
            token = tokens.nextToken();
            if (!token.equalsIgnoreCase("endloop")) {
                throw new RuntimeException("unexpected token '" + token + "' while reading ASCII STL file at line " + tokens.lineIndex() + ", column " + tokens.columnIndex());
            }
            token = tokens.nextToken();
            if (!token.equalsIgnoreCase("endfacet")) {
                throw new RuntimeException("unexpected token '" + token + "' while reading ASCII STL file at line " + tokens.lineIndex() + ", column " + tokens.columnIndex());
            }
            Node n1 = new Node(v1x, v1y, v1z);
            Node n2 = new Node(v2x, v2y, v2z);
            Node n3 = new Node(v3x, v3y, v3z);
            // 
            // merge nodes with identical coordinates.
            // 
            NodeKey key1 = new NodeKey(n1);
            NodeKey key2 = new NodeKey(n2);
            NodeKey key3 = new NodeKey(n3);
            Node node1 = nodeMap.get(key1);
            if (node1 == null) {
                node1 = n1;
                nodeMap.put(key1, n1);
            }
            Node node2 = nodeMap.get(key2);
            if (node2 == null) {
                node2 = n2;
                nodeMap.put(key2, n2);
            }
            Node node3 = nodeMap.get(key3);
            if (node3 == null) {
                node3 = n3;
                nodeMap.put(key3, n3);
            }
            Triangle triangle = new Triangle(node1, node2, node3);
            surface.addPolygon(triangle);
        } else if (token.equalsIgnoreCase("endsolid")) {
            String end_name = tokens.nextToken();
        // should match name
        } else {
            throw new RuntimeException("unexpected token '" + token + "' while reading ASCII STL file at line " + tokens.lineIndex() + ", column " + tokens.columnIndex());
        }
    }
    // 
    // set all nodes to surface collection (global list across all surfaces).
    // 
    surfaceCollection.setNodes(nodeMap.values().toArray(new Node[nodeMap.size()]));
    System.out.println("StlReader.readBinaryStl() - numTriangles = " + surface.getPolygonCount() + ", numNodes=" + surfaceCollection.getNodeCount() + ", numSurfaces=" + surfaceCollection.getSurfaceCount());
    return surfaceCollection;
}
Also used : HashMap(java.util.HashMap) CommentStringTokenizer(org.vcell.util.CommentStringTokenizer)

Example 5 with CommentStringTokenizer

use of org.vcell.util.CommentStringTokenizer in project vcell by virtualcell.

the class MathDescription method fromEditor.

/**
 * This method was created by a SmartGuide.
 * @param tokens java.util.StringTokenizer
 * @exception java.lang.Exception The exception description.
 */
public static MathDescription fromEditor(MathDescription oldMathDesc, String vcml) throws MathException, java.beans.PropertyVetoException {
    CommentStringTokenizer tokens = new CommentStringTokenizer(vcml);
    MathDescription mathDesc = new MathDescription(oldMathDesc.getVersion());
    mathDesc.clearAll();
    mathDesc.setGeometry0(oldMathDesc.getGeometry());
    mathDesc.read_database(tokens);
    // 
    if (!mathDesc.isValid()) {
        System.out.println("Math is invalid, warning = '" + mathDesc.getWarning() + "'");
    }
    return mathDesc;
}
Also used : CommentStringTokenizer(org.vcell.util.CommentStringTokenizer)

Aggregations

CommentStringTokenizer (org.vcell.util.CommentStringTokenizer)20 DataAccessException (org.vcell.util.DataAccessException)9 ArrayList (java.util.ArrayList)5 MathDescription (cbit.vcell.math.MathDescription)4 Expression (cbit.vcell.parser.Expression)4 BigDecimal (java.math.BigDecimal)4 Vector (java.util.Vector)4 MathException (cbit.vcell.math.MathException)3 IOException (java.io.IOException)3 Element (org.jdom.Element)3 ImageException (cbit.image.ImageException)2 AsynchClientTask (cbit.vcell.client.task.AsynchClientTask)2 SetMathDescription (cbit.vcell.client.task.SetMathDescription)2 CSGObject (cbit.vcell.geometry.CSGObject)2 GeometryException (cbit.vcell.geometry.GeometryException)2 MathFormatException (cbit.vcell.math.MathFormatException)2 MathModel (cbit.vcell.mathmodel.MathModel)2 MatrixException (cbit.vcell.matrix.MatrixException)2 ModelException (cbit.vcell.model.ModelException)2 SimpleReferenceData (cbit.vcell.opt.SimpleReferenceData)2