Search in sources :

Example 1 with ArchiveModelResolver

use of org.jlibsedml.execution.ArchiveModelResolver in project vcell by virtualcell.

the class XmlHelper method sedmlToBioModel.

public static VCDocument sedmlToBioModel(VCLogger transLogger, ExternalDocInfo externalDocInfo, SedML sedml, AbstractTask selectedTask) throws Exception {
    if (sedml.getModels().isEmpty()) {
        return null;
    }
    VCDocument doc = null;
    try {
        // extract the path only from the sedml file
        String fullPath = FileUtils.getFullPath(externalDocInfo.getFile().getAbsolutePath());
        // Namespace namespace = sedml.getNamespace();
        // iterate through all the elements and show them at the console
        List<org.jlibsedml.Model> mmm = sedml.getModels();
        for (Model mm : mmm) {
            System.out.println(mm.toString());
        }
        List<org.jlibsedml.Simulation> sss = sedml.getSimulations();
        for (org.jlibsedml.Simulation ss : sss) {
            System.out.println(ss.toString());
        }
        List<AbstractTask> ttt = sedml.getTasks();
        for (AbstractTask tt : ttt) {
            System.out.println(tt.toString());
        }
        List<DataGenerator> ddd = sedml.getDataGenerators();
        for (DataGenerator dd : ddd) {
            System.out.println(dd.toString());
        }
        List<Output> ooo = sedml.getOutputs();
        for (Output oo : ooo) {
            System.out.println(oo.toString());
        }
        KisaoTerm sedmlKisao = null;
        // this will become the vCell simulation
        org.jlibsedml.Simulation sedmlSimulation = null;
        // the "original" model referred to by the task
        org.jlibsedml.Model sedmlOriginalModel = null;
        String sedmlOriginalModelName = null;
        if (selectedTask == null) {
            // no task, just pick the Model and find its sbml file
            sedmlOriginalModelName = SEDMLUtil.getName(mmm.get(0));
        } else {
            if (selectedTask instanceof Task) {
                sedmlOriginalModel = sedml.getModelWithId(selectedTask.getModelReference());
                sedmlSimulation = sedml.getSimulation(selectedTask.getSimulationReference());
            } else if (selectedTask instanceof RepeatedTask) {
                RepeatedTask rt = (RepeatedTask) selectedTask;
                assert (rt.getSubTasks().size() == 1);
                // first (and only) subtask
                SubTask st = rt.getSubTasks().entrySet().iterator().next().getValue();
                String taskId = st.getTaskId();
                AbstractTask t = sedml.getTaskWithId(taskId);
                // get model and simulation from subtask
                sedmlOriginalModel = sedml.getModelWithId(t.getModelReference());
                sedmlSimulation = sedml.getSimulation(t.getSimulationReference());
            } else {
                throw new RuntimeException("Unexpected task " + selectedTask);
            }
            sedmlOriginalModelName = sedmlOriginalModel.getId();
            sedmlKisao = KisaoOntology.getInstance().getTermById(sedmlSimulation.getAlgorithm().getKisaoID());
        }
        // UniformTimeCourse [initialTime=0.0, numberOfPoints=1000, outputEndTime=1.0, outputStartTime=0.0,
        // Algorithm [kisaoID=KISAO:0000019], getId()=SimSlow]
        // identify the vCell solvers that would match best the sedml solver kisao id
        List<SolverDescription> solverDescriptions = new ArrayList<>();
        for (SolverDescription sd : SolverDescription.values()) {
            KisaoTerm solverKisaoTerm = KisaoOntology.getInstance().getTermById(sd.getKisao());
            if (solverKisaoTerm == null) {
                break;
            }
            boolean isExactlySame = solverKisaoTerm.equals(sedmlKisao);
            if (isExactlySame && !solverKisaoTerm.isObsolete()) {
                // we make a list with all the solvers that match the kisao
                solverDescriptions.add(sd);
            }
        }
        // from the list of vcell solvers that match the sedml kisao we select the ones that have a matching time step
        SolverDescription solverDescription = null;
        for (SolverDescription sd : solverDescriptions) {
            if (true) {
                solverDescription = sd;
                break;
            }
        }
        // find out everything else we need about the application we're going to use,
        // some of the info will be needed when we parse the sbml file
        boolean bSpatial = false;
        Application appType = Application.NETWORK_DETERMINISTIC;
        Set<SolverDescription.SolverFeature> sfList = solverDescription.getSupportedFeatures();
        for (SolverDescription.SolverFeature sf : sfList) {
            switch(sf) {
                case Feature_Rulebased:
                    appType = Application.RULE_BASED_STOCHASTIC;
                    break;
                case Feature_Stochastic:
                    appType = Application.NETWORK_STOCHASTIC;
                    break;
                case Feature_Deterministic:
                    appType = Application.NETWORK_DETERMINISTIC;
                    break;
                case Feature_Spatial:
                    bSpatial = true;
                    break;
                default:
                    break;
            }
        }
        // -------------------------------------------------------------------------------------------
        // extract bioModel name from sedx (or sedml) file
        String bioModelName = FileUtils.getBaseName(externalDocInfo.getFile().getAbsolutePath());
        // if we have repeated task, we ignore them, we just use the normal resolvers for archive and changes
        // once the application and simulation are built, we iterate through the repeated tasks and
        // add math overrides to the simulation for each repeated task
        ArchiveComponents ac = null;
        if (externalDocInfo.getFile().getPath().toLowerCase().endsWith("sedx") || externalDocInfo.getFile().getPath().toLowerCase().endsWith("omex")) {
            ac = Libsedml.readSEDMLArchive(new FileInputStream(externalDocInfo.getFile().getPath()));
        }
        ModelResolver resolver = new ModelResolver(sedml);
        if (ac != null) {
            resolver.add(new ArchiveModelResolver(ac));
        }
        resolver.add(new FileModelResolver());
        resolver.add(new RelativeFileModelResolver(fullPath));
        String newMdl = resolver.getModelString(sedmlOriginalModel);
        // sbmlSource with all the changes applied
        XMLSource sbmlSource = new XMLSource(newMdl);
        doc = XmlHelper.importSBML(transLogger, sbmlSource, bSpatial);
        BioModel bioModel = (BioModel) doc;
        bioModel.setName(bioModelName);
        // we already have an application loaded from the sbml file, with initial conditions and stuff
        // which may be not be suitable because the sedml kisao may need a different app type
        // so we do a "copy as" to the right type and then delete the original we loaded from the sbml file
        // the new application we're making from the old one
        SimulationContext newSimulationContext = null;
        if (bioModel.getSimulationContexts().length == 1) {
            SimulationContext oldSimulationContext = bioModel.getSimulationContext(0);
            newSimulationContext = SimulationContext.copySimulationContext(oldSimulationContext, sedmlOriginalModelName, bSpatial, appType);
            bioModel.removeSimulationContext(oldSimulationContext);
            bioModel.addSimulationContext(newSimulationContext);
        } else {
            // length == 0
            newSimulationContext = bioModel.addNewSimulationContext(sedmlOriginalModelName, appType);
        }
        // making the new vCell simulation based on the sedml simulation
        newSimulationContext.refreshDependencies();
        MathMappingCallback callback = new MathMappingCallbackTaskAdapter(null);
        newSimulationContext.refreshMathDescription(callback, NetworkGenerationRequirements.ComputeFullStandardTimeout);
        Simulation newSimulation = new Simulation(newSimulationContext.getMathDescription());
        newSimulation.setName(SEDMLUtil.getName(sedmlSimulation));
        // TODO: make sure that everything has proper names
        // we check the repeated tasks, if any, and add to the list of math overrides
        // if(selectedTask instanceof RepeatedTask) {
        // for(Change change : ((RepeatedTask) selectedTask).getChanges()) {
        // if(!(change instanceof SetValue)) {
        // throw new RuntimeException("Only 'SetValue' changes are supported for repeated tasks.");
        // }
        // SetValue setValue = (SetValue)change;
        // // TODO: extract target from XPath
        // // ......
        // //
        // String target = "s0";	// for now we just use a hardcoded thing
        // ConstantArraySpec cas;
        // Range range = ((RepeatedTask) selectedTask).getRange(setValue.getRangeReference());
        // if(range instanceof UniformRange) {
        // cas = ConstantArraySpec.createIntervalSpec(target, ((UniformRange) range).getStart(), ((UniformRange) range).getEnd(),
        // range.getNumElements(), ((UniformRange) range).getType() == UniformRange.UniformType.LOG ? true : false);
        // } else if(range instanceof VectorRange) {
        // //    				List<String> constants = new ArrayList<> ();
        // //    				for(int i=0; i<range.getNumElements(); i++) {
        // //    					constants.add(new Constant(i+"", new Expression(range.getElementAt(i))));
        // //    				}
        // //    				cas = ConstantArraySpec.createListSpec(target, constants);
        // 
        // } else {
        // throw new RuntimeException("Only 'Uniform Range' and 'Vector Range' are supported at this time.");
        // }
        // 
        // }
        // }
        // we identify the type of sedml simulation (uniform time course, etc)
        // and set the vCell simulation parameters accordingly
        SolverTaskDescription simTaskDesc = newSimulation.getSolverTaskDescription();
        TimeBounds timeBounds = new TimeBounds();
        TimeStep timeStep = new TimeStep();
        double outputTimeStep = 0.1;
        if (sedmlSimulation instanceof UniformTimeCourse) {
            // we translate initial time to zero, we provide output for the duration of the simulation
            // because we can't select just an interval the way the SEDML simulation can
            double initialTime = ((UniformTimeCourse) sedmlSimulation).getInitialTime();
            double outputStartTime = ((UniformTimeCourse) sedmlSimulation).getOutputStartTime();
            double outputEndTime = ((UniformTimeCourse) sedmlSimulation).getOutputEndTime();
            double outputNumberOfPoints = ((UniformTimeCourse) sedmlSimulation).getNumberOfPoints();
            outputTimeStep = (outputEndTime - outputStartTime) / outputNumberOfPoints;
            timeBounds = new TimeBounds(0, outputEndTime - initialTime);
        } else if (sedmlSimulation instanceof OneStep) {
        // for anything other than UniformTimeCourse we just ignore
        } else if (sedmlSimulation instanceof SteadyState) {
        } else {
        }
        OutputTimeSpec outputTimeSpec = new UniformOutputTimeSpec(outputTimeStep);
        simTaskDesc.setTimeBounds(timeBounds);
        simTaskDesc.setTimeStep(timeStep);
        simTaskDesc.setOutputTimeSpec(outputTimeSpec);
        newSimulation.setSolverTaskDescription(simTaskDesc);
        bioModel.addSimulation(newSimulation);
        newSimulation.refreshDependencies();
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("Unable to initialize bioModel for the given selection.");
    }
    return doc;
}
Also used : Task(org.jlibsedml.Task) RepeatedTask(org.jlibsedml.RepeatedTask) SimulationTask(cbit.vcell.messaging.server.SimulationTask) AbstractTask(org.jlibsedml.AbstractTask) SubTask(org.jlibsedml.SubTask) ArrayList(java.util.ArrayList) ArchiveModelResolver(org.jlibsedml.execution.ArchiveModelResolver) FileModelResolver(org.jlibsedml.execution.FileModelResolver) RelativeFileModelResolver(org.vcell.sedml.RelativeFileModelResolver) ModelResolver(org.jlibsedml.execution.ModelResolver) SteadyState(org.jlibsedml.SteadyState) OutputTimeSpec(cbit.vcell.solver.OutputTimeSpec) UniformOutputTimeSpec(cbit.vcell.solver.UniformOutputTimeSpec) SolverTaskDescription(cbit.vcell.solver.SolverTaskDescription) SubTask(org.jlibsedml.SubTask) VCDocument(org.vcell.util.document.VCDocument) MathMappingCallback(cbit.vcell.mapping.SimulationContext.MathMappingCallback) UniformOutputTimeSpec(cbit.vcell.solver.UniformOutputTimeSpec) FileInputStream(java.io.FileInputStream) KisaoTerm(org.jlibsedml.modelsupport.KisaoTerm) ArchiveModelResolver(org.jlibsedml.execution.ArchiveModelResolver) DataGenerator(org.jlibsedml.DataGenerator) UniformTimeCourse(org.jlibsedml.UniformTimeCourse) Application(cbit.vcell.mapping.SimulationContext.Application) AbstractTask(org.jlibsedml.AbstractTask) SolverDescription(cbit.vcell.solver.SolverDescription) RelativeFileModelResolver(org.vcell.sedml.RelativeFileModelResolver) OneStep(org.jlibsedml.OneStep) TimeBounds(cbit.vcell.solver.TimeBounds) TimeStep(cbit.vcell.solver.TimeStep) ArchiveComponents(org.jlibsedml.ArchiveComponents) RepeatedTask(org.jlibsedml.RepeatedTask) Output(org.jlibsedml.Output) MathMappingCallbackTaskAdapter(cbit.vcell.mapping.MathMappingCallbackTaskAdapter) FileModelResolver(org.jlibsedml.execution.FileModelResolver) RelativeFileModelResolver(org.vcell.sedml.RelativeFileModelResolver) SimulationContext(cbit.vcell.mapping.SimulationContext) XMLStreamException(javax.xml.stream.XMLStreamException) SbmlException(org.vcell.sbml.SbmlException) SBMLException(org.sbml.jsbml.SBMLException) IOException(java.io.IOException) ExpressionException(cbit.vcell.parser.ExpressionException) Simulation(cbit.vcell.solver.Simulation) Model(org.jlibsedml.Model) BioModel(cbit.vcell.biomodel.BioModel) MathModel(cbit.vcell.mathmodel.MathModel) BioModel(cbit.vcell.biomodel.BioModel) Model(org.jlibsedml.Model)

