public static void Main(String[] args)
    {
        if (args.Length == 0)
        {
            Console.WriteLine("Need one argument, copasi file");
            Environment.Exit(1);
        }

        CDataModel dataModel = CRootContainer.addDatamodel();

        if (!dataModel.loadModel(args[0]))
        {
            Console.WriteLine("Could not open file");
            Console.WriteLine(CCopasiMessage.getAllMessageText());
            Environment.Exit(1);
        }

        CModel model = dataModel.getModel();
        ModelParameterSetVectorN sets = model.getModelParameterSets();

        // if we don't have one, create one
        if (sets.size() == 0)
        {
            CModelParameterSet newSet = new CModelParameterSet("Current State", model);
            newSet.createFromModel();
            printParameterSet(newSet);
            sets.add(newSet);
        }

        // interrogate the exiting parameter sets
        printExistingParametersets(model.getModelParameterSets());
    }
    public static void Main(String[] args)
    {
        // create a new datamodel
        CDataModel dataModel = CRootContainer.addDatamodel();

        if (args.Length != 1)
        {
            Console.WriteLine("Need one argument: SBML | CPS filename.");
            Environment.Exit(1);
        }

        String filename = args[0];

        try
        {
            String ext = System.IO.Path.GetExtension(filename);
            if (ext.Trim().ToLowerInvariant().EndsWith("xml"))
            {
                // load the model without progress report
                dataModel.importSBML(filename);
            }
            else
            {
                // load the model without progress report
                dataModel.loadModel(filename);
            }
        }
        catch
        {
            Console.WriteLine("Error while loading the model from file named \"" + filename + "\".");
            Environment.Exit(1);
        }
        try
        {
            CModel model          = dataModel.getModel();
            int    numAnnotations = model.getNumUnsupportedAnnotations();
            Console.WriteLine("The model has: " + numAnnotations + " unsupported annotations.");

            if (numAnnotations == 0)
            {
                Console.WriteLine("adding custom annotation");
                // we don't have an annotation, so lets add one
                if (!model.addUnsupportedAnnotation("http://myannotation.org", "<test xmlns='http://myannotation.org' value='blaaaahaaa'/>"))
                {
                    Console.WriteLine("couldn't set annotation: ");
                    Console.WriteLine(CCopasiMessage.getAllMessageText());
                }
            }
            Console.WriteLine("The name of the first is: " + model.getUnsupportedAnnotationName(0));
            Console.WriteLine("The raw xml of the first is: " + model.getUnsupportedAnnotation(0));
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error: " + ex.Message);
        }
    }
Exemplo n.º 3
0
    public static void Main(String[] args)
    {
        // create a new datamodel
        CCopasiDataModel dataModel = CCopasiRootContainer.addDatamodel();

        if (args.Length != 2)
        {
            Console.WriteLine("Need two arguments: filename and filter.");
            Environment.Exit(1);
        }

        String filename = args[0];

        try
        {
            String ext = System.IO.Path.GetExtension(filename);
            if (ext.Trim().ToLowerInvariant() == "xml")
            {
                // load the model without progress report
                dataModel.importSBML(filename);
            }
            else
            {
                // load the model without progress report
                dataModel.loadModel(filename);
            }
        }
        catch
        {
            Console.WriteLine("Error while loading the model from file named \"" + filename + "\".");
            Environment.Exit(1);
        }
        try
        {
            // clear warnings / error messages
            CCopasiMessage.clearDeque();

            // convert
            String translation = dataModel.exportMathModelToString(args[1]);

            // if conversion failed print message
            if (string.IsNullOrEmpty(translation))
            {
                Console.WriteLine("Translation failed: ");
                Console.WriteLine(CCopasiMessage.getAllMessageText());
            }

            // print translation
            Console.WriteLine(translation);
        }
        catch
        {
            Console.WriteLine("Error. Exporting the model to math failed.");
        }
    }
Exemplo n.º 4
0
    static void Main(string[] args)
    {
        if (args.Length == 0)
        {
            Console.WriteLine("usage: process_callback <cps file>");
            return;
        }

        var dataModel = CRootContainer.addDatamodel();

        if (!dataModel.loadModel(args[0]))
        {
            Console.WriteLine("Couldn't open the model: ");
            Console.WriteLine(CCopasiMessage.getAllMessageText());
            return;
        }

        var progress = new ProcessCallback();

        Console.CancelKeyPress += delegate {
            Console.WriteLine("Stop requested ... waiting for process to finish");
            progress.ShouldProceed = false;

            Thread.Sleep(30000);
        };


        for (uint i = 0; i < dataModel.getNumTasks(); ++i)
        {
            var task = dataModel.getTask(i);
            if (!task.isScheduled())
            {
                continue;
            }
            Console.WriteLine(string.Format("Running Scheduled Task: {0}, stop anytime using CTRL+C", task.getObjectName()));

            // set progress support
            task.setCallBack(progress);

            // execute the task
            task.process(true);

            // unset
            task.clearCallBack();
        }
    }
Exemplo n.º 5
0
        /// <summary>
        /// Simulate a Step and return data
        /// </summary>
        /// <param name="stepDuration">Step duration in seconds.</param>
        public SimulationStep Step(double stepDuration)
        {
            CTrajectoryTask trajectoryTask = copasi.TrajectoryTask;

            CTrajectoryProblem problem = (CTrajectoryProblem)trajectoryTask.getProblem();

            problem.setDuration(stepDuration);

            currentTime += stepDuration;

            try
            {
                // now we run the actual trajectory
                trajectoryTask.processWithOutputFlags(true, (int)CCopasiTask.NO_OUTPUT);
            }
            catch
            {
                if (CCopasiMessage.size() > 0)
                {
                    throw new System.Exception("Running the time course simulation failed: " + CCopasiMessage.getAllMessageText(true));
                }

                throw new System.Exception("Running the time course simulation failed");
            }

            // Update the species properties that have changed
            ReactionCount[] reactionCount = new ReactionCount[reactionList.Count];

            for (int i = 0; i < reactionList.Count; i++)
            {
                CopasiReactionGroup r = reactionList[i];

                reactionCount[i] = r.CalcParticleFlux();
            }

            // clean up
            trajectoryTask.restore();

            return(new SimulationStep(reactionCount));
        }
Exemplo n.º 6
0
    static void Main()
    {
        Debug.Assert((CRootContainer.getRoot() != null));
        // create a new datamodel
        CDataModel dataModel = CRootContainer.addDatamodel();

        Debug.Assert((dataModel != null));
        Debug.Assert((CRootContainer.getDatamodelList().size() == 1));
        // next we import a simple SBML model from a string

        // clear the message queue so that we only have error messages from the import in the queue
        CCopasiMessage.clearDeque();
        bool result = true;

        try
        {
            result = dataModel.importSBMLFromString(MODEL_STRING);
        }
        catch
        {
            System.Console.Error.WriteLine("Import of model failed miserably.");
            System.Environment.Exit(1);
        }
        // check if the import was successful
        int mostSevere = CCopasiMessage.getHighestSeverity();

        // if it was a filtered error, we convert it to an unfiltered type
        // the filtered error messages have the same value as the unfiltered, but they
        // have the 7th bit set which basically adds 128 to the value
        mostSevere = mostSevere & 127;

        // we assume that the import succeeded if the return value is true and
        // the most severe error message is not an error or an exception
        if (result != true && mostSevere < CCopasiMessage.ERROR)
        {
            System.Console.Error.WriteLine("Sorry. Model could not be imported.");
            System.Environment.Exit(1);
        }

        //
        // now we tell the model object to calculate the jacobian
        //
        CModel model = dataModel.getModel();

        Debug.Assert((model != null));

        if (model != null)
        {
            // running a task, e.g. a trajectory will automatically make sure that
            // the initial values are transferred to the current state before the calculation begins.
            // If we use low level calculation methods like the one to calculate the jacobian, we
            // have to make sure the the initial values are applied to the state
            model.applyInitialValues();
            // we need an array that stores the result
            // the size of the matrix does not really matter because
            // the calculateJacobian autoamtically resizes it to the correct
            // size
            FloatMatrix jacobian = new FloatMatrix();
            // the first parameter to the calculation function is a reference to
            // the matrix where the result is to be stored
            // the second parameter is the derivationFactor for the calculation
            // it basically represents a relative delta value for the calculation of the derivatives
            // the third parameter is a boolean indicating whether the jacobian should
            // be calculated from the reduced (true) or full (false) system
            model.getMathContainer().calculateJacobian(jacobian, 1e-12, false);
            // now we print the result
            // the jacobian stores the values in the order they are
            // given in the user order in the state template so it is not really straight
            // forward to find out which column/row corresponds to which species
            CStateTemplate stateTemplate = model.getStateTemplate();
            // and we need the user order
            SizeTVector userOrder = stateTemplate.getUserOrder();
            // from those two, we can construct an new vector that contains
            // the names of the entities in the jacobian in the order in which they appear in
            // the jacobian
            System.Collections.Generic.List <string> nameVector = new System.Collections.Generic.List <string>();
            CModelEntity entity = null;
            int          status;

            for (uint i = 0; i < userOrder.size(); ++i)
            {
                entity = stateTemplate.getEntity(userOrder.get(i));
                Debug.Assert((entity != null));
                // now we need to check if the entity is actually
                // determined by an ODE or a reaction
                status = entity.getStatus();

                if (status == CModelEntity.Status_ODE ||
                    (status == CModelEntity.Status_REACTIONS && entity.isUsed()))
                {
                    nameVector.Add(entity.getObjectName());
                }
            }

            Debug.Assert((nameVector.Count == jacobian.numRows()));
            // now we print the matrix, for this we assume that no
            // entity name is longer then 5 character which is a save bet since
            // we know the model
            System.Console.Out.NewLine = "";
            System.Console.WriteLine(System.String.Format("Jacobian Matrix:{0}", System.Environment.NewLine));
            System.Console.WriteLine(System.String.Format("size:{0}x{1}{2}", jacobian.numRows(), jacobian.numCols(), System.Environment.NewLine));
            System.Console.WriteLine(System.String.Format("{0}", System.Environment.NewLine));
            System.Console.Out.WriteLine(System.String.Format("{0,7}", " "));

            for (int i = 0; i < nameVector.Count; ++i)
            {
                System.Console.Out.WriteLine(System.String.Format("{0,7}", nameVector[i]));
            }

            System.Console.WriteLine(System.String.Format("{0}", System.Environment.NewLine));

            for (uint i = 0; i < nameVector.Count; ++i)
            {
                System.Console.Out.WriteLine(System.String.Format("{0,7}", nameVector[(int)i]));

                for (uint j = 0; j < nameVector.Count; ++j)
                {
                    System.Console.Out.WriteLine(System.String.Format("{0,7:0.###}", jacobian.get(i, j)));
                }

                System.Console.WriteLine(System.String.Format("{0}", System.Environment.NewLine));
            }

            // we can also calculate the jacobian of the reduced system
            // in a similar way
            model.getMathContainer().calculateJacobian(jacobian, 1e-12, true);
            // this time generating the output is actually simpler because the rows
            // and columns are ordered in the same way as the independent variables of the state temple
            System.Console.WriteLine(System.String.Format("{0}{0}", System.Environment.NewLine));
            System.Console.WriteLine(System.String.Format("Reduced Jacobian Matrix:{0}{0}", System.Environment.NewLine));
            System.Console.Out.WriteLine(System.String.Format("{0:6}", " "));

            uint iMax = stateTemplate.getNumIndependent();

            for (uint i = 0; i < iMax; ++i)
            {
                System.Console.Out.WriteLine(System.String.Format("\t{0:7}", stateTemplate.getIndependent(i).getObjectName()));
            }

            System.Console.WriteLine(System.String.Format("{0}", System.Environment.NewLine));

            for (uint i = 0; i < iMax; ++i)
            {
                System.Console.Out.WriteLine(System.String.Format("{0:7}", stateTemplate.getIndependent(i).getObjectName()));

                for (uint j = 0; j < iMax; ++j)
                {
                    System.Console.Out.WriteLine(System.String.Format("{0,7:0.###}", jacobian.get(i, j)));
                }

                System.Console.WriteLine(System.String.Format("{0}", System.Environment.NewLine));
            }
        }
    }
Exemplo n.º 7
0
    static void Main()
    {
        // initialize the backend library
        // since we are not interested in the arguments
        // that are passed to main, we pass 0 and NULL to
        // init
        Debug.Assert(CCopasiRootContainer.getRoot() != null);
        // create a new datamodel
        CCopasiDataModel dataModel = CCopasiRootContainer.addDatamodel();

        Debug.Assert((dataModel != null));
        Debug.Assert((CCopasiRootContainer.getDatamodelList().size() == 1));
        // next we import a simple SBML model from a string

        // clear the message queue so that we only have error messages from the import in the queue
        CCopasiMessage.clearDeque();
        bool result = true;

        try
        {
            result = dataModel.importSBMLFromString(MODEL_STRING);
        }
        catch
        {
            System.Console.Error.WriteLine("An exception has occured during the import of the SBML model");
            System.Environment.Exit(1);
        }
        // check if the import was successful
        int mostSevere = CCopasiMessage.getHighestSeverity();

        // if it was a filtered error, we convert it to an unfiltered type
        // the filtered error messages have the same value as the unfiltered, but they
        // have the 7th bit set which basically adds 128 to the value
        mostSevere = mostSevere & 127;

        // we assume that the import succeeded if the return value is true and
        // the most severe error message is not an error or an exception
        if (result != true && mostSevere < CCopasiMessage.ERROR)
        {
            System.Console.Error.WriteLine("Sorry. Model could not be imported.");
            System.Environment.Exit(1);
        }

        // get the trajectory task object
        CSteadyStateTask task = (CSteadyStateTask)dataModel.getTask("Steady-State");

        CCopasiMessage.clearDeque();

        try
        {
            // now we run the actual trajectory
            task.processWithOutputFlags(true, (int)CCopasiTask.ONLY_TIME_SERIES);
        }
        catch
        {
            System.Console.Error.WriteLine("Error. Running the scan failed.");

            String lastErrors = task.getProcessError();
            // check if there are additional error messages
            if (!string.IsNullOrEmpty(lastErrors))
            {
                // print the messages in chronological order
                System.Console.Error.WriteLine(lastErrors);
            }

            System.Environment.Exit(1);
        }

        // now we can get the result of the steady state calculation, e.g. the jacobian
        // matrix of the model at the steady state
        // here we can either get the jacobian as we did in example 8 as a matrix with
        // getJacobian, or we can use getJacobianAnnotated to get an annotated matrix
        // Corresponding methods for the reduced jacobian are getJacobianX and getJacobianXAnnotated
        CArrayAnnotation aj = task.getJacobianAnnotated();

        Debug.Assert((aj != null));

        if (aj != null)
        {
            // we do the output, but as in contrast to the jacobian in example 8,
            // we now have all the information for the output in one place

            // first the array annotation can tell us how many dimensions it has.
            // Since the matrix is a 2D array, it should have 2 dimensions
            Debug.Assert((aj.dimensionality() == 2));
            // since the matrix has a dimensionality of 2, the inde for the underlaying abstract array
            // object is a vector with two unsigned int elements
            // First element is the index for the outer dimension and the second element is the index
            // for the inner dimension
            SizeTStdVector index = new SizeTStdVector();
            // The constructor does not seem to interpret an integer argument
            // as the size
            // I though that in C# we might be able to achieve this using the Capacity property
            // but that didn't work. Maybe I was using it incorrectly since I don't really know C#
            // So for now, we just add two elements to the vector which seems to do the trick.
            index.Add(0);
            index.Add(0);
            // since the rows and columns have the same annotation for the jacobian, it doesn't matter
            // for which dimension we get the annotations
            StringStdVector annotations = aj.getAnnotationsString(1);
            System.Console.Out.NewLine = "";
            System.Console.WriteLine(System.String.Format("Jacobian Matrix:{0}{0}", System.Environment.NewLine));
            System.Console.Out.WriteLine(System.String.Format("{0,7}", " "));

            for (int i = 0; i < annotations.Count; ++i)
            {
                Console.Out.WriteLine(System.String.Format("{0,7}", annotations[i]));
            }

            Console.WriteLine(System.String.Format("{0}", System.Environment.NewLine));

            for (int i = 0; i < annotations.Count; ++i)
            {
                System.Console.Out.WriteLine(System.String.Format("{0,7} ", annotations[i]));
                index[0] = (uint)i;

                for (int j = 0; j < annotations.Count; ++j)
                {
                    index[1] = (uint)j;
                    System.Console.Out.WriteLine(System.String.Format("{0,7:G2} ", aj.array().get(index)));
                }
                System.Console.WriteLine(System.String.Format("{0}", System.Environment.NewLine));
            }
        }
        System.Environment.Exit(0);
    }