Unverified Commit 5653d9e4 authored by Laurent Heirendt's avatar Laurent Heirendt Committed by GitHub
Browse files

Merge pull request #1 from LCSB-BioCore/mk

working version n.1
parents 90ae6cfc 7bd5e709
......@@ -22,3 +22,10 @@ docs/site/
# committed for packages, but should be committed for applications that require a static
# environment.
Manifest.toml
#vim
.*.swp
#BinaryBuilder
/build
/products
MIT License
Copyright (c) 2021 Luxembourg Centre for Systems Biomedicine
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
name = "SBML"
uuid = "e5567a89-2604-4b09-9718-f5f78e97c3bb"
authors = ["Mirek Kratochvil <miroslav.kratochvil@uni.lu>",
"LCSB R3 team <lcsb-r3@uni.lu>"]
version = "0.1.0"
[deps]
Libdl = "8f399da3-3557-5675-b5ff-fb832c97cbdb"
Pkg = "44cfe95a-1eb2-52ea-b672-e2afdf69b78f"
SBML_jll = "bb12108a-f4ef-5f88-8ef3-0b33ff7017f1"
# SBML.jl
\ No newline at end of file
# SBML.jl
This is a simple wrap of some of the libSBML functionality.
Current status is "under development", something works, more wrapped stuff will
be added by need.
## Usage
```julia
using SBML
m = readSBML("myModel.xml")
# m is now a Model with
m.reactions
m.species
m.compartments
...
```
There are several helper functions, for example you can get a nice list of reactions, metabolites and the stoichiometric matrix as follows:
```julia
mets, rxns, S = getS(model)
```
[deps]
Documenter = "e30172f5-a6a5-5a46-863b-614d45cd2de4"
DocumenterTools = "35a29f4d-8980-5a13-9543-d66fff28ecb8"
using Documenter, SBML
makedocs(modules = [SBML],
clean = false,
format = Documenter.HTML(prettyurls = !("local" in ARGS)),
sitename = "SBML.jl",
authors = "The developers of SBML.jl",
linkcheck = !("skiplinks" in ARGS),
pages = [
"Documentation" => "index.md",
],
)
deploydocs(
repo = "github.com/LCSB-BioCore/SBML.jl.git",
target = "build",
branch = "gh-pages",
devbranch = "develop",
versions = "stable" => "v^",
)
# SBML.jl — load systems biology models from SBML files
This package provides a straightforward way to load model- and
simulation-relevant information from SBML files.
The library provides a single function [`readSBML`](@ref) to load a
[`Model`](@ref):
```julia
julia> using SBML
julia> mdl = readSBML("Ec_core_flux1.xml")
Model()
julia> mdl.compartments
2-element Array{String,1}:
"Extra_organism"
"Cytosol"
```
There are several functions to help you with using the data in the usual
COBRA-style workflows, such as [`getS`](@ref):
```julia
julia> metabolites, reactions, S = getS(mdl)
julia> metabolites
77-element Array{String,1}:
"M_succoa_c"
"M_ac_c"
"M_etoh_c"
julia> S
77×77 Array{Float64,2}:
0.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
0.0 -1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 1.0 -1.0 0.0 0.0 0.0
0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 -1.0 0.0 0.0 0.0 0.0 0.0
```
## Functions
### Data structures
```@autodocs
Modules = [SBML]
Pages = ["structs.jl"]
```
### Base functions
```@autodocs
Modules = [SBML]
Pages = ["version.jl", "readsbml.jl"]
```
## Data helpers
```@autodocs
Modules = [SBML]
Pages = ["utils.jl"]
```
module SBML
using SBML_jll, Libdl, Pkg
include("structs.jl")
include("version.jl")
include("readsbml.jl")
include("utils.jl")
sbml = (sym::Symbol) -> dlsym(SBML_jll.libsbml_handle, sym)
export SBMLVersion,
readSBML, Model, UnitPart, Species, Reaction, getS, getLBs, getUBs, getOCs
end # module
const VPtr = Ptr{Cvoid}
"""
function readSBML(fn::String)::Model
Read the SBML from a XML file in `fn` and return the contained `Model`.
"""
function readSBML(fn::String)::Model
doc = ccall(sbml(:readSBML), VPtr, (Cstring,), fn)
try
n_errs = ccall(sbml(:SBMLDocument_getNumErrors), Cuint, (VPtr,), doc)
if n_errs > 0
@error "SBML loading failed"
throw(:IOError)
end
if 0 == ccall(sbml(:SBMLDocument_isSetModel), Cint, (VPtr,), doc)
@error "SBML document does not contain a model"
throw(:ValueError)
end
model = ccall(sbml(:SBMLDocument_getModel), VPtr, (VPtr,), doc)
return extractModel(model)
finally
ccall(sbml(:SBMLDocument_free), Nothing, (VPtr,), doc)
end
end
function extractModel(mdl::VPtr)::Model
units = Dict{String,Vector{UnitPart}}()
for i = 0:ccall(sbml(:Model_getNumUnitDefinitions), Cuint, (VPtr,), mdl)-1
ud = ccall(sbml(:Model_getUnitDefinition), VPtr, (VPtr, Cuint), mdl, i)
id = unsafe_string(ccall(sbml(:UnitDefinition_getId), Cstring, (VPtr,), ud))
units[id] = [
begin
u = ccall(sbml(:UnitDefinition_getUnit), VPtr, (VPtr, Cuint), ud, j)
UnitPart(
unsafe_string(
ccall(
sbml(:UnitKind_toString),
Cstring,
(Cint,),
ccall(sbml(:Unit_getKind), Cint, (VPtr,), u),
),
),
ccall(sbml(:Unit_getExponent), Cint, (VPtr,), u),
ccall(sbml(:Unit_getScale), Cint, (VPtr,), u),
ccall(sbml(:Unit_getMultiplier), Cdouble, (VPtr,), u),
)
end for j = 0:ccall(sbml(:UnitDefinition_getNumUnits), Cuint, (VPtr,), ud)-1
]
end
compartments = [
unsafe_string(
ccall(
sbml(:Compartment_getId),
Cstring,
(VPtr,),
ccall(sbml(:Model_getCompartment), VPtr, (VPtr, Cuint), mdl, i),
),
) for i = 0:ccall(sbml(:Model_getNumCompartments), Cuint, (VPtr,), mdl)-1
]
species = Dict{String,Species}()
for i = 0:ccall(sbml(:Model_getNumSpecies), Cuint, (VPtr,), mdl)-1
sp = ccall(sbml(:Model_getSpecies), VPtr, (VPtr, Cuint), mdl, i)
species[unsafe_string(ccall(sbml(:Species_getId), Cstring, (VPtr,), sp))] = Species(
unsafe_string(ccall(sbml(:Species_getName), Cstring, (VPtr,), sp)),
unsafe_string(ccall(sbml(:Species_getCompartment), Cstring, (VPtr,), sp)),
)
end
reactions = Dict{String,Reaction}()
for i = 0:ccall(sbml(:Model_getNumReactions), Cuint, (VPtr,), mdl)-1
re = ccall(sbml(:Model_getReaction), VPtr, (VPtr, Cuint), mdl, i)
kl = ccall(sbml(:Reaction_getKineticLaw), VPtr, (VPtr,), re)
lb = (-Inf, "")
ub = (Inf, "")
oc = 0.0
for j = 0:ccall(sbml(:KineticLaw_getNumParameters), Cuint, (VPtr,), kl)-1
p = ccall(sbml(:KineticLaw_getParameter), VPtr, (VPtr, Cuint), kl, j)
id = unsafe_string(ccall(sbml(:Parameter_getId), Cstring, (VPtr,), p))
pval = () -> ccall(sbml(:Parameter_getValue), Cdouble, (VPtr,), p)
punit =
() -> unsafe_string(ccall(sbml(:Parameter_getUnits), Cstring, (VPtr,), p))
if id == "LOWER_BOUND"
lb = (pval(), punit())
elseif id == "UPPER_BOUND"
ub = (pval(), punit())
elseif id == "OBJECTIVE_COEFFICIENT"
oc = pval()
end
end
stoi = Dict{String,Float64}()
add_stoi =
(sr, factor) ->
stoi[unsafe_string(
ccall(sbml(:SpeciesReference_getSpecies), Cstring, (VPtr,), sr),
)] =
ccall(sbml(:SpeciesReference_getStoichiometry), Cdouble, (VPtr,), sr) *
factor
for j = 0:ccall(sbml(:Reaction_getNumReactants), Cuint, (VPtr,), re)-1
sr = ccall(sbml(:Reaction_getReactant), VPtr, (VPtr, Cuint), re, j)
add_stoi(sr, -1)
end
for j = 0:ccall(sbml(:Reaction_getNumProducts), Cuint, (VPtr,), re)-1
sr = ccall(sbml(:Reaction_getProduct), VPtr, (VPtr, Cuint), re, j)
add_stoi(sr, 1)
end
reactions[unsafe_string(ccall(sbml(:Reaction_getId), Cstring, (VPtr,), re))] =
Reaction(stoi, lb, ub, oc)
end
return Model(units, compartments, species, reactions)
end
"""
Part of a measurement unit definition that corresponds to the SBML definition of `Unit`. For example, "per square megahour", Mh^(-2), is written as:
UnitPart("second", # base unit of time
-2, # exponent, says "per square"
6, # scale in powers of 10, says "mega"
1/3600) # second-to-hour multiplier
"""
struct UnitPart
kind::String
exponent::Int
scale::Int
multiplier::Float64
UnitPart(k, e, s, m) = new(k, e, s, m)
end
"""
Reaction with stoichiometry that assigns reactants and products their relative
consumption/production rates, lower/upper bounds (in tuples with unit names),
and objective coefficient.
"""
struct Reaction
stoichiometry::Dict{String,Float64}
lb::Tuple{Float64,String}
ub::Tuple{Float64,String}
oc::Float64
Reaction(s, l, u, o) = new(s, l, u, o)
end
"""
Species metadata -- human-readable name and compartment identifier
"""
struct Species
name::String
compartment::String
Species(n, c) = new(n, c)
end
"""
Structure that collects the model-related data. Dictionaries are indexed by
identifiers of the corresponding objects.
"""
struct Model
units::Dict{String,Vector{UnitPart}}
compartments::Vector{String}
species::Dict{String,Species}
reactions::Dict{String,Reaction}
Model(u, c, s, r) = new(u, c, s, r)
end
"""
function getS(m::Model)::Tuple{Vector{String},Vector{String},Matrix{Float64}}
Extract the vector of species (aka metabolite) identifiers, vector of reaction
identifiers, and the (dense) stoichiometry matrix from an existing `Model`.
Returns a tuple with these values.
"""
function getS(m::Model)::Tuple{Vector{String},Vector{String},Matrix{Float64}}
#TODO this will need a sparse version and faster row ID lookup
rows = [k for k in keys(m.species)] #TODO this too
cols = [k for k in keys(m.reactions)]
S = zeros(Float64, length(rows), length(cols))
for ri = 1:length(cols)
stoi = m.reactions[cols[ri]].stoichiometry
S[indexin(keys(stoi), rows), ri] .= values(stoi)
end
return rows, cols, S
end
"""
function getLBs(m::Model)::Vector{Tuple{Float64,String}}
Extract a vector of lower bounds of reaction rates from the model. All bounds
are accompanied with the unit of the corresponding value (this behavior is
based on SBML specification).
"""
function getLBs(m::Model)::Vector{Tuple{Float64,String}}
return broadcast(x -> x.lb, values(m.reactions))
end
"""
function getUBs(m::Model)::Vector{Tuple{Float64,String}}
Likewise to `getLBs`, extract the upper bounds.
"""
function getUBs(m::Model)::Vector{Tuple{Float64,String}}
return broadcast(x -> x.ub, values(m.reactions))
end
"""
function getOCs(m::Model)::Vector{Float64}
Extract the vector of objective coefficients of each reaction.
"""
function getOCs(m::Model)::Vector{Float64}
return broadcast(x -> x.oc, values(m.reactions))
end
"""
function SBMLVersion()
Get the version of the used SBML library in Julia version format.
"""
function SBMLVersion()::VersionNumber
VersionNumber(unsafe_string(ccall(sbml(:getLibSBMLDottedVersion), Cstring, ())))
end
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment