Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,17 @@ result.colnames # column names
result.data # retrieved data
```

The vector forms of `kegg_conv`, `kegg_get`, `kegg_link`, and `kegg_list` send
at most 10 entries per request. Set `request_delay` to control the pause between
requests:

```julia
entries = ["hsa:$id" for id in 10458:10468]
result = kegg_get(entries; request_delay = 0.5)
```

The old `timeout` keyword remains available as a deprecated alias.

## Documentation

- [Getting started](https://cvigilv.github.io/KEGGAPI.jl/dev/man/getting-started/)
Expand Down
6 changes: 3 additions & 3 deletions benchmarking/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,9 @@ have no bar for it in the figure. The `conv` case uses `ncbi-geneid` rather than
`ncbi-proteinid` because Bio.KEGG.REST only recognises the legacy outside-database
names (`ncbi-gi | ncbi-geneid | uniprot`) and rejects the newer ones.

`KEGGAPI.jl`'s chunked `kegg_get` sleeps internally to respect KEGG's rate limit;
the Julia runner passes `timeout = 0.0` so that deliberate delay is not counted
as work, since the runner already spaces its own calls.
`KEGGAPI.jl`'s chunked `kegg_get` waits between requests to respect KEGG's rate
limit. The Julia runner passes `request_delay = 0.0` because the runner already
spaces its own calls and should not include that delay in its timings.

Each interface runs every operation inside a **single** process, so what is
measured is per-call time rather than interpreter startup. A warm-up call is
Expand Down
10 changes: 3 additions & 7 deletions benchmarking/runners/bench_julia.jl
Original file line number Diff line number Diff line change
@@ -1,17 +1,13 @@
# Julia runner: times KEGGAPI.jl calls and prints one CSV row per replicate.
# Usage: julia --project=. runners/bench_julia.jl <nreps> <sleep_seconds>
using KEGGAPI
using Logging

const NREPS = length(ARGS) >= 1 ? parse(Int, ARGS[1]) : 5
const PAUSE = length(ARGS) >= 2 ? parse(Float64, ARGS[2]) : 0.4

# The chunked `kegg_get` methods sleep internally to respect KEGG's rate limit.
# This runner already spaces its own calls, so that sleep is disabled here to
# measure the actual request/parse work; the resulting @warn is silenced.
get_entry(args...) = with_logger(NullLogger()) do
KEGGAPI.kegg_get(args...; timeout = 0.0)
end
# This runner already spaces its calls, so disable the internal batching delay
# to measure request and parsing work only.
get_entry(args...) = KEGGAPI.kegg_get(args...; request_delay = 0.0)

# (label, thunk) pairs -- keep in sync with the other runners.
const CASES = [
Expand Down
40 changes: 30 additions & 10 deletions src/Conv.jl
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@ Convert KEGG identifiers to/from outside identifiers.
```julia
using KEGGAPI

KEGGAPI.conv("eco", "ncbi-geneid")
KEGGAPI.conv("ncbi-geneid", "eco")
KEGGAPI.conv("genes", "ncbi-geneid:948364")
KEGGAPI.kegg_conv("eco", "ncbi-geneid")
KEGGAPI.kegg_conv("ncbi-geneid", "eco")
KEGGAPI.kegg_conv("genes", "ncbi-geneid:948364")
```

# Extended help
Expand All @@ -37,7 +37,7 @@ end


"""
kegg_conv(target_db::String, dbentries::Vector{String}; [timeout::Float64 = 0.4])
kegg_conv(target_db::String, dbentries::Vector{String}; request_delay::Real = 0.4, timeout = nothing)

Convert KEGG identifiers to/from outside identifiers.

Expand All @@ -55,27 +55,47 @@ For chemical substance identifiers:
# Arguments
- `target_db::String`: Target database
- `dbentries::Vector{String}`: Database entries of the available databases
- `timeout::Float64`: Time to wait between requests (default: 0.4 seconds)
- `request_delay::Real`: Seconds to wait between batched requests. Defaults to
0.4. No delay occurs when the input fits in one request.
- `timeout::Real`: Deprecated alias for `request_delay`. If both keywords are
supplied, their values must be equal.

# Throws
- `ArgumentError`: If a delay is negative or non-finite, or if `request_delay`
and `timeout` conflict.

# Examples
```julia
using KEGGAPI