Example 2 with ArchiveModelResolver

use of org.jlibsedml.execution.ArchiveModelResolver in project vcell by virtualcell.

the class StandaloneSEDMLTest method doit.

public static void doit(File archiveFile) throws Exception {
    ArchiveComponents ac = null;
    ac = Libsedml.readSEDMLArchive(new FileInputStream(archiveFile));
    SEDMLDocument sedmlDoc = ac.getSedmlDocuments().get(0);
    SedML sedml = sedmlDoc.getSedMLModel();
    if (sedml == null || sedml.getModels().isEmpty()) {
        throw new RuntimeException("sedml null or empty");
    }
    ModelResolver resolver = new ModelResolver(sedml);
    // resolver.add(new FileModelResolver());
    resolver.add(new ArchiveModelResolver(ac));
    resolver.add(new BioModelsModelsRetriever());
    resolver.add(new URLResourceRetriever());
    // resolver.add(new RelativeFileModelResolver(FileUtils.getFullPath(archiveFile.getAbsolutePath())));
    // 
    // iterate through all the elements and show them at the console
    // 
    List<org.jlibsedml.Model> mmm = sedml.getModels();
    for (Model mm : mmm) {
        System.out.println(mm.toString());
    }
    List<org.jlibsedml.Simulation> sss = sedml.getSimulations();
    for (org.jlibsedml.Simulation ss : sss) {
        System.out.println(ss.toString());
    }
    List<AbstractTask> ttt = sedml.getTasks();
    for (AbstractTask tt : ttt) {
        System.out.println(tt.toString());
    }
    List<DataGenerator> ddd = sedml.getDataGenerators();
    for (DataGenerator dd : ddd) {
        System.out.println(dd.toString());
    }
    List<Output> ooo = sedml.getOutputs();
    for (Output oo : ooo) {
        System.out.println(oo.toString());
    }
    // 
    // extract models referenced in tasks.
    // 
    KisaoOntology kisaoInstance = KisaoOntology.getInstance();
    // HashMap<String,Model> flattenedModels = new HashMap<String, Model>();
    List<AbstractTask> taskList = sedml.getTasks();
    for (AbstractTask task : taskList) {
        String modelReference = task.getModelReference();
        org.jlibsedml.Model sedmlOriginalModel = sedml.getModelWithId(modelReference);
        String sbmlModelString = resolver.getModelString(sedmlOriginalModel);
        // sbmlSource with all the changes applied
        XMLSource sbmlSource = new XMLSource(sbmlModelString);
        org.jlibsedml.Simulation sedmlSimulation = sedml.getSimulation(task.getSimulationReference());
        Algorithm algorithm = sedmlSimulation.getAlgorithm();
        KisaoTerm sedmlKisao = kisaoInstance.getTermById(algorithm.getKisaoID());
        // 
        // try to find a VCell solverDescription to match the Kisao term
        // 
        // UniformTimeCourse [initialTime=0.0, numberOfPoints=1000, outputEndTime=1.0, outputStartTime=0.0,
        // Algorithm [kisaoID=KISAO:0000019], getId()=SimSlow]
        // identify the vCell solvers that would match best the sedml solver kisao id
        List<SolverDescription> solverDescriptions = new ArrayList<>();
        for (SolverDescription sd : SolverDescription.values()) {
            KisaoTerm solverKisaoTerm = kisaoInstance.getTermById(sd.getKisao());
            if (solverKisaoTerm == null) {
                break;
            }
            boolean isExactlySame = solverKisaoTerm.equals(sedmlKisao);
            if (isExactlySame && !solverKisaoTerm.isObsolete()) {
                // we make a list with all the solvers that match the kisao
                solverDescriptions.add(sd);
            }
        }
        if (solverDescriptions.isEmpty()) {
            throw new RuntimeException("cannot find the solverDescription with exact match for Kisao term '" + sedmlKisao + "'");
        }
        // choose first one
        SolverDescription solverDescription = solverDescriptions.get(0);
        // find out everything else we need about the application we're going to use,
        // some of the info will be needed when we parse the sbml file
        boolean bSpatial = false;
        Application appType = Application.NETWORK_DETERMINISTIC;
        Set<SolverDescription.SolverFeature> sfList = solverDescription.getSupportedFeatures();
        for (SolverDescription.SolverFeature sf : sfList) {
            switch(sf) {
                case Feature_Rulebased:
                    appType = Application.RULE_BASED_STOCHASTIC;
                    break;
                case Feature_Stochastic:
                    appType = Application.NETWORK_STOCHASTIC;
                    break;
                case Feature_Deterministic:
                    appType = Application.NETWORK_DETERMINISTIC;
                    break;
                case Feature_Spatial:
                    bSpatial = true;
                    break;
                default:
                    break;
            }
        }
        BioModel bioModel = (BioModel) XmlHelper.importSBML(transLogger, sbmlSource, bSpatial);
        // 
        // we already have an application loaded from the sbml file, with initial conditions and stuff
        // which may be not be suitable because the sedml kisao may need a different app type
        // so we do a "copy as" to the right type and then delete the original we loaded from the sbml file
        // 
        // the new application we're making from the old one
        SimulationContext newSimulationContext = null;
        if (bioModel.getSimulationContexts().length == 1) {
            SimulationContext oldSimulationContext = bioModel.getSimulationContext(0);
            String newSCName = bioModel.getFreeSimulationContextName();
            newSimulationContext = SimulationContext.copySimulationContext(oldSimulationContext, newSCName, bSpatial, appType);
            bioModel.addSimulationContext(newSimulationContext);
            bioModel.removeSimulationContext(oldSimulationContext);
        } else {
            newSimulationContext = bioModel.addNewSimulationContext("App1", appType);
        }
        // 
        // making the new vCell simulation based on the sedml simulation
        // 
        newSimulationContext.refreshDependencies();
        MathMappingCallback callback = new MathMappingCallbackTaskAdapter(progressListener);
        newSimulationContext.refreshMathDescription(callback, NetworkGenerationRequirements.ComputeFullStandardTimeout);
        Simulation newSimulation = new Simulation(newSimulationContext.getMathDescription());
        newSimulation.setName(sedmlSimulation.getName());
        bioModel.addSimulation(newSimulation);
        // and set the vCell simulation parameters accordingly
        if (sedmlSimulation instanceof UniformTimeCourse) {
        } else if (sedmlSimulation instanceof OneStep) {
        } else if (sedmlSimulation instanceof SteadyState) {
        } else {
        }
        System.out.println(XmlHelper.bioModelToXML(bioModel));
    }
}
Also used : AbstractTask(org.jlibsedml.AbstractTask) SolverDescription(cbit.vcell.solver.SolverDescription) ArrayList(java.util.ArrayList) OneStep(org.jlibsedml.OneStep) ModelResolver(org.jlibsedml.execution.ModelResolver) ArchiveModelResolver(org.jlibsedml.execution.ArchiveModelResolver) SteadyState(org.jlibsedml.SteadyState) SedML(org.jlibsedml.SedML) ArchiveComponents(org.jlibsedml.ArchiveComponents) Output(org.jlibsedml.Output) MathMappingCallbackTaskAdapter(cbit.vcell.mapping.MathMappingCallbackTaskAdapter) MathMappingCallback(cbit.vcell.mapping.SimulationContext.MathMappingCallback) BioModelsModelsRetriever(org.jlibsedml.modelsupport.BioModelsModelsRetriever) SimulationContext(cbit.vcell.mapping.SimulationContext) Algorithm(org.jlibsedml.Algorithm) FileInputStream(java.io.FileInputStream) KisaoTerm(org.jlibsedml.modelsupport.KisaoTerm) Simulation(cbit.vcell.solver.Simulation) URLResourceRetriever(org.jlibsedml.modelsupport.URLResourceRetriever) KisaoOntology(org.jlibsedml.modelsupport.KisaoOntology) ArchiveModelResolver(org.jlibsedml.execution.ArchiveModelResolver) Model(org.jlibsedml.Model) SEDMLDocument(org.jlibsedml.SEDMLDocument) DataGenerator(org.jlibsedml.DataGenerator) BioModel(cbit.vcell.biomodel.BioModel) BioModel(cbit.vcell.biomodel.BioModel) Model(org.jlibsedml.Model) UniformTimeCourse(org.jlibsedml.UniformTimeCourse) XMLSource(cbit.vcell.xml.XMLSource) Application(cbit.vcell.mapping.SimulationContext.Application)

Example 3 with ArchiveModelResolver

use of org.jlibsedml.execution.ArchiveModelResolver in project vcell by virtualcell.

the class XmlHelper method sedmlToBioModel.

public static List<VCDocument> sedmlToBioModel(VCLogger transLogger, ExternalDocInfo externalDocInfo, SedML sedml, List<AbstractTask> tasks, String sedmlFileLocation, boolean exactMatchOnly) throws Exception {
    if (sedml.getModels().isEmpty()) {
        throw new Exception("No models found in SED-ML document");
    }
    try {
        // iterate through all the elements and show them at the console
        List<org.jlibsedml.Model> mmm = sedml.getModels();
        for (Model mm : mmm) {
            System.out.println(mm.toString());
        }
        List<org.jlibsedml.Simulation> sss = sedml.getSimulations();
        for (org.jlibsedml.Simulation ss : sss) {
            System.out.println(ss.toString());
        }
        List<AbstractTask> ttt = sedml.getTasks();
        if (ttt.isEmpty()) {
            throw new Exception("No tasks found in SED-ML document");
        }
        for (AbstractTask tt : ttt) {
            System.out.println(tt.toString());
        }
        List<DataGenerator> ddd = sedml.getDataGenerators();
        for (DataGenerator dd : ddd) {
            System.out.println(dd.toString());
        }
        List<Output> ooo = sedml.getOutputs();
        for (Output oo : ooo) {
            System.out.println(oo.toString());
        }
        if (ooo.isEmpty()) {
            System.err.println("List of outputs cannot be empty!");
        }
        if (tasks == null || tasks.isEmpty()) {
            // no task selection, we'll import all that we find in the SED-ML
            tasks = sedml.getTasks();
        }
        // We need to make a separate BioModel for each SED-ML model
        // We will parse all tasks and create Simulations for each in the BioModel(s) corresponding to the model referenced by the tasks
        List<VCDocument> docs = new ArrayList<VCDocument>();
        // extract bioModel name from sedx (or sedml) file
        String bioModelBaseName = FileUtils.getBaseName(externalDocInfo.getFile().getAbsolutePath());
        String kisaoID = null;
        // this will become the vCell simulation
        org.jlibsedml.Simulation sedmlSimulation = null;
        // the "original" model referred to by the task
        org.jlibsedml.Model sedmlOriginalModel = null;
        // this will be used in the BioModel name
        String sedmlOriginalModelName = null;
        // can be sbml or vcml
        String sedmlOriginalModelLanguage = null;
        ArchiveComponents ac = null;
        if (externalDocInfo.getFile().getPath().toLowerCase().endsWith("sedx") || externalDocInfo.getFile().getPath().toLowerCase().endsWith("omex")) {
            ac = Libsedml.readSEDMLArchive(new FileInputStream(externalDocInfo.getFile().getPath()));
        }
        ModelResolver resolver = new ModelResolver(sedml);
        if (ac != null) {
            resolver.add(new ArchiveModelResolver(ac));
        }
        resolver.add(new FileModelResolver());
        if (sedmlFileLocation != null) {
            File sedmlFile = new File(sedmlFileLocation);
            String sedmlRelativePrefix = sedmlFile.getParent() + File.separator;
            if (sedmlRelativePrefix != null) {
                resolver.add(new RelativeFileModelResolver(sedmlRelativePrefix));
            }
        }
        for (AbstractTask selectedTask : tasks) {
            if (selectedTask instanceof Task) {
                sedmlOriginalModel = sedml.getModelWithId(selectedTask.getModelReference());
                sedmlSimulation = sedml.getSimulation(selectedTask.getSimulationReference());
            } else if (selectedTask instanceof RepeatedTask) {
                System.err.println("RepeatedTask not supported yet, task " + SEDMLUtil.getName(selectedTask) + " is being skipped");
                continue;
            // TODO the below is unfinished code
            // RepeatedTask rt = (RepeatedTask)selectedTask;
            // assert(rt.getSubTasks().size() == 1);
            // SubTask st = rt.getSubTasks().entrySet().iterator().next().getValue();		// first (and only) subtask
            // String taskId = st.getTaskId();
            // AbstractTask t = sedml.getTaskWithId(taskId);
            // sedmlOriginalModel = sedml.getModelWithId(t.getModelReference());			// get model and simulation from subtask
            // sedmlSimulation = sedml.getSimulation(t.getSimulationReference());
            } else {
                throw new RuntimeException("Unexpected task " + selectedTask);
            }
            sedmlOriginalModelName = sedmlOriginalModel.getId();
            sedmlOriginalModelLanguage = sedmlOriginalModel.getLanguage();
            // at this point we assume that the sedml simulation, algorithm and kisaoID are all valid
            Algorithm algorithm = sedmlSimulation.getAlgorithm();
            kisaoID = algorithm.getKisaoID();
            // identify the vCell solvers that would match best the sedml solver kisao id
            // try to find a match in the ontology tree
            SolverDescription solverDescription = SolverUtilities.matchSolverWithKisaoId(kisaoID, exactMatchOnly);
            if (solverDescription != null) {
                System.out.println("Task (id='" + selectedTask.getId() + "') is compatible, solver match found in ontology: '" + kisaoID + "' matched to " + solverDescription);
            } else {
                // give it a try anyway with our deterministic default solver
                solverDescription = SolverDescription.CombinedSundials;
                System.err.println("Task (id='" + selectedTask.getId() + ")' is not compatible, no equivalent solver found in ontology for requested algorithm '" + kisaoID + "'; trying with deterministic default solver " + solverDescription);
            }
            // find out everything else we need about the application we're going to use,
            // some of the info will be needed when we parse the sbml file
            boolean bSpatial = false;
            Application appType = Application.NETWORK_DETERMINISTIC;
            Set<SolverDescription.SolverFeature> sfList = solverDescription.getSupportedFeatures();
            for (SolverDescription.SolverFeature sf : sfList) {
                switch(sf) {
                    case Feature_Rulebased:
                        appType = Application.RULE_BASED_STOCHASTIC;
                        break;
                    case Feature_Stochastic:
                        appType = Application.NETWORK_STOCHASTIC;
                        break;
                    case Feature_Deterministic:
                        appType = Application.NETWORK_DETERMINISTIC;
                        break;
                    case Feature_Spatial:
                        bSpatial = true;
                        break;
                    default:
                        break;
                }
            }
            // we make a biomodel for each task; if there are many simulations, probably
            // only one will match the selected task id, the others are parasites and must not be run
            BioModel bioModel = null;
            boolean justMade = false;
            String newMdl = resolver.getModelString(sedmlOriginalModel);
            String bioModelName = bioModelBaseName + "_" + sedml.getFileName() + "_" + sedmlOriginalModelName;
            // get it if we made it already
            for (VCDocument existingDoc : docs) {
                if (!docs.isEmpty()) {
                    if (existingDoc.getName().equals(bioModelName)) {
                        bioModel = (BioModel) existingDoc;
                        break;
                    }
                }
            }
            // make it if we didn't and mark it as fresh
            if (bioModel == null) {
                if (sedmlOriginalModelLanguage.contentEquals(SUPPORTED_LANGUAGE.VCELL_GENERIC.getURN())) {
                    // vcml
                    XMLSource vcmlSource = new XMLSource(newMdl);
                    bioModel = (BioModel) XmlHelper.XMLToBioModel(vcmlSource);
                    bioModel.setName(bioModelName);
                    docs.add(bioModel);
                    justMade = true;
                    try {
                        bioModel.getVCMetaData().createBioPaxObjects(bioModel);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    // we assume it's sbml, if it's neither import will fail
                    // sbmlSource with all the changes applied
                    XMLSource sbmlSource = new XMLSource(newMdl);
                    bioModel = (BioModel) XmlHelper.importSBML(transLogger, sbmlSource, bSpatial);
                    bioModel.setName(bioModelName);
                    docs.add(bioModel);
                    justMade = true;
                }
            }
            if (sedmlOriginalModelLanguage.contentEquals(SUPPORTED_LANGUAGE.VCELL_GENERIC.getURN())) {
                // we basically ignore the sedml simulation altogether
                for (Simulation sim : bioModel.getSimulations()) {
                    if (sim.getName().equals(selectedTask.getName())) {
                        System.out.println(" --- selected task - name: " + selectedTask.getName() + ", id: " + selectedTask.getId());
                        sim.setImportedTaskID(selectedTask.getId());
                    }
                }
                continue;
            }
            // even if we just created the biomodel from the sbml file we have at least one application with initial conditions and stuff
            // see if there is a suitable application type for the sedml kisao
            // if not, we add one by doing a "copy as" to the right type
            SimulationContext[] existingSimulationContexts = bioModel.getSimulationContexts();
            SimulationContext matchingSimulationContext = null;
            for (SimulationContext simContext : existingSimulationContexts) {
                if (simContext.getApplicationType().equals(appType) && ((simContext.getGeometry().getDimension() > 0) == bSpatial)) {
                    matchingSimulationContext = simContext;
                    break;
                }
            }
            if (matchingSimulationContext == null) {
                if (justMade) {
                    matchingSimulationContext = SimulationContext.copySimulationContext(existingSimulationContexts[0], sedmlOriginalModelName, bSpatial, appType);
                    bioModel.removeSimulationContext(existingSimulationContexts[0]);
                } else {
                    matchingSimulationContext = SimulationContext.copySimulationContext(existingSimulationContexts[0], sedmlOriginalModelName + "_" + existingSimulationContexts.length, bSpatial, appType);
                }
                bioModel.addSimulationContext(matchingSimulationContext);
            }
            // making the new vCell simulation based on the sedml simulation
            matchingSimulationContext.refreshDependencies();
            MathMappingCallback callback = new MathMappingCallbackTaskAdapter(null);
            matchingSimulationContext.refreshMathDescription(callback, NetworkGenerationRequirements.ComputeFullStandardTimeout);
            Simulation newSimulation = new Simulation(matchingSimulationContext.getMathDescription());
            newSimulation.setSimulationOwner(matchingSimulationContext);
            if (selectedTask instanceof Task) {
                String newSimName = selectedTask.getId();
                if (SEDMLUtil.getName(selectedTask) != null) {
                    newSimName += "_" + SEDMLUtil.getName(selectedTask);
                }
                newSimulation.setName(newSimName);
                newSimulation.setImportedTaskID(selectedTask.getId());
            } else {
                newSimulation.setName(SEDMLUtil.getName(sedmlSimulation) + "_" + SEDMLUtil.getName(selectedTask));
            }
            // we identify the type of sedml simulation (uniform time course, etc)
            // and set the vCell simulation parameters accordingly
            SolverTaskDescription simTaskDesc = newSimulation.getSolverTaskDescription();
            if (solverDescription != null) {
                simTaskDesc.setSolverDescription(solverDescription);
            }
            TimeBounds timeBounds = new TimeBounds();
            TimeStep timeStep = new TimeStep();
            double outputTimeStep = 0.1;
            int outputNumberOfPoints = 1;
            if (sedmlSimulation instanceof UniformTimeCourse) {
                // we translate initial time to zero, we provide output for the duration of the simulation
                // because we can't select just an interval the way the SEDML simulation can
                double initialTime = ((UniformTimeCourse) sedmlSimulation).getInitialTime();
                double outputStartTime = ((UniformTimeCourse) sedmlSimulation).getOutputStartTime();
                double outputEndTime = ((UniformTimeCourse) sedmlSimulation).getOutputEndTime();
                outputNumberOfPoints = ((UniformTimeCourse) sedmlSimulation).getNumberOfPoints();
                outputTimeStep = (outputEndTime - outputStartTime) / outputNumberOfPoints;
                timeBounds = new TimeBounds(0, outputEndTime - initialTime);
                ErrorTolerance errorTolerance = new ErrorTolerance();
                // we look for explicit algorithm parameters
                List<AlgorithmParameter> sedmlAlgorithmParameters = algorithm.getListOfAlgorithmParameters();
                for (AlgorithmParameter sedmlAlgorithmParameter : sedmlAlgorithmParameters) {
                    String apKisaoID = sedmlAlgorithmParameter.getKisaoID();
                    String apValue = sedmlAlgorithmParameter.getValue();
                    if (apKisaoID == null || apKisaoID.isEmpty()) {
                        System.err.println("Undefined KisaoID algorithm parameter for algorithm '" + kisaoID + "'");
                    }
                    // TODO: use the proper ontology for the algorithm parameters kisao id
                    if (apKisaoID.contentEquals(ErrorTolerance.ErrorToleranceDescription.Absolute.getKisao())) {
                        double value = Double.parseDouble(apValue);
                        errorTolerance.setAbsoluteErrorTolerance(value);
                    } else if (apKisaoID.contentEquals(ErrorTolerance.ErrorToleranceDescription.Relative.getKisao())) {
                        double value = Double.parseDouble(apValue);
                        errorTolerance.setRelativeErrorTolerance(value);
                    } else if (apKisaoID.contentEquals(TimeStep.TimeStepDescription.Default.getKisao())) {
                        double value = Double.parseDouble(apValue);
                        timeStep.setDefaultTimeStep(value);
                    } else if (apKisaoID.contentEquals(TimeStep.TimeStepDescription.Maximum.getKisao())) {
                        double value = Double.parseDouble(apValue);
                        timeStep.setMaximumTimeStep(value);
                    } else if (apKisaoID.contentEquals(TimeStep.TimeStepDescription.Minimum.getKisao())) {
                        double value = Double.parseDouble(apValue);
                        timeStep.setMinimumTimeStep(value);
                    } else if (apKisaoID.contentEquals(AlgorithmParameterDescription.Seed.getKisao())) {
                        // custom seed
                        if (simTaskDesc.getSimulation().getMathDescription().isNonSpatialStoch()) {
                            NonspatialStochSimOptions nssso = simTaskDesc.getStochOpt();
                            int value = Integer.parseInt(apValue);
                            nssso.setCustomSeed(value);
                        } else {
                            System.err.println("Algorithm parameter '" + AlgorithmParameterDescription.Seed.getDescription() + "' is only supported for nonspatial stochastic simulations");
                        }
                    // some arguments used only for non-spatial hybrid solvers
                    } else if (apKisaoID.contentEquals(AlgorithmParameterDescription.Epsilon.getKisao())) {
                        NonspatialStochHybridOptions nssho = simTaskDesc.getStochHybridOpt();
                        nssho.setEpsilon(Double.parseDouble(apValue));
                    } else if (apKisaoID.contentEquals(AlgorithmParameterDescription.Lambda.getKisao())) {
                        NonspatialStochHybridOptions nssho = simTaskDesc.getStochHybridOpt();
                        nssho.setLambda(Double.parseDouble(apValue));
                    } else if (apKisaoID.contentEquals(AlgorithmParameterDescription.MSRTolerance.getKisao())) {
                        NonspatialStochHybridOptions nssho = simTaskDesc.getStochHybridOpt();
                        nssho.setMSRTolerance(Double.parseDouble(apValue));
                    } else if (apKisaoID.contentEquals(AlgorithmParameterDescription.SDETolerance.getKisao())) {
                        NonspatialStochHybridOptions nssho = simTaskDesc.getStochHybridOpt();
                        nssho.setSDETolerance(Double.parseDouble(apValue));
                    } else {
                        System.err.println("Algorithm parameter with kisao id '" + apKisaoID + "' not supported at this time, skipping.");
                    }
                }
                simTaskDesc.setErrorTolerance(errorTolerance);
            } else if (sedmlSimulation instanceof OneStep) {
                // for anything other than UniformTimeCourse we just ignore
                System.err.println("OneStep Simulation not supported");
                continue;
            } else if (sedmlSimulation instanceof SteadyState) {
                System.err.println("SteadyState Simulation not supported");
                continue;
            }
            OutputTimeSpec outputTimeSpec = new UniformOutputTimeSpec(outputTimeStep);
            simTaskDesc.setTimeBounds(timeBounds);
            simTaskDesc.setTimeStep(timeStep);
            if (simTaskDesc.getSolverDescription().supports(outputTimeSpec)) {
                simTaskDesc.setOutputTimeSpec(outputTimeSpec);
            } else {
                simTaskDesc.setOutputTimeSpec(new DefaultOutputTimeSpec(1, Integer.max(DefaultOutputTimeSpec.DEFAULT_KEEP_AT_MOST, outputNumberOfPoints)));
            }
            newSimulation.setSolverTaskDescription(simTaskDesc);
            newSimulation.setDescription(SEDMLUtil.getName(selectedTask));
            bioModel.addSimulation(newSimulation);
            newSimulation.refreshDependencies();
        }
        return docs;
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("Unable to initialize bioModel for the given selection\n" + e.getMessage());
    }
}
Also used : Task(org.jlibsedml.Task) RepeatedTask(org.jlibsedml.RepeatedTask) SimulationTask(cbit.vcell.messaging.server.SimulationTask) AbstractTask(org.jlibsedml.AbstractTask) SubTask(org.jlibsedml.SubTask) ArrayList(java.util.ArrayList) ArchiveModelResolver(org.jlibsedml.execution.ArchiveModelResolver) FileModelResolver(org.jlibsedml.execution.FileModelResolver) RelativeFileModelResolver(org.vcell.sedml.RelativeFileModelResolver) ModelResolver(org.jlibsedml.execution.ModelResolver) SteadyState(org.jlibsedml.SteadyState) VCDocument(org.vcell.util.document.VCDocument) MathMappingCallback(cbit.vcell.mapping.SimulationContext.MathMappingCallback) Algorithm(org.jlibsedml.Algorithm) FileInputStream(java.io.FileInputStream) ArchiveModelResolver(org.jlibsedml.execution.ArchiveModelResolver) DataGenerator(org.jlibsedml.DataGenerator) UniformTimeCourse(org.jlibsedml.UniformTimeCourse) AlgorithmParameter(org.jlibsedml.AlgorithmParameter) File(java.io.File) Application(cbit.vcell.mapping.SimulationContext.Application) AbstractTask(org.jlibsedml.AbstractTask) RelativeFileModelResolver(org.vcell.sedml.RelativeFileModelResolver) OneStep(org.jlibsedml.OneStep) ArchiveComponents(org.jlibsedml.ArchiveComponents) RepeatedTask(org.jlibsedml.RepeatedTask) Output(org.jlibsedml.Output) MathMappingCallbackTaskAdapter(cbit.vcell.mapping.MathMappingCallbackTaskAdapter) FileModelResolver(org.jlibsedml.execution.FileModelResolver) RelativeFileModelResolver(org.vcell.sedml.RelativeFileModelResolver) SimulationContext(cbit.vcell.mapping.SimulationContext) XMLStreamException(javax.xml.stream.XMLStreamException) SbmlException(org.vcell.sbml.SbmlException) SBMLException(org.sbml.jsbml.SBMLException) IOException(java.io.IOException) ExpressionException(cbit.vcell.parser.ExpressionException) Model(org.jlibsedml.Model) BioModel(cbit.vcell.biomodel.BioModel) MathModel(cbit.vcell.mathmodel.MathModel) BioModel(cbit.vcell.biomodel.BioModel) Model(org.jlibsedml.Model)

Aggregations

BioModel (cbit.vcell.biomodel.BioModel)3 MathMappingCallbackTaskAdapter (cbit.vcell.mapping.MathMappingCallbackTaskAdapter)3 SimulationContext (cbit.vcell.mapping.SimulationContext)3 Application (cbit.vcell.mapping.SimulationContext.Application)3 MathMappingCallback (cbit.vcell.mapping.SimulationContext.MathMappingCallback)3 FileInputStream (java.io.FileInputStream)3 ArrayList (java.util.ArrayList)3 AbstractTask (org.jlibsedml.AbstractTask)3 ArchiveComponents (org.jlibsedml.ArchiveComponents)3 DataGenerator (org.jlibsedml.DataGenerator)3 Model (org.jlibsedml.Model)3 OneStep (org.jlibsedml.OneStep)3 Output (org.jlibsedml.Output)3 SteadyState (org.jlibsedml.SteadyState)3 UniformTimeCourse (org.jlibsedml.UniformTimeCourse)3 ArchiveModelResolver (org.jlibsedml.execution.ArchiveModelResolver)3 ModelResolver (org.jlibsedml.execution.ModelResolver)3 MathModel (cbit.vcell.mathmodel.MathModel)2 SimulationTask (cbit.vcell.messaging.server.SimulationTask)2 ExpressionException (cbit.vcell.parser.ExpressionException)2