KEGGAPI.conv("ncbi-proteinid", ["hsa:10458", "ece:Z5100"])
KEGGAPI.kegg_conv("ncbi-proteinid", ["hsa:10458", "ece:Z5100"])
```
"""
function kegg_conv(target_db::String, dbentries::Vector{String}; timeout::Float64 = 0.4)
function kegg_conv(
target_db::String, dbentries::Vector{String};
request_delay::Union{Nothing, Real} = nothing,
timeout::Union{Nothing, Real} = nothing,
)
return _kegg_conv(target_db, dbentries, request, sleep; request_delay, timeout)
end

function _kegg_conv(
target_db::String, dbentries::Vector{String}, requester::F, sleep_function::S;
request_delay::Union{Nothing, Real} = nothing,
timeout::Union{Nothing, Real} = nothing,
) where {F, S}
request_count = cld(length(dbentries), KEGG_BATCH_SIZE)
delay = resolve_request_delay(request_delay, timeout, :kegg_conv, request_count)
urls = String[]
data = []
for chunk in partition(dbentries, 10)
foreach_request_batch(dbentries, delay, sleep_function) do chunk
url = "https://rest.kegg.jp/conv/$(target_db)/$(join(chunk, "+"))"
push!(urls, url)
response_text = request(url)
response_text = requester(url)
for datum in eachline(IOBuffer(response_text))
id, d = split(datum, '\t') .|> String
push!(data, [id, d])
end
sleep(timeout)
end
return KeggTupleList(urls, ["source", target_db], data)
end
43 changes: 31 additions & 12 deletions src/Get.jl
Original file line number Diff line number Diff line change
Expand Up @@ -67,8 +67,8 @@ end

# ---------------------------------------------------------------------------- Main function
"""
kegg_get(dbentries::Vector{String}, option::Union{Symbol, Nothing} = nothing; timeout::Float64 = 0.4)
kegg_get(dbentry::String, args...; kwargs...)
kegg_get(dbentries::Vector{String}, option::Union{Symbol, Nothing} = nothing; request_delay::Real = 0.4, timeout = nothing)
kegg_get(dbentry::String, option::Union{Symbol, Nothing} = nothing; request_delay::Real = 0.4, timeout = nothing)

Retrieve given database entries.

Expand All @@ -89,8 +89,14 @@ Allowed `option` for retrieval of selected fields:
- `dbentries::Vector{String}`: A vector of KEGG database entries to retrieve.
- `option::Union{Symbol, Nothing}`: An optional symbol specifying the format of the
retrieved data. If `nothing`, the default format is used.
- `timeout::Float64`: A float specifying the time to wait between API requests when retrieving
more than 10 entries. Default is 0.4 seconds.
- `request_delay::Real`: Seconds to wait between batched requests. Defaults to
0.4. No delay occurs when the input fits in one request.
- `timeout::Real`: Deprecated alias for `request_delay`. If both keywords are
supplied, their values must be equal.

# Throws
- `ArgumentError`: If a delay is negative or non-finite, or if `request_delay`
and `timeout` conflict.

# Returns
A tuple containing:
Expand All @@ -110,9 +116,10 @@ urls, data = kegg_get(dbentries, option)
This operation retrieves given database entries in a flat file format or in other
formats with `option`. Flat file formats are available for all KEGG databases
except brite. The input is limited up to 10 entries; if more are provided the
query will be split into chunks of 10 entries and multiple requests will be made
with a `timeout` between each request (KEGG API indicates that the maximum API
calls per seconds is 3, so a default timeout of 0.4 seconds is set to ensure that).
query is split into chunks of 10 entries. The function waits `request_delay`
seconds between requests, but does not wait after the final request. The default
of 0.4 seconds keeps batched calls below KEGG's limit of three requests per
second.

Options allow retrieval of selected fields, including sequence data from genes
entries, chemical structure data or GIF image files from compound, glycan and
Expand All @@ -127,23 +134,35 @@ and to **one pathway entry with the `:image`, `:image2x` or `:kgml` option**.
- https://www.kegg.jp/kegg/rest/keggapi.html#get

"""
function kegg_get(dbentries::Vector{String}, option::Union{Symbol, Nothing} = nothing; timeout::Float64 = 0.4)
function kegg_get(
dbentries::Vector{String}, option::Union{Symbol, Nothing} = nothing;
request_delay::Union{Nothing, Real} = nothing,
timeout::Union{Nothing, Real} = nothing,
)
return _kegg_get(dbentries, option, request, sleep; request_delay, timeout)
end

function _kegg_get(
dbentries::Vector{String}, option::Union{Symbol, Nothing}, requester::F,
sleep_function::S; request_delay::Union{Nothing, Real} = nothing,
timeout::Union{Nothing, Real} = nothing,
) where {F, S}
validate_get_option(option)
timeout < 0.334 && @warn "KEGG API accepts 3 requests per second. Current timeout may lead to API rate limit errors."
request_count = cld(length(dbentries), KEGG_BATCH_SIZE)
delay = resolve_request_delay(request_delay, timeout, :kegg_get, request_count)
length(dbentries) > 1 && option == :image && @warn "Using the :image option with kegg_get is limited to one compound/glycan/drug entry"

urls = String[]
data = []
processor = get_response_processor(option)

for chunk in partition(dbentries, 10)
foreach_request_batch(dbentries, delay, sleep_function) do chunk
url = build_kegg_url(chunk, option)
push!(urls, url)
response_text = option in KEGGAPI_GET_BINARY_OPTIONS ? request(url, Vector{UInt8}) : request(url)
response_text = option in KEGGAPI_GET_BINARY_OPTIONS ? requester(url, Vector{UInt8}) : requester(url)
for datum in processor(response_text)
push!(data, datum)
end
sleep(timeout)
end

return (url = urls, data = data)
Expand Down
2 changes: 1 addition & 1 deletion src/KEGGAPI.jl
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
module KEGGAPI

import HTTP: get
import .Iterators: partition

include("utils.jl")
include("Conv.jl")
include("Ddi.jl")
include("Find.jl")
Expand Down
35 changes: 29 additions & 6 deletions src/Link.jl
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ function kegg_link(target_db::String, source_db::String, option::String = "")
end

"""
kegg_link(target_db::String, dbentries::Vector{String}, option::String = ""; [timeout::Float64 = 0.4])
kegg_link(target_db::String, dbentries::Vector{String}, option::String = ""; request_delay::Real = 0.4, timeout = nothing)

Find related entries by using database cross-references.

Expand All @@ -76,19 +76,43 @@ and the available external databases are:
(`species | genus | family | order | class | phylum`) for `genome`/`taxonomy`
links, or an RDF output format (`turtle | n-triple`) for the `drug`/`atc`/`jtc`
databases (in which case the raw response text is returned).
- `timeout::Float64`, time to wait between requests (default: 0.4 seconds)
- `request_delay::Real`, seconds to wait between batched requests. Defaults to
0.4. No delay occurs when the input fits in one request.
- `timeout::Real`, deprecated alias for `request_delay`. If both keywords are
supplied, their values must be equal.

# Throws
- `ArgumentError`: If a delay is negative or non-finite, or if `request_delay`
and `timeout` conflict.

The vector form sends at most 10 entries per request. It waits `request_delay`
seconds between requests, but does not wait after the final request.
"""
function kegg_link(target_db::String, dbentries::Vector{String}, option::String = ""; timeout::Float64 = 0.4)
function kegg_link(
target_db::String, dbentries::Vector{String}, option::String = "";
request_delay::Union{Nothing, Real} = nothing,
timeout::Union{Nothing, Real} = nothing,
)
return _kegg_link(target_db, dbentries, option, request, sleep; request_delay, timeout)
end

function _kegg_link(
target_db::String, dbentries::Vector{String}, option::String, requester::F,
sleep_function::S; request_delay::Union{Nothing, Real} = nothing,
timeout::Union{Nothing, Real} = nothing,
) where {F, S}
option_str = isempty(option) ? "" : "/$option"
is_rdf = option in KEGG_LINK_RDF_OPTIONS
request_count = cld(length(dbentries), KEGG_BATCH_SIZE)
delay = resolve_request_delay(request_delay, timeout, :kegg_link, request_count)

urls = String[]
data = []
rdf_text = ""
for chunk in partition(dbentries, 10)
foreach_request_batch(dbentries, delay, sleep_function) do chunk
url = "https://rest.kegg.jp/link/$(target_db)/$(join(chunk, "+"))$option_str"
push!(urls, url)
response_text = request(url)
response_text = requester(url)
if is_rdf
rdf_text *= response_text
else
Expand All @@ -97,7 +121,6 @@ function kegg_link(target_db::String, dbentries::Vector{String}, option::String
push!(data, [id, d])
end
end
sleep(timeout)
end

is_rdf && return rdf_text
Expand Down
38 changes: 29 additions & 9 deletions src/List.jl
Original file line number Diff line number Diff line change
Expand Up @@ -47,33 +47,53 @@ function _kegg_list(query::String, query_type::String, request_function::F) wher
end

"""
kegg_list(dbentries::Vector{String}; timeout::Float64 = 0.4) -> KeggTupleList
kegg_list(dbentries::Vector{String}; request_delay::Real = 0.4, timeout = nothing) -> KeggTupleList

Get a list of entry identifiers and associated names

# Arguments
- `dbentries::Vector{String}`: The list of entries to list.
- `request_delay::Real`: Seconds to wait between batched requests. Defaults to
0.4. No delay occurs when the input fits in one request.
- `timeout::Real`: Deprecated alias for `request_delay`. If both keywords are
supplied, their values must be equal.

# Throws
- `ArgumentError`: If a delay is negative or non-finite, or if `request_delay`
and `timeout` conflict.

# Returns
- `data::KeggTupleList`: A data structure containing the `url`, the `data` retrieved,
and the `columns` names for the data.

# Extended help

The input is limited up to 10 entries; if more are provided the query will be
split into chunks of 10 entries and multiple requests will be made with a `timeout`
between each request (KEGG API indicates that the maximum API calls per seconds
is 3, so a default timeout of 0.4 seconds is set to ensure that).
The input is limited to 10 entries per request. Larger inputs are split into
batches, with `request_delay` seconds between requests and no wait after the
final request. The default of 0.4 seconds keeps batched calls below KEGG's limit
of three requests per second.
"""
function kegg_list(dbentries::Vector{String}; timeout::Float64 = 0.4)
function kegg_list(
dbentries::Vector{String}; request_delay::Union{Nothing, Real} = nothing,
timeout::Union{Nothing, Real} = nothing,
)
return _kegg_list(dbentries, request, sleep; request_delay, timeout)
end

function _kegg_list(
dbentries::Vector{String}, requester::F, sleep_function::S;
request_delay::Union{Nothing, Real} = nothing,
timeout::Union{Nothing, Real} = nothing,
) where {F, S}
request_count = cld(length(dbentries), KEGG_BATCH_SIZE)
delay = resolve_request_delay(request_delay, timeout, :kegg_list, request_count)
urls = String[]
data = []
for chunk in partition(dbentries, 10)
foreach_request_batch(dbentries, delay, sleep_function) do chunk
url = "https://rest.kegg.jp/list/$(join(chunk, "+"))"
push!(urls, url)
response_text = request(url)
response_text = requester(url)
append!(data, list_parser(response_text, url).data)
sleep(timeout)
end
colnames = inferred_list_colnames(data)
return KeggTupleList(urls, colnames, data)
Expand Down
40 changes: 40 additions & 0 deletions src/utils.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
const DEFAULT_REQUEST_DELAY = 0.4
const KEGG_REQUEST_INTERVAL = 1 / 3
const KEGG_BATCH_SIZE = 10

function resolve_request_delay(
request_delay::Union{Nothing, Real}, timeout::Union{Nothing, Real},
function_name::Symbol, request_count::Int,
)
for delay in (request_delay, timeout)
if !isnothing(delay) && (!isfinite(delay) || delay < 0)
throw(ArgumentError("request delays must be finite and nonnegative"))
end
end

if !isnothing(request_delay) && !isnothing(timeout) && request_delay != timeout
throw(ArgumentError("request_delay and the deprecated timeout alias must be equal when both are supplied"))
end

if !isnothing(timeout)
Base.depwarn("The timeout keyword is deprecated; use request_delay instead.", function_name)
end

delay = something(request_delay, timeout, DEFAULT_REQUEST_DELAY)
if request_count > 1 && delay < KEGG_REQUEST_INTERVAL
@warn "KEGG allows at most three requests per second. A request_delay below one third of a second may cause rate-limit errors."
end
return delay
end

function foreach_request_batch(
f::F, dbentries::AbstractVector{String}, request_delay::Real,
sleep_function::S,
) where {F, S}
request_count = cld(length(dbentries), KEGG_BATCH_SIZE)
for (request_index, chunk) in enumerate(Iterators.partition(dbentries, KEGG_BATCH_SIZE))
f(chunk)
request_index < request_count && sleep_function(request_delay)
end
return nothing
end
2 changes: 2 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
using KEGGAPI
using Test

include("test_batching.jl")
include("test_list.jl")
include("test_requests.jl")
include("test_utils.jl")
Loading
Loading